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);
Related
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 am new, and I am making an app that displays data in a cardView within a recyclerView in android studio. I am trying to be able to delete the data that is displayed on the cardView. The cardView and data gets deleted as it should, but once I go back to the activity holding the cardView and recyclerView, it's all still there. Does anyone know why this is happening? I'll post my code below
ReminderDBHelper:
package com.example.lasttry;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
private Context context;
private ArrayList reminder_id, reminder_title, reminder_location, reminder_medication;
reminderDBHelper mydb;
Button reminderDelete;
CustomAdapter(Context context,
ArrayList reminder_id,
ArrayList reminder_title,
ArrayList reminder_location,
ArrayList reminder_medication) {
this.context = context;
this.reminder_id = reminder_id;
this.reminder_title = reminder_title;
this.reminder_location = reminder_location;
this.reminder_medication = reminder_medication;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.my_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
holder.reminder_id.setText(String.valueOf(reminder_id.get(position)));
holder.reminder_title.setText(String.valueOf(reminder_title.get(position)));
holder.reminder_location.setText(String.valueOf(reminder_location.get(position)));
holder.reminder_medication.setText(String.valueOf(reminder_medication.get(position)));
holder.reminderDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mydb = new reminderDBHelper(context);
String id = String.valueOf(reminder_id);
mydb.deleteData(id);
reminder_id.remove(holder.getAdapterPosition());
notifyItemRemoved(holder.getLayoutPosition());
}
});
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, UpdateActivity.class);
intent.putExtra("id", String.valueOf(reminder_id.get(holder.getAdapterPosition())));
intent.putExtra("title", String.valueOf(reminder_title.get(holder.getAdapterPosition())));
intent.putExtra("location", String.valueOf(reminder_location.get(holder.getAdapterPosition())));
intent.putExtra("medication", String.valueOf(reminder_medication.get(holder.getAdapterPosition())));
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return reminder_id.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView reminder_id, reminder_title, reminder_location, reminder_medication;
Button reminderDelete;
LinearLayout mainLayout;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
reminderDelete = itemView.findViewById(R.id.reminder_delete);
reminder_id = itemView.findViewById(R.id.reminder_id);
reminder_title = itemView.findViewById(R.id.reminder_title);
reminder_location = itemView.findViewById(R.id.reminder_location);
reminder_medication = itemView.findViewById(R.id.reminder_medication);
mainLayout = itemView.findViewById(R.id.mainLayout);
}
}
}
CustomAdapter:
package com.example.lasttry;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
private Context context;
private ArrayList reminder_id, reminder_title, reminder_location, reminder_medication;
reminderDBHelper mydb;
Button reminderDelete;
CustomAdapter(Context context,
ArrayList reminder_id,
ArrayList reminder_title,
ArrayList reminder_location,
ArrayList reminder_medication) {
this.context = context;
this.reminder_id = reminder_id;
this.reminder_title = reminder_title;
this.reminder_location = reminder_location;
this.reminder_medication = reminder_medication;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.my_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
holder.reminder_id.setText(String.valueOf(reminder_id.get(position)));
holder.reminder_title.setText(String.valueOf(reminder_title.get(position)));
holder.reminder_location.setText(String.valueOf(reminder_location.get(position)));
holder.reminder_medication.setText(String.valueOf(reminder_medication.get(position)));
holder.reminderDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mydb = new reminderDBHelper(context);
String id = String.valueOf(reminder_id);
mydb.deleteData(id);
reminder_id.remove(holder.getAdapterPosition());
notifyItemRemoved(holder.getLayoutPosition());
}
});
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, UpdateActivity.class);
intent.putExtra("id", String.valueOf(reminder_id.get(holder.getAdapterPosition())));
intent.putExtra("title", String.valueOf(reminder_title.get(holder.getAdapterPosition())));
intent.putExtra("location", String.valueOf(reminder_location.get(holder.getAdapterPosition())));
intent.putExtra("medication", String.valueOf(reminder_medication.get(holder.getAdapterPosition())));
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return reminder_id.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView reminder_id, reminder_title, reminder_location, reminder_medication;
Button reminderDelete;
LinearLayout mainLayout;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
reminderDelete = itemView.findViewById(R.id.reminder_delete);
reminder_id = itemView.findViewById(R.id.reminder_id);
reminder_title = itemView.findViewById(R.id.reminder_title);
reminder_location = itemView.findViewById(R.id.reminder_location);
reminder_medication = itemView.findViewById(R.id.reminder_medication);
mainLayout = itemView.findViewById(R.id.mainLayout);
}
}
}
I have searched stackOverflow and reddit, but nothing seems to work. I have tried making the array array list instead.
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.
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());
Have an apparently simple task of -
Display a list of items using recycler view and each item should be card view.On click of any item new screen should open which shows detail of that item.
I already have seen various questions posted on the same topic, I would appreciate a little help on the attempt ive made rather than redirecting me there, since I'm pretty new and unable to understand how exactly to implement just by seeing those answers.I have tried to follow a tutorial closely but clearly have failed in replicating the results.HERE ARE THE FILES
MainActivity.java
. package com.example.hardikvats.recylerviewdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private String[] phones={"MotoX","Nokia Asha","Lumia 710","Iphone 7s"};
private String[] OperatingSytem={"Android","Symbian","Windows","Ios"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RecyclerView recyclerView= (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
MyAdapter adapter=new MyAdapter(this,phones);
recyclerView.setAdapter(adapter);
}
}
MyAdapter.java
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Hardik Vats on 20-Jan-17.
*/
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
Context c;
String[] phones;
String[] OperatingSystem;
//CONSTRUCTOR
public MyAdapter(Context c, String[] PhoneModel){
this.c=c;
this.phones=PhoneModel;
//this.OperatingSystem=OperatingSystem;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//INFLATING FROM XML TO JAVA VIEW
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.model,null);
MyHolder holder=new MyHolder(v);
return holder;
}
#Override
public void onBindViewHolder(MyHolder holder, int position) {
holder.PhoneModel.setText(phones[position]);
holder.setItemClickListner(new ItemClickListner() {
#Override
public void onItemClick(View v, int position) {
Intent i=new Intent(c,DetailActivity.class);
i.putExtra("OS name",OperatingSystem[position]);
}
});
}
#Override
public int getItemCount() {
return phones.length;
}
}
MyHolder.java
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
/**
* Created by Hardik Vats on 20-Jan-17.
*/
public class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView PhoneModel;
ItemClickListner icl;
public MyHolder(View itemView) {
super(itemView);
PhoneModel=(TextView) itemView.findViewById(R.id.MobilePhone);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
this.icl.onItemClick(v,getLayoutPosition());
}
public void setItemClickListner(ItemClickListner itemClickListner){
this.icl=itemClickListner;
}
}
DetailActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class DetailActivity extends AppCompatActivity {
TextView OperatingSystem;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail2);
Intent i=getIntent();
final String OperatingSystem =i.getExtras().getString("Operating System");
}
}
ItemClickListner.java(Interface)
`import android.view.View;
/**
* Created by Hardik Vats on 20-Jan-17.
*/
public interface ItemClickListner {
void onItemClick(View v, int position);
}`
The goal is to click each list item from phones array and get an activity listing the OS in a new activity in a new textfield
after i.putExtra("OS NAME ....
add this line
c.startActivity(c,DetailActivity.class);
As you did, in order that changes to be small, try this:
holder.PhoneModel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(c,DetailActivity.class);
i.putExtra("OS name",OperatingSystem[holder.getAdapterPosition()]);
}
});
Holder will always retain your position.
//set on item click listener like this
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Toast.makeText(MainActivity.this, "Card at " + position + " is clicked", Toast.LENGTH_SHORT).show();
// here you can start your detail Activity
Intent i=new Intent(c,DetailActivity.class);
i.putExtra("OS name",OperatingSystem[position]);
c.startActivity(i);
}
}));
// here is the on item click listener class
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
GestureDetector mGestureDetector;
public interface OnItemClickListener{
public void onItemClick(View view, int position);
}
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View childView = rv.findChildViewUnder(e.getX(),e.getY());
if(childView != null && mListener != null && mGestureDetector.onTouchEvent(e)){
mListener.onItemClick(childView, rv.getChildAdapterPosition(childView));
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override`enter code here`
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}