2016-05-17 158 views
-1

請幫忙。 在開發了一個接口以在片段之間進行通信「計算器」(發送信息)「ShoppingList」(接收信息)我似乎無法獲取要添加到我的ArrayList中的信息。我知道這些信息已經發送過來,但我似乎無法將它添加到列表中,以便將它合併到我的列表視圖中。 另外,我不應該。如果我硬編碼 中的信息,例如:myItems.add(new ListItems(R.drawable.thrash,「Cornflakes」,1,50.00,60.00)); 它工作正常將數據添加到arraylist

請幫助。

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

請提供完整的Logcat輸出,然後我可以更新我的答案。 – RScottCarson

回答

1

你應該檢查一下你的車是在調用它的方法之一,前空。

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

FragmentManager文檔:

查找所識別由給定id的片段或者當從XML或作爲交易添加時容器ID充氣 。 這首先搜索當前添加到 經理活動的片段;如果沒有找到這樣的片段,則搜索當前在與該ID相關聯的後棧上的所有片段 。

因此,看起來好像您從未創建或使用ShoppingList片段,因此FragmentManager無法找到它。

嘗試添加ShoppingList你的活動作爲一個局部變量,並在您的MainActivity的onCreate初始化它...

​​3210

編輯:

至於你ShoppingList類,讓你的ListViewArrayAdapter類變量。然後你可以從你的populatelist()方法訪問它們。將項目添加到您的列表後,請致電adapter.notifyDataSetChanged()

備註: 以後再問一個新問題,不要完全改變現有的問題。它讓未來尋找答案的其他人感到困惑。

+0

謝謝Man.As懷疑它是空的。爲什麼?基於代碼我有東西應該已經傳遞給setCart(view,itemName,qty,beforeTax,afterTax)方法。 –

+0

我更新了答案,希望它有幫助。 – RScottCarson

+0

謝謝,我檢查了你的更新並對我自己做了一些修改。請參閱上面顯示的代碼示例。我這次在core.java中包含了對指定片段的引用(「ShopFrag」),但是現在我遇到了上面圖像鏈接中顯示的新錯誤。 –