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

Adding data to arraylist

Please help.
After developing an interface to communicate between fragments "Calculator" (Sending Info) and "ShoppingList" (Receiving Info) I can't seem to get the information to be added to my ArrayList. I know the information was sent over but I just can't seem to get it added to the list in order to incorporate it in my listview.
Also, I should not. If I hardcode the information in
eg: myItems.add(new ListItems(R.drawable.thrash, "Cornflakes", 1, 50.00, 60.00));
it works fine

Please Help.

Calculator.java

public class Calculator extends Fragment {


private static EditText ItemText, Editcost, Editquantity, Calcost, Rtax;
private static RadioGroup rgroup;

CalculatorListener activityCommander;


public interface CalculatorListener{
public void addtoCart(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());
}
}


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


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_calculator, container, false);


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);

Rtax.setEnabled(false);
Calcost.setEnabled(false);

ItemText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
v.setBackgroundResource(R.drawable.edittxt);
} else {
v.setBackgroundResource(R.drawable.edittxtfocus);
}
}
}
);

Calcost.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
v.setBackgroundResource(R.drawable.edittxtfocus);
} else {
v.setBackgroundResource(R.drawable.edittxt);
}
}
}
);

Editcost.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
v.setBackgroundResource(R.drawable.edittxtfocus);
} else {
v.setBackgroundResource(R.drawable.edittxt);
}
}
}
);
Editquantity.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
v.setBackgroundResource(R.drawable.edittxtfocus);
} else {
v.setBackgroundResource(R.drawable.edittxt);
}
}
}
);



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

}
);

return view;

}



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(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(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(String itemName, int qty, double beforeTax, double afterTax) {
ShoppingList mShoppingList = (ShoppingList) getSupportFragmentManager().findFragmentById(R.id.ShopFrag);
if(mShoppingList != null)
{
mShoppingList.populatelist(itemName, qty, beforeTax, afterTax);
}
else{
Log.e(Tag,"Cart is Null");
}

}


ShoppingList.java

package com.sta.salestaxaccumulator;


import android.app.LauncherActivity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;


public class ShoppingList extends Fragment {

public 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);
populatelistview(view);
//setCart();
return view;

}


public void populatelist(String itemName, int qty, double beforeTax, double afterTax)
{


myItems.add(new ListItems(R.drawable.thrash, itemName, qty, beforeTax, afterTax));
//myItems.add(new ListItems(R.drawable.thrash, "Cornflakes", 1, 50.00, 60.00));

/*Toast show = Toast.makeText(getActivity(),itemName+" is here", Toast.LENGTH_LONG);
show.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
show.show();*/
}

/*public void setCart(String itemName, int qty, double beforeTax, double afterTax)
{
//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));
}*/


public 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
ListItems currentitem = myItems.get(position);

//Fills the view
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;
}

}



}


ListItems.java

package com.sta.salestaxaccumulator;


public class ListItems {
private int IconID;
private String ItemName;
private int Qty;
private double BeforeTax, AfterTax;

public ListItems(int iconID, String itemName, int qty, double beforeTax, double afterTax) {
IconID = iconID;
ItemName = itemName;
Qty = qty;
BeforeTax = beforeTax;
AfterTax = afterTax;
}

public int getIconID() {
return IconID;
}

public String getItemName() {
return ItemName;
}

public int getQty() {
return Qty;
}

public double getBeforeTax() {
return BeforeTax;
}

public double getAfterTax() {
return AfterTax;
}

}


Core.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http//schemas.android.com/tools"
xmlns:tools2="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.sta.salestaxaccumulator.Core">

<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:id="@+id/AppBarFrag">

<include
android:layout_height="wrap_content"
android:layout_width="match_parent"
layout="@layout/toolbar_layout"/>

<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tabLayout"
app:tabMode="fixed"
app:tabGravity="fill">

</android.support.design.widget.TabLayout>

</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/viewPager"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/AppBarFrag">

<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.sta.salestaxaccumulator.Calculator"
tools2:layout="@layout/fragment_calculator"
android:id="@+id/CalcuFrag" />

<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.sta.salestaxaccumulator.ShoppingList"
tools2:layout="@layout/fragment_shopping_list"
android:id="@+id/ShopFrag"/>

</android.support.v4.view.ViewPager>




</RelativeLayout>


ViewPagerAdapter.java

public class ViewPagerAdapter extends FragmentPagerAdapter{


ArrayList<Fragment> fragments = new ArrayList<>();
ArrayList<String> tabTitles = new ArrayList<>();

public void addFragments(Fragment fragments, String titles)
{
this.fragments.add(fragments);
this.tabTitles.add(titles);

}

public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}

@Override
public Fragment getItem(int position) {
return fragments.get(position);
}

@Override
public int getCount() {
return fragments.size();
}

@Override
public CharSequence getPageTitle(int position) {
return tabTitles.get(position);
}
}

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);
    }
}

Edit:

As for your ShoppingList class, make your ListView and ArrayAdapter class variables. Then you can access them from your populatelist() method. After adding the items to your your list, call adapter.notifyDataSetChanged().

Note: In the future, ask a new question, don't completely change the existing question. It gets confusing for others coming to look for answers in the future.

Comments