my adapter of recycler view returning null - java

I am trying to use a RecyclerView with an adapter to call a specific
person. In the adapter I am using a call button and taking a reference from
PlaceCallActivity. The problem is that PlaceCallActivity is
using the above values which I can't access from the adapter. Thanks in advance for your help.
My PlaceCallActivity:
package techheromanish.example.com.videochatapp;
import com.sinch.android.rtc.calling.Call;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class PlaceCallActivity extends BaseActivity {
private Button mCallButton;
private EditText mCallName;
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<ListItem> listItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainn);
//initializing UI elements
//mCallName = (EditText) findViewById(R.id.callName);
mCallButton = (Button) findViewById(R.id.callButton);
//mCallButton.setEnabled(false);
//mCallButton.setOnClickListener(buttonClickListener);
Button stopButton = (Button) findViewById(R.id.stopButton);
stopButton.setOnClickListener(buttonClickListener);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
// loadRecyclerViewData();
ListItem listItem = new ListItem(
R.drawable.user,
"Jawad",
"Android Developer");
listItems.add(listItem);
ListItem listItem1 = new ListItem(
R.drawable.user,
"Malik",
"Developer");
listItems.add(listItem1);
adapter = new MyAdapter(listItems, this);
recyclerView.setAdapter(adapter);
}
// invoked when the connection with SinchServer is established
#Override
protected void onServiceConnected() {
TextView userName = (TextView) findViewById(R.id.loggedInName);
userName.setText(getSinchServiceInterface().getUserName());
//mCallButton.setEnabled(true);
}
#Override
public void onDestroy() {
if (getSinchServiceInterface() != null) {
getSinchServiceInterface().stopClient();
}
super.onDestroy();
}
//to kill the current session of SinchService
private void stopButtonClicked() {
if (getSinchServiceInterface() != null) {
getSinchServiceInterface().stopClient();
}
finish();
}
//to place the call to the entered name
public void callButtonClicked(String user) {
//String userName = mCallName.getText().toString();
if (user.isEmpty()) {
Toast.makeText(this, "Please enter a user to call", Toast.LENGTH_LONG).show();
return;
}
Call call = getSinchServiceInterface().callUserVideo(user);
String callId = call.getCallId();
Intent callScreen = new Intent(this, CallScreenActivity.class);
callScreen.putExtra(SinchService.CALL_ID, callId);
startActivity(callScreen);
}
private OnClickListener buttonClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.callButton:
String str = MyAdapter.getStr();
Toast.makeText(PlaceCallActivity.this, "" + str, Toast.LENGTH_SHORT).show();
//callButtonClicked(str);
break;
case R.id.stopButton:
stopButtonClicked();
break;
}
}
};
}
and MyAdapter Class:
package techheromanish.example.com.videochatapp;
import android.content.Context;
import android.support.annotation.NonNull;
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.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<ListItem> listItems;
private Context context;
private static String str;
public MyAdapter(List<ListItem> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_view, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final ListItem listItem = listItems.get(position);
holder.imageViewProfile.setImageResource(listItem.getImage());
holder.textViewName.setText(listItem.getName());
holder.textViewBio.setText(listItem.getBio());
/*Picasso.with(context)
.load(listItem.getImageUrl())
.into(holder.imageView);
*/
// str = listItem.getName();
holder.callButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "You Clicked " + listItem.getName(), Toast.LENGTH_SHORT).show();
PlaceCallActivity placeCallActivity = new PlaceCallActivity();
placeCallActivity.callButtonClicked(listItem.getName());
}
});
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textViewName, textViewBio;
public ImageView imageViewProfile;
public Button callButton;
ViewHolder(View itemView) {
super(itemView);
textViewName = (TextView) itemView.findViewById(R.id.textViewName);
textViewBio = (TextView) itemView.findViewById(R.id.textViewBio);
imageViewProfile = (ImageView) itemView.findViewById(R.id.imageViewProfile);
callButton = (Button) itemView.findViewById(R.id.callButton);
}
}
public static String getStr() {
return str;
}
}
In this adapter I am using button to call from PlaceCallActivity.

Please change this:
private RecyclerView.Adapter adapter;
to this:
private MyAdapter adapter;

creating an instance of an activity wouldn't make it go through its lifecycle; if the declaration of the properties which are necessary to make the code run is dependent on your activity's lifecycle then calling the method on the properly initialized activity instance should solve this.
MyAdapter class:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<ListItem> listItems;
private Context context;
private PlaceCallActivity placeCallActivity;
private static String str;
public MyAdapter(List<ListItem> listItems, Context context) {
this.listItems = listItems;
this.context = context;
// this.placeCallActivity now references the parent activity instance
this.placeCallActivity=(PlaceCallActivity)context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_view, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final ListItem listItem = listItems.get(position);
holder.imageViewProfile.setImageResource(listItem.getImage());
holder.textViewName.setText(listItem.getName());
holder.textViewBio.setText(listItem.getBio());
/*Picasso.with(context)
.load(listItem.getImageUrl())
.into(holder.imageView);
*/
// str = listItem.getName();
holder.callButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "You Clicked " + listItem.getName(), Toast.LENGTH_SHORT).show();
placeCallActivity.callButtonClicked(listItem.getName());
}
});
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textViewName, textViewBio;
public ImageView imageViewProfile;
public Button callButton;
ViewHolder(View itemView) {
super(itemView);
textViewName = (TextView) itemView.findViewById(R.id.textViewName);
textViewBio = (TextView) itemView.findViewById(R.id.textViewBio);
imageViewProfile = (ImageView) itemView.findViewById(R.id.imageViewProfile);
callButton = (Button) itemView.findViewById(R.id.callButton);
}
}
public static String getStr() {
return str;
}
}

you can create an interface:
public interface CallButtonClickListener{
void onButtonClicked(String name);
}
Edit
public class PlaceCallActivity extends BaseActivity {
private Button mCallButton;
private EditText mCallName;
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<ListItem> listItems;
//new code
private CallButtonClickListener buttonListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainn);
//initializing UI elements
//mCallName = (EditText) findViewById(R.id.callName);
mCallButton = (Button) findViewById(R.id.callButton);
//mCallButton.setEnabled(false);
//mCallButton.setOnClickListener(buttonClickListener);
Button stopButton = (Button) findViewById(R.id.stopButton);
stopButton.setOnClickListener(buttonClickListener);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
// loadRecyclerViewData();
ListItem listItem = new ListItem(
R.drawable.user,
"Jawad",
"Android Developer");
listItems.add(listItem);
ListItem listItem1 = new ListItem(
R.drawable.user,
"Malik",
"Developer");
listItems.add(listItem1);
//implement the logic there
adapter = new MyAdapter(listItems, this, new CallButtonClickListener(){
#Override
public void onButtonClicked(String name){
//your code here.
}
});
recyclerView.setAdapter(adapter);
}
// invoked when the connection with SinchServer is established
#Override
protected void onServiceConnected() {
TextView userName = (TextView) findViewById(R.id.loggedInName);
userName.setText(getSinchServiceInterface().getUserName());
//mCallButton.setEnabled(true);
}
#Override
public void onDestroy() {
if (getSinchServiceInterface() != null) {
getSinchServiceInterface().stopClient();
}
super.onDestroy();
}
//to kill the current session of SinchService
private void stopButtonClicked() {
if (getSinchServiceInterface() != null) {
getSinchServiceInterface().stopClient();
}
finish();
}
//to place the call to the entered name
public void callButtonClicked(String user) {
//String userName = mCallName.getText().toString();
if (user.isEmpty()) {
Toast.makeText(this, "Please enter a user to call", Toast.LENGTH_LONG).show();
return;
}
Call call = getSinchServiceInterface().callUserVideo(user);
String callId = call.getCallId();
Intent callScreen = new Intent(this, CallScreenActivity.class);
callScreen.putExtra(SinchService.CALL_ID, callId);
startActivity(callScreen);
}
private OnClickListener buttonClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.callButton:
String str = MyAdapter.getStr();
Toast.makeText(PlaceCallActivity.this, "" + str, Toast.LENGTH_SHORT).show();
//callButtonClicked(str);
break;
case R.id.stopButton:
stopButtonClicked();
break;
}
}
};
}
Adapter
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<ListItem> listItems;
private Context context;
private static String str;
private CallButtonClickListener buttonListener;
public MyAdapter(List<ListItem> listItems, Context context, CallButtonClickListener buttonListener) {
this.listItems = listItems;
this.context = context;
this.buttonListener = buttonListner;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_view, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final ListItem listItem = listItems.get(position);
holder.imageViewProfile.setImageResource(listItem.getImage());
holder.textViewName.setText(listItem.getName());
holder.textViewBio.setText(listItem.getBio());
/*Picasso.with(context)
.load(listItem.getImageUrl())
.into(holder.imageView);
*/
// str = listItem.getName();
holder.callButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "You Clicked " + listItem.getName(), Toast.LENGTH_SHORT).show();
buttonListener.onButtonClicked(listItem.getName());
}
});
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textViewName, textViewBio;
public ImageView imageViewProfile;
public Button callButton;
ViewHolder(View itemView) {
super(itemView);
textViewName = (TextView) itemView.findViewById(R.id.textViewName);
textViewBio = (TextView) itemView.findViewById(R.id.textViewBio);
imageViewProfile = (ImageView) itemView.findViewById(R.id.imageViewProfile);
callButton = (Button) itemView.findViewById(R.id.callButton);
}
}
public static String getStr() {
return str;
}
}

Related

RecyclerView get EditText and set TextView

I want to get the data I put inside the EditText and when I press a button and I want to add the data to the TextView.
I have done everything inside the onBindViewHolder
#Override
public void onBindViewHolder(#NonNull ReyclerViewerAdapter.ViewHolder holder, int position) {
holder.btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.txtTask.setText(tasksList.get(position).getEdtTxtTask().getText().toString());
}
});
holder.edtTxtTask.setText(tasksList.get(position).getEdtTxtTask().getText().toString());
}
This is the ViewHolder inner class.
public ViewHolder(#NonNull View itemView) {
super(itemView);
txtTask = itemView.findViewById(R.id.txtTask);
btnSave = itemView.findViewById(R.id.btnSave);
parent = itemView.findViewById(R.id.parent);
edtTxtTask = itemView.findViewById(R.id.edtTxtTask);
}
And this is the data class
package com.example.todolistapp;
import android.widget.EditText;
public class TaskList {
private String taskName;
private EditText edtTxtTask;
public TaskList(String taskName) {
this.taskName = taskName;
}
public EditText getEdtTxtTask() {
return edtTxtTask;
}
public void setEdtTxtTask(EditText edtTxtTask) {
this.edtTxtTask = edtTxtTask;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
}
Here is the MainActivity
RecyclerView recyclerView = findViewById(R.id.recyclerViewerTasks);
EditText edtTxtTask = findViewById(R.id.edtTxtTask);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
ArrayList<TaskList> taskLists = new ArrayList<>();
taskLists.add(new TaskList(edtTxtTask.getText().toString()));
ReyclerViewerAdapter adapter = new ReyclerViewerAdapter();
recyclerView.setAdapter(adapter);
adapter.setTasks(taskLists);

Get button call from another class

I have the two classes OrderAdapter.java OrderActivity.java. In the class OrderAdapter.java is a button and when i click it has to change a textview in the class OrderActivity.java. When i run the app the textview changes one time because of this line which is intend:
textView_order_price.setText(adapter.totalAmount + "");
but when i press the button again it should change the text again but it doesn't. Can you guys help me?
OrderActivity.java
package com.nfc.netvision;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.util.ArrayList;
public class OrderActivity extends AppCompatActivity {
RecyclerView recyclerView;
TextView textView_order_price;
ArrayList<ModelOrder> orderArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
recyclerView = findViewById(R.id.recyclerview_order_scroll);
textView_order_price = findViewById(R.id.textView_order_price);
orderArrayList = new ArrayList<>();
orderArrayList.add(new ModelOrder(R.drawable.coke, "Coka Cola", "Eine Cola hält dich wach und schmeckt dazu.", "3",0));
orderArrayList.add(new ModelOrder(R.drawable.fastfood, "Pommes", "Fritten für die Titten.", "5",0));
orderArrayList.add(new ModelOrder(R.drawable.water, "Wasser", "Still und sanft, so mag ich es.", "5",0));
orderArrayList.add(new ModelOrder(R.drawable.burger, "Burger", "Ach mir fällt nichts ein.", "10",0));
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
RecyclerView.LayoutManager recLiLayoutManager = layoutManager;
recyclerView.setLayoutManager(recLiLayoutManager);
OrderAdapter adapter = new OrderAdapter(this, orderArrayList);
recyclerView.setAdapter(adapter);
textView_order_price.setText(adapter.totalAmount + "");
System.out.println(adapter.totalAmount + "TOASBTORT");
}
}
OrderAdapter.java
package com.nfc.netvision;
import android.content.Context;
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 androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firestore.v1.StructuredQuery;
import java.util.ArrayList;
public class OrderAdapter extends RecyclerView.Adapter<OrderAdapter.ViewHolder> {
public int totalAmount;
private Context mContext;
private ArrayList<ModelOrder> nList;
OrderAdapter(Context context, ArrayList<ModelOrder> list) {
mContext = context;
nList = list;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
View view = layoutInflater.inflate(R.layout.recyclerview_order_items, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
final ModelOrder orderItem = nList.get(position);
ImageView image = holder.item_image;
final TextView name, place, price;
name = holder.item_name;
place = holder.item_place;
price = holder.item_price;
image.setImageResource(orderItem.getImage());
name.setText(orderItem.getName());
place.setText(orderItem.getPlace());
price.setText(orderItem.getPrice());
holder.order_item_minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(orderItem.getCounter() > 0) {
orderItem.setCounter(orderItem.getCounter()-1);
holder.order_item_count.setText("" + orderItem.getCounter());
calculatePrice(Integer.parseInt((String) price.getText()), false);
}
}
});
holder.order_item_plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(orderItem.getCounter() < 9) {
orderItem.setCounter(orderItem.getCounter() + 1);
holder.order_item_count.setText("" + orderItem.getCounter());
calculatePrice(Integer.parseInt((String) price.getText()), true);
}
}
});
}
#Override
public int getItemCount() {
return nList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView item_image;
TextView item_name, item_place, item_price,order_item_minus,order_item_count, order_item_plus;
public ViewHolder(#NonNull View itemView) {
super(itemView);
item_image = itemView.findViewById(R.id.order_item_image);
item_name = itemView.findViewById(R.id.order_item_name);
item_place = itemView.findViewById(R.id.order_item_place);
item_price = itemView.findViewById(R.id.order_item_price);
order_item_minus = itemView.findViewById(R.id.order_item_minus);
order_item_plus = itemView.findViewById(R.id.order_item_plus);
order_item_count = itemView.findViewById(R.id.order_item_count);
}
}
public void calculatePrice(int pPrice, boolean pUpDown) {
if(pUpDown) {
totalAmount = totalAmount + pPrice;
}
else {
totalAmount = totalAmount - pPrice;
}
System.out.println(totalAmount);
}
}
2 ways to solve your problem:
1st way - very simple - just add your textView from activity to constructor adapter;
private TextView orderPrice;
OrderAdapter(Context context, ArrayList<ModelOrder> list,TextView orderPrice) {
mContext = context;
nList = list;
this.orderPrice = orderPrice;
}
public void calculatePrice(int pPrice, boolean pUpDown) {
if(pUpDown) {
totalAmount = totalAmount + pPrice;
}
else {
totalAmount = totalAmount - pPrice;
}
//here you add totalAmount to your textView in activity
orderPrice.setText(totalAmount.toString)
System.out.println(totalAmount);
}
2d way create interface in your adapter and implement it in your activity;
//1st create interface in your adapter like this:
public class OrderAdapter extends
RecyclerView.Adapter<OrderAdapter.ViewHolder> {
public int totalAmount;
private Context mContext;
private ArrayList<ModelOrder> nList;
private TotalListener listener;
interface TotalListener{
void onTotalChanged(String result);
}
OrderAdapter(Context context, ArrayList<ModelOrder> list,TotalListener listener) {
mContext = context;
nList = list;
this.listener = listener;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
View view = layoutInflater.inflate(R.layout.recyclerview_order_items, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
final ModelOrder orderItem = nList.get(position);
ImageView image = holder.item_image;
final TextView name, place, price;
name = holder.item_name;
place = holder.item_place;
price = holder.item_price;
image.setImageResource(orderItem.getImage());
name.setText(orderItem.getName());
place.setText(orderItem.getPlace());
price.setText(orderItem.getPrice());
holder.order_item_minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(orderItem.getCounter() > 0) {
orderItem.setCounter(orderItem.getCounter()-1);
holder.order_item_count.setText("" + orderItem.getCounter());
calculatePrice(Integer.parseInt((String) price.getText()), false);
}
}
});
holder.order_item_plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(orderItem.getCounter() < 9) {
orderItem.setCounter(orderItem.getCounter() + 1);
holder.order_item_count.setText("" + orderItem.getCounter());
calculatePrice(Integer.parseInt((String) price.getText()), true);
}
}
});
}
#Override
public int getItemCount() {
return nList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView item_image;
TextView item_name, item_place, item_price,order_item_minus,order_item_count, order_item_plus;
public ViewHolder(#NonNull View itemView) {
super(itemView);
item_image = itemView.findViewById(R.id.order_item_image);
item_name = itemView.findViewById(R.id.order_item_name);
item_place = itemView.findViewById(R.id.order_item_place);
item_price = itemView.findViewById(R.id.order_item_price);
order_item_minus = itemView.findViewById(R.id.order_item_minus);
order_item_plus = itemView.findViewById(R.id.order_item_plus);
order_item_count = itemView.findViewById(R.id.order_item_count);
}
}
public void calculatePrice(int pPrice, boolean pUpDown) {
if(pUpDown) {
totalAmount = totalAmount + pPrice;
}
else {
totalAmount = totalAmount - pPrice;
}
//this is callback to your activity
listener.onTotalChanged(totalAmount.toString)
System.out.println(totalAmount);
}
}
and this is your updated activity
public class OrderActivity extends AppCompatActivity impelemts OrderAdapter.TotalListener {
RecyclerView recyclerView;
TextView textView_order_price;
ArrayList<ModelOrder> orderArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
recyclerView = findViewById(R.id.recyclerview_order_scroll);
textView_order_price = findViewById(R.id.textView_order_price);
orderArrayList = new ArrayList<>();
orderArrayList.add(new ModelOrder(R.drawable.coke, "Coka Cola", "Eine Cola hält dich wach und schmeckt dazu.", "3",0));
orderArrayList.add(new ModelOrder(R.drawable.fastfood, "Pommes", "Fritten für die Titten.", "5",0));
orderArrayList.add(new ModelOrder(R.drawable.water, "Wasser", "Still und sanft, so mag ich es.", "5",0));
orderArrayList.add(new ModelOrder(R.drawable.burger, "Burger", "Ach mir fällt nichts ein.", "10",0));
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
RecyclerView.LayoutManager recLiLayoutManager = layoutManager;
recyclerView.setLayoutManager(recLiLayoutManager);
OrderAdapter adapter = new OrderAdapter(this, orderArrayList,this);
recyclerView.setAdapter(adapter);
textView_order_price.setText(adapter.totalAmount + "");
System.out.println(adapter.totalAmount + "TOASBTORT");
}
#Override
public void onTotalChanged(String result) {
textView_order_price.setText(result);
}
}
add this listener to your adpater class and when you clik button listner call
private OnButtonClickListener listener;
public void setOnButtonClickListener(OnButtonClickListener listener){
this.listener=listener;
}
public interface OnButtonClickListener{
void OnButtonClick();
}
in Button click in your adapter :
listener.OnButtonClick();
in your activty class
OrderAdapter adapter = new OrderAdapter(this, orderArrayList);
adapter.setOnButtonClickListener(new OnButtonClickListener () {
#Override
public void OnButtonClick() {
//here you can do any thing on your text view
}
});

Getting Null Pointer exception in setting recycler item click listener [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I have searched a lot and didn't find any solution for my problem.I have created an interface for handling click listeners on particular item on recycler view.Logcat shows the error is occured in setting the listener in maiactivity
here is my MainActivity.java file
package com.example.mynotes;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.List;
public class MainActivity extends AppCompatActivity implements NoteAdapter.OnItemClickListener {
public static final int ADD_NOTE_REQUEST = 1;
public static final int EDIT_NOTE_REQUEST = 2;
NoteViewModel noteViewModel;
List<Note> allNotes;
RecyclerView rv;
NoteAdapter adapter;
FloatingActionButton floatingActionButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
floatingActionButton = (FloatingActionButton) findViewById(R.id.fab);
rv = (RecyclerView) findViewById(R.id.noterv);
rv.setLayoutManager(new LinearLayoutManager(this));
rv.setHasFixedSize(true);
noteViewModel = ViewModelProviders.of(this).get(NoteViewModel.class);
noteViewModel.getAllnotes().observe(this, new Observer<List<Note>>() {
#Override
public void onChanged(List<Note> notes) {
adapter = new NoteAdapter(notes);
rv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
});
adapter.SetOnItemClickListener(this) ;
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), AddNoteActivity.class);
startActivityForResult(intent, ADD_NOTE_REQUEST);
}
});
ItemTouchHelper itemTouchHelper = 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) {
noteViewModel.delete(adapter.getAt(viewHolder.getAdapterPosition()));
Toast.makeText(MainActivity.this, "note has been deleted", Toast.LENGTH_SHORT).show();
}
});
itemTouchHelper.attachToRecyclerView(rv);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ADD_NOTE_REQUEST && resultCode == RESULT_OK) {
String title = data.getStringExtra("EXTRA_TITLE");
String description = data.getStringExtra("EXTRA_DESCRIPTION");
String time = data.getStringExtra("EXTRA_TIME");
Note note = new Note(title, description, time);
noteViewModel.insert(note);
}
else if(requestCode == EDIT_NOTE_REQUEST && resultCode == RESULT_OK){
String title = data.getStringExtra("EXTRA_TITLE");
String description = data.getStringExtra("EXTRA_DESCRIPTION");
String time = data.getStringExtra("EXTRA_TIME");
Note note = new Note(title, description, time);
note.setId(data.getIntExtra("EXTRA_ID",-1));
noteViewModel.update(note);
Toast.makeText(this, "note has been updated", Toast.LENGTH_SHORT).show();
}
}
#Override
public void OnItemClick(Note note) {
Intent intent =new Intent(MainActivity.this,AddNoteActivity.class);
intent.putExtra("EXTRA_ID",note.getId());
intent.putExtra("EXTRA_TITLE",note.getTitle());
intent.putExtra("EXTRA_DESCRIPTION",note.getDescription());
intent.putExtra("EXTRA_TIME",note.getModified_time());
startActivityForResult(intent,EDIT_NOTE_REQUEST);
}
}
here is my NoteAdapter.java file
package com.example.mynotes;
import android.content.Context;
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;
import java.util.List;
public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.NoteViewHolder> {
OnItemClickListener listener;
List<Note> notes=new ArrayList<>();
public NoteAdapter(List<Note> notes) {
this.notes = notes;
}
#NonNull
#Override
public NoteViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View item_view = inflater.inflate(R.layout.single_note_item, parent, false);
// Return a new holder instance
NoteViewHolder viewHolder = new NoteViewHolder(item_view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull NoteViewHolder holder, int position) {
Note note =notes.get(position);
holder.titletv.setText(note.getTitle());
holder.datetv.setText(note.getModified_time());
}
#Override
public int getItemCount() {
return notes.size();
}
public class NoteViewHolder extends RecyclerView.ViewHolder{
TextView titletv ;
TextView datetv;
public NoteViewHolder(#NonNull View itemView) {
super(itemView);
titletv=(TextView) itemView.findViewById(R.id.titletv);
datetv=(TextView) itemView.findViewById(R.id.datetv);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener !=null && getAdapterPosition() != RecyclerView.NO_POSITION){
int position=getAdapterPosition();
listener.OnItemClick(notes.get(position));
}
}
});
}
}
Note getAt(int position){
return notes.get(position);
}
public interface OnItemClickListener{
void OnItemClick(Note note);
}
public void SetOnItemClickListener(OnItemClickListener onItemClickListener){
this.listener =onItemClickListener;
}
}
here is my Logcat message:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.mynotes.NoteAdapter.SetOnItemClickListener(com.example.mynotes.NoteAdapter$OnItemClickListener)' on a null object reference
at com.example.mynotes.MainActivity.onCreate(MainActivity.java:52)
at android.app.Activity.performCreate(Activity.java:7009)
at android.app.Activity.performCreate(Activity.java:7000)
Move this code to observer
adapter.SetOnItemClickListener(this) ;
So your code must be like this
noteViewModel.getAllnotes().observe(this, new Observer<List<Note>>() {
#Override
public void onChanged(List<Note> notes) {
adapter = new NoteAdapter(notes);
adapter.SetOnItemClickListener(this);
rv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
});
do this in your adapter and where you will new your adapter in activity:
package com.example.mynotes;
public class NoteAdapter extends RecyclerView.Adapter {
OnItemClickListener listener;
List<Note> notes=new ArrayList<>();
public NoteAdapter(List<Note> notes, OnItemClickListener listener) {
this.notes = notes;
this.listener = listener;
}
#NonNull
#Override
public NoteViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View item_view = inflater.inflate(R.layout.single_note_item, parent, false);
// Return a new holder instance
NoteViewHolder viewHolder = new NoteViewHolder(item_view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull NoteViewHolder holder, int position) {
Note note =notes.get(position);
holder.titletv.setText(note.getTitle());
holder.datetv.setText(note.getModified_time());
}
#Override
public int getItemCount() {
return notes.size();
}
public class NoteViewHolder extends RecyclerView.ViewHolder{
TextView titletv ;
TextView datetv;
public NoteViewHolder(#NonNull View itemView) {
super(itemView);
titletv=(TextView) itemView.findViewById(R.id.titletv);
datetv=(TextView) itemView.findViewById(R.id.datetv);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener !=null && getAdapterPosition() != RecyclerView.NO_POSITION){
int position=getAdapterPosition();
listener.OnItemClick(notes.get(position));
}
}
});
}
}
Note getAt(int position){
return notes.get(position);
}
public interface OnItemClickListener{
void OnItemClick(Note note);
}
public void SetOnItemClickListener(OnItemClickListener onItemClickListener){
this.listener =onItemClickListener;
}
}
and now in your activity where you will new your adapter do this:
adapter = new NoteAdapter(notes, NoteAdapter.OnItemClickListener() {
#Override
public void OnItemClick(Note note) {
//DO WHATEVER YOU WANT HERE
}

Facebook Native Ads in RycyclerView android

I found similar issue Facebook Native ads in recycler view android , but had some problems with integration with Custom Ad.
For the first I tried to describe NativeAdsManager :
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
manager = new NativeAdsManager(getActivity(), "892769720837476_892772047503910", 5);
manager.setListener(this);
manager.loadAds();
nativeAd = new NativeAd(getActivity(), "892769720837476_892772047503910");
nativeAd.setAdListener(this);
nativeAd.loadAd();
...
}
Then I included Native ad as a parameter in RecyclerAdapter constructor:
adapter = new RecyclerAdapter(foodDataList, getActivity(), nativeAd);
In this Class I also implement AdListener and NativeAdsManager.Listener methods:
#Override
public void onError(Ad ad, AdError adError) {
}
#Override
public void onAdLoaded(Ad ad) {
}
#Override
public void onAdClicked(Ad ad) {
}
#Override
public void onAdsLoaded() {
System.out.println("Loaded in fragment");
nativeAd = manager.nextNativeAd();
nativeAd.setAdListener(this);
adapter.notifyDataSetChanged();
}
#Override
public void onAdError(AdError adError) {
}
After that in RecyclerAdapter class :
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
switch (holder.getItemViewType()) {
...
case 2:
AdditionalHolder new_holder = (AdditionalHolder) holder;
adView = NativeAdView.render(context, nativeAd, NativeAdView.Type.HEIGHT_100);
new_holder.templateContainer.addView(adView);
return;
...
public class AdditionalHolder extends RecyclerView.ViewHolder {
protected LinearLayout templateContainer;
public AdditionalHolder(View view) {
super(view);
templateContainer = (LinearLayout) view.findViewById(R.id.ad_test2);
}
}
After all of that my Fragment with RecyclerView becomes very "luggy" and every time I can see more and more ads items (1 - from the beginning, 2 - after 10 items, 3 - after next 10 and so on).
It's my first time of using multiple RecyclerView holders, and find this issue difficult.
Provide you with gist of 2 Classes
https://gist.github.com/burnix/6af8196ee8acf5c8f94e - RecyclerAdapter.class
https://gist.github.com/burnix/53dc2ed7446969b78f07 - FragmentList.class
Help me please to solve lugs problem and to place AudienceNetwork as it needs to be.
Thanks in advance!
After several hours of headache I solved my problem.
I needed to change the constructor of RecyclerView:
public RecyclerAdapter(List<FoodData> food, Context context, NativeAd nativeAd, NativeAdsManager manager) {
this.foodDataList = food;
this.context = context;
this.nativeAd = nativeAd;
this.manager = manager;
}
And implement the behavior of Native Ads in onBindViewHolder:
AdditionalHolder new_holder = (AdditionalHolder) holder;
try {
new_holder.templateContainer.removeViewInLayout(adView);
} catch (Exception e) {
e.printStackTrace();
}
nativeAd = manager.nextNativeAd();
try {
adView = NativeAdView.render(context, nativeAd, NativeAdView.Type.HEIGHT_300);
} catch (NullPointerException e) {
e.printStackTrace();
}
new_holder.templateContainer.addView(adView);
new_holder.blank_holder.setVisibility(View.GONE);
But it hasn't solved my problem entirely (micro-lags while scrolling), but still it could be useful for someone, I hoped.
Youur adapter==>
import android.app.Activity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.romantic.pictures.hd.love.wallpaper.download.R;
import com.romantic.pictures.hd.love.wallpaper.download.activity.ROMANTIC_LOVE_WALLPAPER;
import com.romantic.pictures.hd.love.wallpaper.download.model.ImageStorage;
import java.util.ArrayList;
/**
* Created by abc on 4/11/2018.
*/
public class ImageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public final int CONTENT_TYPE = 0;
public final int AD_TYPE = 1;
private OnItemClickListener mOnItemClickListener;
Activity context;
ArrayList<ImageStorage> catagorilist;
public ImageAdapter(Activity context, ArrayList<ImageStorage> catagorilist, OnItemClickListener mOnItemClickListener) {
this.mOnItemClickListener = mOnItemClickListener;
this.context = context;
this.catagorilist = catagorilist;
}
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
#Override
public int getItemViewType(int position) {
Log.e("TAG", "getItemViewType position : " + position);
Log.e("TAG", "getItemViewType position% : " + position % 5);
if (position % 7 == 0)
return AD_TYPE;
return CONTENT_TYPE;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case CONTENT_TYPE:
Log.e("TAG", "content type : ");
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_layout2, parent, false);
return new MyHolder(view);
case AD_TYPE:
Log.e("TAG", "ad type : ");
View nativeView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_nativead, parent, false);
return new NativeAd(nativeView);
default:
Log.e("TAG", "default : ");
LayoutInflater inflater1 = LayoutInflater.from(parent.getContext());
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_layout2, parent, false);
return new MyHolder(v);
}
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
holder.setIsRecyclable(false);
int viewType = getItemViewType(position);
ImageStorage listitem = catagorilist.get(position);
switch (viewType) {
case CONTENT_TYPE:
Log.e("TAG", "bind CONTENT_TYPE : ");
final MyHolder menuItemHolder = (MyHolder) holder;
// holder.imagview.setText(listitem.getId());
/*holder.cat_name.setText(listitem.getName());*/
Glide.with(context).load("http://learntodraw.in/ImageApp/new_" + listitem.getCat_imagem()).listener(new RequestListener<String, GlideDrawable>() {
#Override
public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
return false;
}
#Override
public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
menuItemHolder.progressBar.setVisibility(View.GONE);
return false;
}
}).into(menuItemHolder.imagview);
Log.e("TAG", "onBindViewHolder: " + "http://learntodraw.in/ImageApp/new_" + listitem.getCat_imagem());
Log.e("TAG", "onBindViewHolder: " + position);
menuItemHolder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mOnItemClickListener.onItemClick(v, position);
}
});
break;
case AD_TYPE:
Log.e("TAG", "bind AD_TYPE : ");
final NativeAd nativeHolder = (NativeAd) holder;
ROMANTIC_LOVE_WALLPAPER.showNativeVidAd(context, nativeHolder.container);
nativeHolder.container_height.post(new Runnable() {
public void run() {
// int height = nativeHolder.container_height.getHeight();
ViewGroup.LayoutParams params = nativeHolder.container.getLayoutParams();
// params.height = height;
params.height = LinearLayout.LayoutParams.WRAP_CONTENT;
nativeHolder.container.setLayoutParams(params);
// nativeHolder.linearlayout_title.setVisibility(View.GONE);
}
});
break;
}
}
#Override
public int getItemCount() {
return catagorilist.size();
}
public class MyHolder extends RecyclerView.ViewHolder {
public ImageView imagview;
public LinearLayout mainLayout;
public CardView cardview;
public ProgressBar progressBar;
public MyHolder(View itemView) {
super(itemView);
imagview = (ImageView) itemView.findViewById(R.id.imagview);
mainLayout = (LinearLayout) itemView.findViewById(R.id.mainLayout);
progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar);
cardview = (CardView) itemView.findViewById(R.id.cardview);
}
}
public static class NativeAd extends RecyclerView.ViewHolder {
LinearLayout container;
LinearLayout container_height;
// LinearLayout linearlayout_title;
public NativeAd(View view) {
super(view);
container = view.findViewById(R.id.native_ad_container);
container_height = view.findViewById(R.id.container_height);
/* linearlayout_title = view.findViewById(R.id.linearlayout_title);*/
}
}
}
public static void showNativeVidAd(final Activity context, final LinearLayout nativeContainer) {
final NativeAd nativeAd = new NativeAd(context, context.getString(R.string.fb_test_ad_img) + context.getString(R.string.native_ads3));
// final NativeAd nativeAd = new NativeAd(context, context.getString(R.string.facebook_native_ad_unit_id));
nativeAd.setAdListener(new com.facebook.ads.AdListener() {
#Override
public void onError(Ad ad, AdError error) {
// Ad error callback
Log.e("TAG", "facebook native error : " + error.getErrorMessage());
nativeContainer.setVisibility(View.GONE);
}
#Override
public void onAdLoaded(Ad ad) {
// Ad loaded callback
Log.e("TAG", "facebook native onAdLoaded : ");
if (nativeAd != null) {
nativeAd.unregisterView();
}
try {
LinearLayout nativeAdContainer = nativeContainer;
nativeAdContainer.setVisibility(View.VISIBLE);
// Add the Ad view into the ad container.
nativeAdContainer = (LinearLayout) context.findViewById(R.id.native_ad_container);
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the Ad view. The layout referenced should be the one you created in the last step.
RelativeLayout adView = (RelativeLayout) inflater.inflate(R.layout.custom_nativead, nativeAdContainer, false);
nativeAdContainer.removeAllViews();
nativeAdContainer.addView(adView);
// Create native UI using the ad metadata.
MediaView nativeAdMedia = (MediaView) adView.findViewById(R.id.native_ad_media);
/* //TextView nativeAdSocialContext = (TextView) adView.findViewById(R.id.native_ad_social_context);
Typeface typeface = Typeface.createFromAsset(context.getAssets(), "ProximaNova-Semibold.otf");
nativeAdSocialContext.setTypeface(typeface);*/
// TextView nativeAdCallToAction = (TextView) adView.findViewById(R.id.native_ad_call_to_action);
// Set the Text.
// nativeAdSocialContext.setText(nativeAd.getAdSocialContext());
// nativeAdCallToAction.setText(nativeAd.getAdCallToAction());
// Download and display the ad icon.
// NativeAd.Image adIcon = nativeAd.getAdIcon();
// Download and display the cover image.
nativeAdMedia.setNativeAd(nativeAd);
// Add the AdChoices icon
LinearLayout adChoicesContainer = (LinearLayout) adView.findViewById(R.id.ad_choices_container);
AdChoicesView adChoicesView = new AdChoicesView(context, nativeAd, true);
adChoicesContainer.addView(adChoicesView);
// Register the Title and CTA button to listen for clicks.
List<View> clickableViews = new ArrayList<>();
// clickableViews.add(nativeAdCallToAction);
clickableViews.add(nativeAdMedia);
clickableViews.add(adChoicesContainer);
nativeAd.registerViewForInteraction(nativeAdContainer, clickableViews);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onAdClicked(Ad ad) {
// Ad clicked callback
}
#Override
public void onLoggingImpression(Ad ad) {
// Ad impression logged callback
Log.e("TAG", "facebook native onLoggingImpression");
}
});
// Request an ad
nativeAd.loadAd(NativeAd.MediaCacheFlag.ALL);
}

recyclerview onclicklistener java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

when I dynamic remove an item, or when I refresh the adapter(swipe to fresh) i get these erros:
recyclerview onclicklistener java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
Really can't figure out why this is happening, Really Appreciate any feed back.
MainActivity:
adapter.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
GroupModel selectedList = mGroupModels.get(position);
if (selectedList != null) {
Log.d(TAG, "setAdpterListner > view.getId: " + view.getId() +
" | P: " + position +
" | data ID: " + selectedList.getGroupName()
//" | viewID: " + viewID
);
Intent intent = new Intent(this, DetailsActivity.class);
String listId = selectedList.getGroupID();
String listName = selectedList.getGroupName();
intent.putExtra(Constant.KEY_LIST_ID, listId);
intent.putExtra(Constant.KEY_LIST_NAME, listName);
startActivity(intent);
}
}
});
Adapter:
public class GroupListAdapter extends RecyclerView.Adapter<GroupListAdapter.StatusViewHolder> {
Context context;
private List<GroupModel> mGroupModels;
private static OnItemClickListener listener;
public GroupListAdapter(Context context, List<GroupModel> groupList) {
this.context = context;
this.mGroupModels = groupList;
}
public void setOnItemClickListener(OnItemClickListener listener) {
GroupListAdapter.listener = listener;
}
#Override
public StatusViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_group_list, parent, false);
return new StatusViewHolder(view);
}
#Override
public void onBindViewHolder(StatusViewHolder holder, int position) {
final GroupModel data = mGroupModels.get(position);
holder.text_view_list_name.setText(data.getGroupName());
}//end onBindViewHolder
#Override
public int getItemCount() {
return mGroupModels.size();
}
public class StatusViewHolder extends RecyclerView.ViewHolder {
public TextView text_view_list_name;
public TextView created_by;
public StatusViewHolder(final View itemView) {
super(itemView);
text_view_list_name = (TextView) itemView.findViewById(R.id.text_view_list_name);
created_by = (TextView) itemView.findViewById(R.id.created_by);
// Setup the click listener
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null)
listener.onItemClick(itemView, getLayoutPosition());
}
});
}
}//end StatusViewHolder
}//end GroupListAdapter
UPDATE:
I taken into consideration Yurii Tsap Feedback. I check the code again. I think the problem is somewhere below:
Whenever I swipe to Fresh, and If i click on the list straight way, the app Crash with the error from above.
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
// Refresh items
mRecyclerView.invalidate();
adapter = null;
initGetGroupList();
mSwipeRefreshLayout.setRefreshing(false);
}
});
In the API call
...
GroupModel groupModel = new GroupModel(groupID, groupName, groupCreatedBy);
mGroupModels.add(groupModel);
}
updateUI(true);
if (adapter == null) {
adapter = new GroupListAdapter(MainActivity.this, mGroupModels);
mRecyclerView.setAdapter(adapter);
setAdapterListener(adapter);
}
The problem is definitely not in the static listener. And also the listener is just an interface callback(related to the comment above) not a AdapterView.OnItemClickListener(). I think the problem is somewhere behind this code, maybe you are clearing the item list somewhere else or something like that?
And also as for me in your case it's better to use getAdapterPosition() instead of getLayoutPosition().
As mentioned in docs :
If LayoutManager needs to call an external method that requires the adapter position of the item, it can use getAdapterPosition() or RecyclerView.Recycler.convertPreLayoutPositionToPostLayout(int).
Make OnItemClickListener non static .Like
private OnItemClickListener listener;
your code have alot of problem
i will explain my way to handle recycle view
very simple adapter
package com.pentavalue.ongo.transportway.adapter;
import android.app.Activity;
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.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import com.pentavalue.ongo.R;
import com.pentavalue.ongo.Utilts.ImageLoaderHelper;
import com.pentavalue.ongo.register.model.Vechiles;
import com.pentavalue.ongo.widget.ArabicTextView;
import java.util.ArrayList;
/**
* Created by hamada on 19/09/2015.
*/
public class TransportTypeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public LayoutInflater inflater = null;
Activity activity;
ArrayList<Vechiles> vechileList;
ImageLoaderHelper imageLoaderHelper;
public TransportTypeAdapter(Activity activity, ArrayList<Vechiles> vechileList) {
this.activity = activity;
this.vechileList = vechileList;
imageLoaderHelper = new ImageLoaderHelper(activity, null);
inflater = LayoutInflater.from(activity);
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View vi = inflater.inflate(R.layout.single_transport_item, parent, false);
RecyclerView.ViewHolder vh = new VechileListHolder(vi);
return vh;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int pos) {
VechileListHolder mHolder = (VechileListHolder) viewHolder;
mHolder.renderDate(vechileList.get(pos));
}
#Override
public int getItemCount() {
if (vechileList != null)
return this.vechileList.size();
else
return 0;
}
public class VechileListHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
ArabicTextView vecName;
RelativeLayout img_layout;
ProgressBar progress;
ImageView imgView;
public VechileListHolder(View vi) {
super(vi);
vi.setOnClickListener(this);
img_layout = (RelativeLayout) vi.findViewById(R.id.img_layout);
vecName = (ArabicTextView) vi.findViewById(R.id.TVVecName);
progress = (ProgressBar) vi.findViewById(R.id.progress);
imgView = (ImageView) vi.findViewById(R.id.imgView);
}
public void renderDate(Vechiles item) {
imageLoaderHelper.loadImage(imgView, progress, item.getImg());
vecName.setText(item.getVecName());
}
#Override
public void onClick(View v) {
if (mItemClickListener != null)
mItemClickListener.onItemClickListener(getPosition(), v);
}
}
public void setOnItemClickListener(ItemClickListener itemClick) {
this.mItemClickListener = itemClick;
}
public ItemClickListener mItemClickListener;
public interface ItemClickListener {
public void onItemClickListener(int pos, View v);
}
public void updateList(ArrayList<Vechiles> vechileList) {
this.vechileList = vechileList;
notifyDataSetChanged();
}
public void removeItem(int pos){
this.vechileList.remove(pos);
notifyItemRemoved(pos);
}
}
and in Fragment or activity can
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initListView();
}
private void initRecycleView(){
listView = (RecyclerView) v.findViewById(R.id.listView);
listView.getItemAnimator().setAddDuration(1000);
listView.getItemAnimator().setChangeDuration(1000);
listView.getItemAnimator().setMoveDuration(1000);
listView.getItemAnimator().setRemoveDuration(1000);
listView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
listView.setAdapter(new TransportTypeAdapter(getActivity(), vecList));
}
then after data back from API can update adapter with new data by use method update
((VechileListHolder ) listView.getAdapter).updateList( vechileList);
in case went to remove any item by using Pos can do call method that in adapter removeItem(pos)
((VechileListHolder ) listView.getAdapter).removeItem(1);
hope this code help you

Categories

Resources