Issue
I want the user number to be called and recalled through Recycler View and Model Data
In the adapter, I used the following code but it gives an error
Code in adapter:
holder.call.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
String number=model.getNumber();
String call="tel:"+number.trim();
Intent intent=new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(call));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
error: enter image description here
source code:
public class Adapter extends RecyclerView.Adapter<Adapter.Holder> {
Context context;
List<Model> models=new ArrayList<>();
ModelListener modelListener;
public Adapter(ModelListener modelListener) {
this.modelListener = modelListener;
}
@NonNull
@Override
public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.page_item,parent,false);
return new Holder(view);
}
@Override
public void onBindViewHolder(@NonNull Holder holder, int position) {
Model model=models.get(position);
holder.name.setText(model.getName());
holder.number.setText(model.getNumber());
holder.call.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String number = model.getNumber();
final Uri numberToCall = Uri.parse("tel:" + number);
final Intent intent = new Intent(Intent.ACTION_DIAL, numberToCall);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return models.size();
}
public class Holder extends RecyclerView.ViewHolder{
TextView name,number;
ImageView delete,edit,call;
public Holder(@NonNull View itemView) {
super(itemView);
name=itemView.findViewById(R.id.txt_name);
number=itemView.findViewById(R.id.txt_number);
call=itemView.findViewById(R.id.call);
}
}
}
Solution
You need to use requireContext()
to avoid from null
.
holder.call.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String number = model.getNumber();
final Uri numberToCall = Uri.parse("tel:" + number);
final Intent intent = new Intent(Intent.ACTION_DIAL, numberToCall);
context.startActivity(intent); //Use back context
}
UPDATE:
Add one more parameter for Context
.
public Adapter(ModelListener modelListener, Context context) {
this.modelListener = modelListener;
this.context = context;
}
When you call your adapter
, you pass the value context
. Maybe you will have something like this.
final Adapter mAdapter = new Adapter(modelListener, this);
Answered By - Ticherhaz FreePalestine
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.