C.Sutherland C.Sutherland - 6 months ago 12
Java Question

Attempting to invoke virtual method on a null object reference

i'm fairly new to android development and I was recently completing my first app when I got a an error after clicking my "calculate" button. The error reads : java.lang.NullPointerException: Attempt to invoke virtual method 'void com.sta.salestaxaccumulator.ShoppingList.setCart(java.lang.String, int, double, double)' on a null object reference

I've read multiple post on here that seems similar to my issue but I can't seem to resolve mine. Below is portions of my code that I believe to be the issue. PLEASE any help would be appreciated. Thanks in advance

Calculator.java

CalculatorListener activityCommander;


public interface CalculatorListener{
public void addtoCart(View v,String itemName, int qty, double beforeTax, double afterTax);
}

@Override
public void onAttach(Context context) {
super.onAttach(context);
try{
activityCommander = (CalculatorListener) context;
}catch (ClassCastException e){
throw new ClassCastException(context.toString());
}
}

Editcost = (EditText)view.findViewById(R.id.editcost);
ItemText = (EditText)view.findViewById(R.id.itemText);
Editquantity = (EditText)view.findViewById(R.id.editquantity);
Calcost = (EditText)view.findViewById(R.id.calcost);
Rtax = (EditText)view.findViewById(R.id.rtax);

rgroup = (RadioGroup)view.findViewById(R.id.rgroup);

final ImageButton FieldButton = (ImageButton)view.findViewById(R.id.FieldButton);
final ImageButton TaxButton = (ImageButton)view.findViewById(R.id.TaxButton);
final ImageButton CalButton = (ImageButton)view.findViewById(R.id.CalButton);


CalButton.setOnClickListener(
new View.OnClickListener(){
public void onClick(View v){
results(v);
}

}
);

public void results (View view)
{



double taxValue = Double.parseDouble(Rtax.getText().toString()), cost = 0, newCost = 0;

int quantity = 1, radiobuttonID = rgroup.getCheckedRadioButtonId(), index;

String item = ItemText.getText().toString();


//FIELD VALIDATIONS
if(Editcost.getText().toString().isEmpty())
{
Toast show = Toast.makeText(getActivity(), "Cost is required!", Toast.LENGTH_SHORT);
show.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
show.show();
}


//CHECKS THE TAX VALUE IF IT NEEDS TO BE CONVERTED
if (taxValue > 1)
{
taxValue = taxValue / 100;
}
else
{
taxValue = taxValue * 1;
}

//CUSTOM VALIDATOR FOR QUANTITY FIELD
if (Editquantity.getText().toString().isEmpty())
{
quantity = 1;
}
else if (!Editquantity.getText().toString().isEmpty())
{
quantity = Integer.parseInt(Editquantity.getText().toString());
}


//DECIDE WHETHER TO USE TAX INCLUDED OR EXCLUDED
View radioButton = rgroup.findViewById(radiobuttonID);
index = rgroup.indexOfChild(radioButton);

if(index == 0)
{
newCost = (((cost = Double.parseDouble(Editcost.getText().toString())) * taxValue) + cost) * quantity;
}
else if (index == 1)
{
newCost = ((cost = Double.parseDouble(Editcost.getText().toString())) * quantity);
}


//PRINTS NEW COST TO SCREEN
Calcost.setText("" + newCost);


//CUSTOM HINT POP UP
if(!item.isEmpty())
{
Toast show = Toast.makeText(getActivity(), item+" was added to cart", Toast.LENGTH_LONG);
show.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
activityCommander.addtoCart(view,item, quantity, cost, newCost);
show.show();

}else if(item.isEmpty() & !Editcost.getText().toString().isEmpty())
{
if (index == 0 || index == 1)
{
Toast show = Toast.makeText(getActivity(),"Item was added to cart", Toast.LENGTH_LONG);
show.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
activityCommander.addtoCart(view,item, quantity, cost, newCost);
show.show();
}

}



}


Core.java

public class Core extends AppCompatActivity implements Calculator.CalculatorListener{

Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;

@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.core);
toolbar = (Toolbar)findViewById(R.id.toolBar);
setSupportActionBar(toolbar);
tabLayout = (TabLayout)findViewById(R.id.tabLayout);
viewPager = (ViewPager)findViewById(R.id.viewPager);
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragments(new Calculator(),"Calculator");
viewPagerAdapter.addFragments(new ShoppingList(), "Shopping Cart");
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);


}

@Override
public void addtoCart(View view,String itemName, int qty, double beforeTax, double afterTax) {
ShoppingList cart = (ShoppingList)getSupportFragmentManager().findFragmentById(R.id.shoppinglistfrag);
cart.setCart(view,itemName,qty,beforeTax,afterTax);
}


}

ShoppingList.java

public class ShoppingList extends Fragment {

private List<ListItems> myItems = new ArrayList<ListItems>();





public ShoppingList() {
// Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{

View view = inflater.inflate(R.layout.fragment_shopping_list, container, false);

//populatelist();
//populatelistview(view);

return view;

}

public void setCart(View view,String itemName, int qty, double beforeTax, double afterTax) {
myItems.add(new ListItems(R.drawable.thrash, itemName, qty, beforeTax, afterTax));
populatelistview(view);
}

/*private void populatelist()
{
//myItems.add(new ListItems(R.drawable.thrash, "Cornflakes", 1, 50.00, 60.00));
//myItems.add(new ListItems(R.drawable.thrash, "Cheese", 1, 80.00, 90.00));
//myItems.add(new ListItems(R.drawable.thrash, "Rice", 1, 40.00, 70.00));
//myItems.add(new ListItems(R.drawable.thrash, "Oatmeal", 2, 35.00, 62.00));
}*/

private void populatelistview(View view)
{
ArrayAdapter<ListItems> adapter = new MyListAdapter();
ListView listView = (ListView)view.findViewById(R.id.listView);
listView.setAdapter(adapter);
}


private class MyListAdapter extends ArrayAdapter<ListItems>
{
public MyListAdapter()
{
super(getActivity(), R.layout.custom_row, myItems);
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
//Ensures we have a view to work with (may have been given null)
View itemView = convertView;
if (itemView == null) {
itemView = getActivity().getLayoutInflater().inflate(R.layout.custom_row, parent, false);
}

//Finds the item to work with
final ListItems currentitem = myItems.get(position);

//Fills the view
final ImageView imageView = (ImageView) itemView.findViewById(R.id.Thrash);
imageView.setImageResource(currentitem.getIconID());

//Item Name
TextView name = (TextView) itemView.findViewById(R.id.ItemName);
name.setText(currentitem.getItemName());

//Item Qty
TextView qty = (TextView) itemView.findViewById(R.id.QuantityValue);
qty.setText("" + currentitem.getQty());

//Before Tax
TextView btax = (TextView) itemView.findViewById(R.id.BeforeTaxValue);
btax.setText("" + currentitem.getBeforeTax());

//After Tax
TextView atax = (TextView) itemView.findViewById(R.id.AfterTaxValue);
atax.setText("" + currentitem.getAfterTax());


imageView.setTag(currentitem);

imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myItems.remove(myItems.get(position));
notifyDataSetChanged();
}

});

return itemView;
}

}



}

Answer

You should check if your cart is null before calling one of it's methods.

ShoppingList cart = (ShoppingList)getSupportFragmentManager().findFragmentById(R.id.shoppinglistfrag);
if(cart != null){    
    cart.setCart(view,itemName,qty,beforeTax,afterTax);
}
else{
    Log.e(TAG, "null cart");
}

From the FragmentManager docs:

Finds a fragment that was identified by the given id either when inflated from XML or as the container ID when added in a transaction. This first searches through fragments that are currently added to the manager's activity; if no such fragment is found, then all fragments currently on the back stack associated with this ID are searched.

So, it seems as though you have never created or used the ShoppingList fragment, so the FragmentManager can't find it.

Try adding the ShoppingList to your Activity as a local variable and initializing it in your MainActivity onCreate...

public class Core extends AppCompatActivity implements Calculator.CalculatorListener{

    Toolbar toolbar;
    TabLayout tabLayout;
    ViewPager viewPager;
    ViewPagerAdapter viewPagerAdapter;
    ShoppingList mShoppingList;

    @Override
    protected  void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        ...

        mShoppingList = new ShoppingList();

    }

    @Override
    public void addtoCart(View view,String itemName, int qty, double beforeTax, double afterTax) {
        mShoppingList.setCart(view,itemName,qty,beforeTax,afterTax);
    }
}