How to refresh a TextView from another class? - java

I get this error:
Attempt to invoke virtual method 'android.view.Window$Callback
android.view.Window.getCallback()' on a null object reference
public class AdaptadorCarrito extends
RecyclerView.Adapter<AdaptadorCarrito.ViewHolderCarrito> {
ArrayList<CarritoVo> listaCarrito;
AdaptadorCarrito adapter;
RecyclerView.Adapter madapter;
int i = 1;
public AdaptadorCarrito(ArrayList<CarritoVo> listaCarrito) {
this.listaCarrito = listaCarrito;
}
#NonNull
#Override
public ViewHolderCarrito onCreateViewHolder(#NonNull final ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_carrito, null, false);
final ViewHolderCarrito myHolder = new ViewHolderCarrito(view);
final CafeteriaDB cafeteriaDB = new CafeteriaDB(parent.getContext());
myHolder.item_list_carrito.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int newPosition = myHolder.getAdapterPosition();
cafeteriaDB.eliminarProducto(myHolder.etiNombre.getText().toString(), myHolder.etiInfo.getText().toString());
eliminarProducto(newPosition);
// i++;
// Toast.makeText(parent.getContext(),"Producto Eliminado "+i+" eliminado",Toast.LENGTH_SHORT).show();
CarritoCompras obj = new CarritoCompras();
TextView tv = obj.getTextView(); //Error Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
tv.setText(String.valueOf(cafeteriaDB.getTotal()));
}
});
return myHolder;
}
private void eliminarProducto(int position) {
listaCarrito.remove(position);
notifyItemRemoved(position);
}
#Override
public void onBindViewHolder(#NonNull ViewHolderCarrito holder, int position) {
CarritoVo positions = listaCarrito.get(position);
holder.etiNombre.setText(listaCarrito.get(position).getNombre());
holder.etiPrecio.setText(String.valueOf(listaCarrito.get(position).getPrecio()));
holder.etiInfo.setText(listaCarrito.get(position).getInfo());
holder.etiCantidades.setText(String.valueOf(listaCarrito.get(position).getCantidad()));
holder.etiFoto.setImageBitmap(positions.getFoto());
}
#Override
public int getItemCount() {
//return listaCarrito.size();
return (listaCarrito == null) ? 0 : listaCarrito.size();
}
public class ViewHolderCarrito extends RecyclerView.ViewHolder {
LinearLayout item_list_carrito;
TextView etiNombre, etiPrecio, etiInfo, etiCantidades, txtTotalB, txtTotalF;
ImageView etiFoto;
public ViewHolderCarrito(#NonNull View itemView) {
super(itemView);
item_list_carrito = (LinearLayout) itemView.findViewById(R.id.id_carrito_item);
etiFoto = (ImageView) itemView.findViewById(R.id.fotoC);
etiNombre = (TextView) itemView.findViewById(R.id.nombreC);
etiPrecio = (TextView) itemView.findViewById(R.id.precioC);
etiInfo = (TextView) itemView.findViewById(R.id.infoC);
etiCantidades = (TextView) itemView.findViewById(R.id.cantidadC);
}
}
}
Activity
public class CarritoCompras extends AppCompatActivity implements Carrito.OnFragmentInteractionListener{
TextView txtTotalF;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_carrito_compras);
CafeteriaDB db = new CafeteriaDB(this);
getTextView();
txtTotalF = (TextView)findViewById(R.id.totalF);
txtTotalF.setText(String.valueOf(db.totalFilas()));
}
public TextView getTextView(){
TextView txtTotalB = (TextView)findViewById(R.id.totalB); //Error Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
return txtTotalB;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}

You can do like the following way
Step 1:
Load TextView at only once
TextView txtTotalB; // declare class level
inside onCreate()
txtTotalB = (TextView)findViewById(R.id.totalB);
Step 2:
create method
public TextView getTextView(){
return txtTotalB
}
Step 3:
inside your adapter class access your activity method like below
TextView tv = ((CarritoCompras)context).getTextView();
tv.setText(String.valueOf(cafeteriaDB.getTotal())); // now here you done

You can use Interfaces for communication.
Create an interface as shown below:
public interface RecyclerItemClickListener {
void onItemClick(String text);
}
In your adapter class, create declare a variable of type RecyclerItemClickListener and modify the Adapter's constructor to accept an instance of 'RecyclerItemClickListener' as a parameter. i.e Modify your Adapter class as shown below:
public class AdaptadorCarrito extends
RecyclerView.Adapter<AdaptadorCarrito.ViewHolderCarrito> {
RecyclerItemClickListener recyclerItemClickListener; //Here we are declaring a variable of the created interface
ArrayList<CarritoVo> listaCarrito;
AdaptadorCarrito adapter;
RecyclerView.Adapter madapter;
int i = 1;
//Modifying the constructor to initialize the above declared listener
public AdaptadorCarrito(ArrayList<CarritoVo> listaCarrito, RecyclerItemClickListener listener) {
this.listaCarrito = listaCarrito;
this.recyclerItemClickListener = listener;
}
#NonNull
#Override
public ViewHolderCarrito onCreateViewHolder(#NonNull final ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_carrito, null, false);
final ViewHolderCarrito myHolder = new ViewHolderCarrito(view);
final CafeteriaDB cafeteriaDB = new CafeteriaDB(parent.getContext());
myHolder.item_list_carrito.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int newPosition = myHolder.getAdapterPosition();
cafeteriaDB.eliminarProducto(myHolder.etiNombre.getText().toString(), myHolder.etiInfo.getText().toString());
eliminarProducto(newPosition);
// i++;
// Toast.makeText(parent.getContext(),"Producto Eliminado "+i+" eliminado",Toast.LENGTH_SHORT).show();
CarritoCompras obj = new CarritoCompras();
/*TextView tv = obj.getTextView(); //Error Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
tv.setText(String.valueOf(cafeteriaDB.getTotal()));*/
//Here we are passing the test to be displayed in the textview to your activity
recyclerItemClickListener.onItemClick(String.valueOf(cafeteriaDB.getTotal()));
}
});
return myHolder;
}
private void eliminarProducto(int position) {
listaCarrito.remove(position);
notifyItemRemoved(position);
}
#Override
public void onBindViewHolder(#NonNull ViewHolderCarrito holder, int position) {
CarritoVo positions = listaCarrito.get(position);
holder.etiNombre.setText(listaCarrito.get(position).getNombre());
holder.etiPrecio.setText(String.valueOf(listaCarrito.get(position).getPrecio()));
holder.etiInfo.setText(listaCarrito.get(position).getInfo());
holder.etiCantidades.setText(String.valueOf(listaCarrito.get(position).getCantidad()));
holder.etiFoto.setImageBitmap(positions.getFoto());
}
#Override
public int getItemCount() {
//return listaCarrito.size();
return (listaCarrito == null) ? 0 : listaCarrito.size();
}
public class ViewHolderCarrito extends RecyclerView.ViewHolder {
LinearLayout item_list_carrito;
TextView etiNombre, etiPrecio, etiInfo, etiCantidades, txtTotalB, txtTotalF;
ImageView etiFoto;
public ViewHolderCarrito(#NonNull View itemView) {
super(itemView);
item_list_carrito = (LinearLayout) itemView.findViewById(R.id.id_carrito_item);
etiFoto = (ImageView) itemView.findViewById(R.id.fotoC);
etiNombre = (TextView) itemView.findViewById(R.id.nombreC);
etiPrecio = (TextView) itemView.findViewById(R.id.precioC);
etiInfo = (TextView) itemView.findViewById(R.id.infoC);
etiCantidades = (TextView) itemView.findViewById(R.id.cantidadC);
}
}
}
Now in your Activity where you will be instantiating the AdaptadorCarrito Object, you need to pass the instance of RecyclerItemClickListener as parameter to the Adapter's constructor.
Example:
AdaptadorCarrito adapter = new AdaptadorCarrito(listaCarrito , new RecyclerItemClickListener() {
#Override
public void onItemClick(String text) {
//In here you can set your TextView's text
TextView txtTotalB = (TextView)findViewById(R.id.totalB);
txtTotalB.setText(text);
}
});

Thanks for answering, I was able to solve my problem, which was to update a text view that was in an activity but that needed the help of an event that was in another class to do so.
first adding an activity in the constructor of the adapter
Activity activity;
public AdaptadorCarrito(ArrayList<CarritoVo> nlistaCarrito, Activity nactivity) {
nListCarrito = nlistaCarrito;
this.activity = nactivity;
}
Then calling TextView the this way:
public ViewHolderCarrito onCreateViewHolder(#NonNull final ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_carrito,null,false);
final ViewHolderCarrito myHolder = new ViewHolderCarrito(view);
final CafeteriaDB cafeteriaDB = new CafeteriaDB(parent.getContext());;
final CarritoCompras carrito = new CarritoCompras();
---->final TextView txtTotalB = (TextView)this.activity.findViewById(R.id.totalB);
txtTotalB.setText(String.valueOf(cafeteriaDB.getTotal()));
myHolder.item_list_carrito.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int newPosition = myHolder.getAdapterPosition();
cafeteriaDB.eliminarProducto(myHolder.etiNombre.getText().toString(), myHolder.etiInfo.getText().toString());
eliminarProducto(newPosition);
Toast.makeText(parent.getContext(),"Producto Eliminado",Toast.LENGTH_SHORT).show();
-----> txtTotalB.setText(String.valueOf(cafeteriaDB.getTotal()));
}
});
return myHolder;
}
and finally creating an instance of the adapter in the activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_carrito_compras);
ArrayList<CarritoVo> nLlistaCarrito = null;
------>AdaptadorCarrito adapter = new AdaptadorCarrito(nLlistaCarrito,this);
CafeteriaDB cafeteriaDB = new CafeteriaDB(this);
TextView txtTotalB = (TextView)findViewById(R.id.totalB);
txtTotalB.setText(String.valueOf(cafeteriaDB.totalFilas()));
TextView txtTotalF = (TextView)findViewById(R.id.totalF);
txtTotalF.setText(String.valueOf(cafeteriaDB.totalFilas()));
}

Related

Attempt to invoke virtual method 'void.estate.view.adapter.plucking.EmployeePluckingSessionAdapter.setList(java.util.List)' on a null object reference

I am getting this error but I cannot find the reason.
This is my code of Adapter.
public class EmployeePluckingSessionAdapter extends RecyclerView.Adapter<EmployeePluckingSessionAdapter.EmployeePluckingSessionAdapterHolder> {
private SubSessionListActivity.AdapterEvents adapterEvents;
private List<EmployeePluckingCollectionSummary> employeePluckingCollectionSummaries = new ArrayList<>();
public EmployeePluckingSessionAdapter(SubSessionListActivity.AdapterEvents adapterEvents){
this.adapterEvents = adapterEvents;
}
public void setList(List<EmployeePluckingCollectionSummary> employeePluckingCollectionSummaries){
this.employeePluckingCollectionSummaries = employeePluckingCollectionSummaries;
}
public void setAdapterEvents(SubSessionListActivity.AdapterEvents adapterEvents) {
this.adapterEvents = adapterEvents;
}
#NonNull
#Override
public EmployeePluckingSessionAdapterHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.plucking_summary_data, parent, false);
return new EmployeePluckingSessionAdapterHolder(view);
}
#Override
public void onBindViewHolder(#NonNull EmployeePluckingSessionAdapterHolder holder, int position) {
EmployeePluckingCollectionSummary employeePluckingCollectionSummary = employeePluckingCollectionSummaries.get(position);
holder.userName.setText(String.valueOf(employeePluckingCollectionSummary.getEmployeeName()));
holder.userId.setText(String.valueOf(employeePluckingCollectionSummary.getEmployeeId()));
holder.session.setText(String.valueOf(employeePluckingCollectionSummary.getSessionName()));
holder.sessionTotal.setText(String.valueOf(employeePluckingCollectionSummary.getWeight()));
}
#Override
public int getItemCount() {
return 0;
}
class EmployeePluckingSessionAdapterHolder extends RecyclerView.ViewHolder {
private final LinearLayout plucking_data;
private final TextView userName;
private final TextView userId;
private final TextView session;
private final TextView sessionTotal;
public EmployeePluckingSessionAdapterHolder(View view) {
super(view);
this.plucking_data = view.findViewById(R.id.plucking_data);
this.userName = view.findViewById(R.id.userName);
this.userId =view.findViewById(R.id.userId);
this.session = view.findViewById(R.id.session);
this.sessionTotal = view.findViewById(R.id.sessionTotal);
}
}
}
This is my code of Activity.
public class PluckingChecklistReportActivity extends AppCompatActivity {
private PluckingCollectionViewModel pluckingCollectionViewModel;
RecyclerView recyclerView;
List<EmployeePluckingCollectionSummary> pluckingSummary = new ArrayList<>();
LinearLayoutManager linearLayoutManager;
EmployeePluckingSessionAdapter employeePluckingSessionAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_plucking_checklist_report);
pluckingCollectionViewModel = new ViewModelProvider(this).get(PluckingCollectionViewModel.class);
recyclerView = findViewById(R.id.plucking_data);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setAdapter(employeePluckingSessionAdapter);
recyclerView.setLayoutManager(linearLayoutManager);
pluckingCollectionViewModel.getEmployeePluckingSessionSummary().observe(this, new Observer<List<EmployeePluckingCollectionSummary>>() {
#Override
public void onChanged(List<EmployeePluckingCollectionSummary> employeePluckingCollectionSummaries) {
pluckingSummary = employeePluckingCollectionSummaries;
employeePluckingSessionAdapter.setList(pluckingSummary);
}
});
}
}
I found that "pluckingSummary" list is null. I don't know how to set values to the list. I tried to set the values to arrayList after convert it into JSONObject but it did not work as well. I get values correctly when I use System.out.println(new Gson().toJson(employeePluckingCollectionSummaries));

How do I pass data from adapter to mainactivity when a button is clicked

I Uploaded some data to sqlite and I want to delete each data from the recyclerview by pressing a button. so how can I achieve this? I want to get the id from recyclerview to the mainactivity then delete the data from sqlite and update reyclerview. How can I achieve this?
MainActivity
public class SelectedProblems extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selecte_problem_drawal);
mRecyclerView = (RecyclerView) findViewById(R.id.selected_problem_recycle_view); // Instantiate Recyclerview
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(true);
selectedProblemsAdapter = new SelectedProblemsAdapter(this, getAllItems(), listener);
mRecyclerView.setAdapter(selectedProblemsAdapter);
Button remove = findviewbyid(R.id.remove);
remove.setOnClickListener(new View.OnClickListener() {
}
}
SelectedProblemsAdapter
public SelectedProblemsAdapter(Context context, Cursor cursor, OnItemClick listener) {
this.context = context;
this.cursor = cursor;
listener = listener;
}
#Override
public SelectedProblemsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.activity_selected_problems_content, null, false);
return new SelectedProblemsViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SelectedProblemsViewHolder holder, final int position) {
if (this.cursor != null){
}
}
#Override
public int getItemCount() {
return (null != cursor ? cursor.getCount(): 0);
}
public void update(Cursor cursor) {
this.cursor = cursor;
notifyDataSetChanged();
}
class SelectedProblemsViewHolder extends RecyclerView.ViewHolder{
TextView selectedProblems, selectedProblemPrice, selectedProblemTotal;
Button remove_problem_from_cart;
public SelectedProblemsViewHolder(View itemView) {
super(itemView);
selectedProblems = itemView.findViewById(R.id.selected_problems);
selectedProblemPrice = itemView.findViewById(R.id.selected_problem_price);
selectedProblemTotal = itemView.findViewById(R.id.selectedProblemTotal);
remove_problem_from_cart = itemView.findViewById(R.id.remove_problem_from_cart);
}
}
}
MainActivity
public class SelectedProblems extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selecte_problem_drawal);
mRecyclerView = (RecyclerView) findViewById(R.id.selected_problem_recycle_view); // Instantiate Recyclerview
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(true);
selectedProblemsAdapter = new SelectedProblemsAdapter(this, getAllItems(), listener);
mRecyclerView.setAdapter(selectedProblemsAdapter);
Button remove = findviewbyid(R.id.remove);
remove.setOnClickListener(new View.OnClickListener() {
}
}
SelectedProblemsAdapter
public SelectedProblemsAdapter(Context context, Cursor cursor, OnItemClick listener) {
this.context = context;
this.cursor = cursor;
listener = listener;
}
#Override
public SelectedProblemsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.activity_selected_problems_content, null, false);
return new SelectedProblemsViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SelectedProblemsViewHolder holder, final int position) {
if (this.cursor != null){
// it will call your interface method which is implemented in Activity
holder.yourView_name.setOnClickListener(new View.OnClickListener() {
listener.yourmethod();
}
}
}
#Override
public int getItemCount() {
return (null != cursor ? cursor.getCount(): 0);
}
public void update(Cursor cursor) {
this.cursor = cursor;
notifyDataSetChanged();
}
class SelectedProblemsViewHolder extends RecyclerView.ViewHolder{
TextView selectedProblems, selectedProblemPrice, selectedProblemTotal;
Button remove_problem_from_cart;
public SelectedProblemsViewHolder(View itemView) {
super(itemView);
selectedProblems = itemView.findViewById(R.id.selected_problems);
selectedProblemPrice = itemView.findViewById(R.id.selected_problem_price);
selectedProblemTotal = itemView.findViewById(R.id.selectedProblemTotal);
remove_problem_from_cart = itemView.findViewById(R.id.remove_problem_from_cart);
}
}
}
You can achieve it by implementing an interface.
Step 1: Create an interface with an abstract function that takes in the type of data as its parameters.
public interface OnDataItemClickListener {
void onItemClick(YourItem yourItem);
}
Step 2: Make the activity implement the interface and override its methods.
public class SelectedProblems extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selecte_problem_drawal);
mRecyclerView = (RecyclerView) findViewById(R.id.selected_problem_recycle_view); //
//Instantiate Recyclerview
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(true);
selectedProblemsAdapter = new SelectedProblemsAdapter(this, getAllItems());
mRecyclerView.setAdapter(selectedProblemsAdapter);
}
#Override
public void onItemClick(YourItem yourItem) {
}
Step 3: Pass the interface through the adapter's constructor.
//Global variable of the interface
private onDataItemClickListener onclickListner;
// while instatiating the adapter
selectedProblemsAdapter = new SelectedProblemsAdapter(this, getAllItems(), onClickListener);
Step 4: In the onBindViewHolder method, use the interface instance(received through the constructor) to call the methods, which will help pass the data to the main activity/ activity.
public SelectedProblemsAdapter(Context context, Cursor cursor, OnDataItemClickListener listener) {
this.context = context;
this.cursor = cursor;
listener = listener;
}
#Override
public SelectedProblemsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.activity_selected_problems_content, null, false);
return new SelectedProblemsViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SelectedProblemsViewHolder holder, final int position) {
if (this.cursor != null){
holder.yourView.setOnClickListener(new View.OnClickListener() {
// onItemClick is the abstract function present in the interface.
listener.onItemClicked(" your data item ");
// here the data item/position etc, which you want to delete will be passed on to the main acticity.
}
}
}
#Override
public int getItemCount() {
return (null != cursor ? cursor.getCount(): 0);
}
public void update(Cursor cursor) {
this.cursor = cursor;
notifyDataSetChanged();
}
class SelectedProblemsViewHolder extends RecyclerView.ViewHolder{
TextView selectedProblems, selectedProblemPrice, selectedProblemTotal;
Button remove_problem_from_cart;
public SelectedProblemsViewHolder(View itemView) {
super(itemView);
selectedProblems = itemView.findViewById(R.id.selected_problems);
selectedProblemPrice = itemView.findViewById(R.id.selected_problem_price);
selectedProblemTotal = itemView.findViewById(R.id.selectedProblemTotal);
remove_problem_from_cart = itemView.findViewById(R.id.remove_problem_from_cart);
}
}
}
Step 5: Finally write the code to delete the object through the overridden interface method, in the main activity.
#Override
public void onItemClick(YourItem yourItem) {
yourItem.delete();
// you can use any number of functions to perform with your dataItem here.
selectedProblemsAdapter.update()
//call your update function here to change the list in recycler view.
}
Note: If you are using a view model and live data, you do not need to write the notifyDataSetChanged() function.The data gets updated automatically.
This will help you to delete or perform any number of operations on your data, which is passed from your adapter to the main activity.

How do I send the text of the ListView item that was clicked to my new activity?

I would like someone to click on an item in my ListView and then my new activity would start and the text of the item they clicked on should be set as the text of the TextView in my new activity. Currently with the following code, my TextView result is:
'com.example.draft.AnimalNames#31571cf'
Here is what I have in MainActivity.java:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String clickedName = (list.getItemAtPosition(position).toString());
Intent intent = new Intent(MainActivity.this, Profile.class);
intent.putExtra("clickedName", clickedName);
startActivity(intent);
System.out.println(clickedName);
}
});
And in my new activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_layout);
Intent intent = getIntent();
String clickedName = intent.getStringExtra("clickedName");
animalName = findViewById(R.id.textView);
animalName.setText(clickedName);
}
And in my AnimalNames.java file:
public class AnimalNames {
private String animalName;
public AnimalNames(String animalName) {
this.animalName = animalName;
}
public String getanimalName() {
return this.animalName;
}
}
I don't think it's relevant to my question but here is my ListViewAdapter.java file:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<AnimalNames> animalNamesList; // Declare a null variable
private ArrayList<AnimalNames> arraylist; // Declare a null array
public ListViewAdapter(Context context, List<AnimalNames> animalNamesList) {
mContext = context;
this.animalNamesList = animalNamesList;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<AnimalNames>();
this.arraylist.addAll(animalNamesList);
}
public class ViewHolder {
TextView name;
}
#Override
public int getCount() {
return animalNamesList.size();
}
#Override
public AnimalNames getItem(int position) {
return animalNamesList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.list_view_items, null); // Locate the TextViews in list_view_items.xml
holder.name = (TextView) view.findViewById(R.id.name);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.name.setText(animalNamesList.get(position).getanimalName());
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
animalNamesList.clear();
if (charText.length() == 0) {
animalNamesList.addAll(arraylist);
} else {
for (AnimalNames wp : arraylist) {
if (wp.getanimalName().toLowerCase(Locale.getDefault()).contains(charText)) {
animalNamesList.add(wp);
}
}
}
notifyDataSetChanged();
}
}
String clickedName = (list.getItemAtPosition(position).toString());
By calling toString() method, it will give you the object reference, which is what you get in the TextView.
According to your code, if you wish to see the Animal name, you should do (and fix the method name to getAnimalName):
String clickedName = ((AnimalNames)list.getItemAtPosition(position)).getanimalName();
getItemAtPosition() returns an Object, so you need to cast it to the correct class.

Recycler List Adapter is null after initialization

My app has a tab bar with three fragments. During the onCreate Method I call a function called initPlantList. This function initializes my RecyclerListAdapter.
private void initPlantList(){
RecyclerView rV = findViewById(R.id.plantsRecycler);
PlantListAdapter pLA = new PlantListAdapter(this);
Log.d("PLA", pLA.hasContext());
rV.setAdapter(pLA);
rV.setLayoutManager(new LinearLayoutManager(this));
}
I get this error java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference when I attempt to call rV.setAdapter(pLA);
Here is my Adapter Class
public class PlantListAdapter extends
RecyclerView.Adapter<PlantListAdapter.ViewHolder>{
private static final String TAG = "PlantListAdapter";
private Context mContext;
public PlantListAdapter(Context c){
this.mContext = c;
}
public String hasContext(){
if(this.mContext != null){
return mContext.getPackageResourcePath();
}
return "false";
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layoutplantlist, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Log.d(TAG, "onBindViewHolder: called.");
holder.image.setImageDrawable(MyApplication.myPlantList.get(position).getImage());
holder.plantName.setText(MyApplication.myPlantList.get(position).getName());
}
#Override
public int getItemCount() {
return MyApplication.myPlantList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
CircleImageView image;
TextView plantName;
RelativeLayout plantListItem;
public ViewHolder(View itemView) {
super(itemView);
image = itemView.findViewById(R.id.plantImage);
plantName = itemView.findViewById(R.id.plantName);
plantListItem = itemView.findViewById(R.id.plantListItem);
}
}
}
Any thoughts on why it is reffering to pLA as a null object reference?
It is not your adapter that is null. Its is your Recyclerview. You are using a fragment therefore you can’t use (findViewById).
You have to find it using the view you inflated.
Try this:
private void initPlantList(View v){
RecyclerView rV = v.findViewById(R.id.plantsRecycler);
PlantListAdapter pLA = new PlantListAdapter(this);
Log.d("PLA", pLA.hasContext());
rV.setAdapter(pLA);
rV.setLayoutManager(new LinearLayoutManager(this));
}
And when you call that method in your fragment onCrrateView() just pass the view as a parameter.
Hope it helps you

How to pass onClickHandler as parameter while setting adapter for a RecyclerView in a Fragment?

I made an Adapter for my recyclerView. This adapter works when I use on any xxxActivity.java but when I try to use is on a Fragment Its hows error. Doesn't let me Pass the onClickHandler() that I created in Adapter.
I am Setting Adapter Like this -
events_recyclerview.setAdapter(new FixedPlaceListAdapter(getContext(), placelist, mClickHandler)); //ClickListener doesn't work :'(
Another try was like --
events_recyclerview.setAdapter(new FixedPlaceListAdapter(getContext(), placelist, getmClickHandler()));
Here, I implemented getClickHandler() in the Fragment--
public FixedPlaceListAdapter.FixedPlaceListAdapterOnclickHandler getmClickHandler() {
return mClickHandler;
} //Still doesn't work :'(
and the Adapter Part--
Constructor like this-
public FixedPlaceListAdapter(Context mContext, List<PlaceBean>
placeBeanList, FixedPlaceListAdapterOnclickHandler mClickHandler) {
this.mContext = mContext;
this.placeBeanList = placeBeanList;
this.mClickHandler = mClickHandler;
}
I tried to do this ... but still doesn't work--
events_recyclerview.setAdapter(new FixedPlaceListAdapter(getContext(), placelist, FixedPlaceListAdapter.FixedPlaceListAdapterOnclickHandler.mClickhandler));
here is my full adapter code-
public class FixedPlaceListAdapter extends RecyclerView.Adapter<FixedPlaceListAdapter.FixedPlaceListAdapterViewHolder> {
private final FixedPlaceListAdapterOnclickHandler mClickHandler;
Context mContext;
List<PlaceBean> placeBeanList;
public FixedPlaceListAdapter(Context mContext, List<PlaceBean> placeBeanList, FixedPlaceListAdapterOnclickHandler mClickHandler) {
this.mContext = mContext;
this.placeBeanList = placeBeanList;
this.mClickHandler = mClickHandler;
}
public void setData(List<PlaceBean> placeBeanList) {
this.placeBeanList = placeBeanList;
notifyDataSetChanged();
}
#Override
public FixedPlaceListAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.top_list_single, parent, false);
return new FixedPlaceListAdapterViewHolder(view);
}
#Override
public void onBindViewHolder(FixedPlaceListAdapterViewHolder holder, int position) {
PlaceBean pb = placeBeanList.get(position);
holder.nameTextView.setText(pb.getName());
holder.addressTextView.setText(pb.getVicinity());
holder.rating.setRating(pb.getRating());
if (pb.getPhotoref() != null) {
String imageUrl = UrlsUtil.getSinglePhotoUrlString(mContext, pb.getPhotoref(), "350", "300");
Picasso.with(mContext)
.load(imageUrl)
.into(holder.thumbnailImage);
}
}
#Override
public int getItemCount() {
return placeBeanList.size();
}
public interface FixedPlaceListAdapterOnclickHandler {
void onClick(String id);
}
public class FixedPlaceListAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView nameTextView;
TextView addressTextView;
RatingBar rating;
ImageView thumbnailImage;
public FixedPlaceListAdapterViewHolder(View itemView) {
super(itemView);
nameTextView = (TextView) itemView.findViewById(R.id.place_name_now_in_list);
addressTextView = (TextView) itemView.findViewById(R.id.address_in_list);
rating = (RatingBar) itemView.findViewById(R.id.rating_single_place_in_list);
thumbnailImage = (ImageView) itemView.findViewById(R.id.place_image_thumb);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String placeID = placeBeanList.get(getAdapterPosition()).getPlaceref();
mClickHandler.onClick(placeID);
}
}
}
Need Help!
public class CategoryNewsListAdapter extends RecyclerView.Adapter<CategoryNewsListAdapter.ViewHolder> {
private List<CategoryNews> actors = new ArrayList<>();
private Context mContext;
private Queue<List<CategoryNews>> pendingUpdates =
new ArrayDeque<>();
**public interface NewsItemClickListener {
void onNewsItemClick(int pos, CategoryNews categoryNews, ImageView shareImageView);
}**
**NewsItemClickListener newsItemClickListener;**
public CategoryNewsListAdapter(List<CategoryNews> personList, Context mContext, NewsItemClickListener newsItemClickListener) {
this.actors.addAll(personList);
this.mContext = mContext;
this.newsItemClickListener = newsItemClickListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final LayoutInflater inflater = LayoutInflater.from(parent.getContext());
final View view = inflater.inflate(R.layout.particular_cat_news_list_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Log.d("BusinessSubCategoryListAdapter", "Bindviewholder without payload");
final CategoryNews newsCategory = actors.get(position);
holder.news_title.setText(newsCategory.getPostTitle());
holder.news_date.setText(newsCategory.getPostDate());
holder.news_category.setText(newsCategory.getCategoryName());
holder.news_description.setText(newsCategory.getPostContent());
// GlideApp
// .with(mContext).load(newsCategory.getPostImage())
// .placeholder(R.mipmap.ic_launcher) // can also be a drawable
// .error(R.drawable.placeholder_image) // will be displayed if the image cannot be loaded
// .crossFade()
// .into(holder.news_image);
Picasso.with(mContext).load(newsCategory.getPostImage()).placeholder(R.drawable.placeholder_image).error(R.drawable.placeholder_image).into(holder.news_image);
**holder.itemView.setOnClickListener(v -> {
newsItemClickListener.onNewsItemClick(position, newsCategory, holder.news_image);
});**
}
#Override
public void onBindViewHolder(ViewHolder holder, int position, List<Object> payloads) {
if (payloads.isEmpty()) {
// if empty, do full binding;
onBindViewHolder(holder, position);
return;
}
Bundle bundle = (Bundle) payloads.get(0);
String newTitle = bundle.getString("NAME_CHANGE");
if (newTitle != null) {
// add some animation if you want
final CategoryNews actor = actors.get(position);
holder.news_title.setText(actor.getPostTitle());
holder.news_date.setText(actor.getPostDate());
holder.news_category.setText(actor.getCategoryName());
holder.news_description.setText(actor.getPostContent());
}
}
public void addItems(List<CategoryNews> newItems) {
// record this value before making any changes to the existing list
int curSize = getItemCount();
// update the existing list
actors.addAll(newItems);
// curSize should represent the first element that got added
// newItems.size() represents the itemCount
notifyItemRangeInserted(curSize, newItems.size());
}
public void updtateItems(List<CategoryNews> newItems) {
// record this value before making any changes to the existing list
int curSize = getItemCount();
// update the existing list
actors.addAll(newItems);
// curSize should represent the first element that got added
// newItems.size() represents the itemCount
notifyItemRangeInserted(0,newItems.size()- getItemCount()-1);
}
#Override
public int getItemCount() {
return actors.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView news_title, news_date, news_category, news_description;
private ImageView news_image;
public ViewHolder(View itemView) {
super(itemView);
news_title = (TextView) itemView.findViewById(R.id.news_title);
news_date = (TextView) itemView.findViewById(R.id.news_date);
news_category = (TextView) itemView.findViewById(R.id.news_category);
news_description = (TextView) itemView.findViewById(R.id.news_description);
news_image = (ImageView) itemView.findViewById(R.id.news_image);
}
}
}
And In your activity
implements NewsItemClickListener
create object NewsItemClickListener newsItemClickListner;
inside oncreate newsItemClickListner=this; (you mush have implemented 1)
pass that object to recyclerview.
In adapter it is received by this
public CategoryNewsListAdapter(List personList, Context mContext, NewsItemClickListener newsItemClickListener) {
this.actors.addAll(personList);
this.mContext = mContext;
this.newsItemClickListener = newsItemClickListener;
}
In your activity
CategoryNewsListAdapter categoryNewsListAdapter= new CategoryNewsListAdapter(list,this,newsItemClickListner)
After doing all this your overriden method will be called when you click in item of recycler view where you have set onclick listner
Okay .. The Problem is Fixed now ...
I was passing the wrong value or maybe the method of passing the ClickHandler was wrong.
The Solution of the Problem :
I Created another Class for ClickHandler-
public class PlaceCardClickHandler implements
FixedPlaceListAdapter.FixedPlaceListAdapterOnclickHandler,
PlaceListAdapter.PlaceListAdapterOnclickHandler {
Context mContext;
public PlaceCardClickHandler(Context mContext) {
this.mContext = mContext;
}
#Override
public void onClick(String id) {
Intent intentToStartDetail = new Intent(mContext, PlaceDetailActivity.class);
intentToStartDetail.putExtra("id", id);
mContext.startActivity(intentToStartDetail);
}
}
and the change in the Fragment was like this- (Just passed a object from the ClickHandler class)
events_recyclerview.setAdapter(new FixedPlaceListAdapter(getContext(), placelist, new PlaceCardClickHandler(getContext())));

Categories