如何将两个固定标签添加到我的活动中,并将listview导入该标签

时间:2016-06-09 15:11:34

标签: android listview tabs

您好我正在创建一个带有标签的应用,我正在使用一个名为Cart的活动类,如下所示

public class Cart extends AppCompatActivity {
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;


@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_mycart);
    mFragmentManager = getSupportFragmentManager();
    mFragmentTransaction = mFragmentManager.beginTransaction();
    mFragmentTransaction.replace(R.id.containerView1,new MyCartTab()).commit();


}
}

在此活动中,我想调用下面代码中显示的Two Fixed标签

public class MyCartTab extends Fragment {

public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 2 ;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View x =  inflater.inflate(R.layout.mycartdata,null);
    tabLayout = (TabLayout) x.findViewById(R.id.carttabs);
    viewPager = (ViewPager) x.findViewById(R.id.cartviewpager);

    viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
    tabLayout.post(new Runnable() {
        @Override
        public void run() {
            tabLayout.setupWithViewPager(viewPager);
        }
    });
    return x;

}

class MyAdapter extends FragmentPagerAdapter {

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

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return new My_Menu_List();
            case 1:
                return new My_Extra_List();
            }
        return null;
    }

    @Override
    public int getCount() {

        return int_items;

    }
    @Override
    public CharSequence getPageTitle(int position) {

        switch (position) {
            case 0:
                return "MyCart";
            case 1:
                return "MyExtras";
        }
        return null;
    }
}
}

这是一个Tab活动文件MyCart

public class My_Menu_List extends android.support.v4.app.ListFragment {

ArrayList<Product> cart_list = new ArrayList<Product>();
ArrayList<Extra> ecart_list = new ArrayList<Extra>();
SQLiteDatabase sqLite;
int count=0;
int totalCartItemCount =0;
int totalCartValue = 0;
View view;
final String[] qtyValues = {"1","2","3","4","5","6","7","8","9","10"};


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.myextralist, container, false);

    TextView itemText = (TextView) view.findViewById(R.id.item_text);
    TextView itemCount = (TextView) view.findViewById(R.id.cart_item_count);
    TextView totalAmount = (TextView) view.findViewById(R.id.total_cart_amount);
    Button checkout_cart = (Button) view.findViewById(R.id.checkout_cart);
    ListView lv2=(ListView) view.findViewById(R.id.my_cart_list);
    TextView cartEmpty = (TextView) view.findViewById(R.id.mycart_empty);
    checkout_cart.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            startActivity(new Intent(getActivity(),Customer_Payment.class));
        }
    });

    getCartData();
    try{
        totalCartItemCount = (cart_list.size()+ecart_list.size());
        totalCartValue =0;
        for (int temp1=0; temp1 < cart_list.size(); temp1++) {
            for (int temp2 = 0; temp2 < ecart_list.size(); temp2++) {
                totalCartValue = totalCartValue + Integer.parseInt(cart_list.get(temp1).getFinalValue()) + Integer.parseInt(ecart_list.get(temp2).getExtraCheckoutPrice());
            }
        }
    }catch(NumberFormatException n){n.printStackTrace();}

    if (totalCartItemCount == 0)
    {
        itemText.setVisibility(view.INVISIBLE);
        itemCount.setVisibility(view.INVISIBLE);
        totalAmount.setVisibility(view.INVISIBLE);
        checkout_cart.setVisibility(view.INVISIBLE);
        lv2.setVisibility(view.INVISIBLE);
        cartEmpty.setVisibility(view.VISIBLE);
    }

    else
    {
        itemText.setVisibility(view.VISIBLE);
        itemCount.setVisibility(view.VISIBLE);
        totalAmount.setVisibility(view.VISIBLE);
        checkout_cart.setVisibility(view.VISIBLE);
        lv2.setVisibility(view.VISIBLE);
        cartEmpty.setVisibility(view.INVISIBLE);

    }
    itemCount.setText("("+ totalCartItemCount + ")");
    totalAmount.setText("("+ totalCartValue +")");
    lv2.setAdapter(new custom_list_one(getActivity(),cart_list));

    return view;
}

class custom_list_one extends BaseAdapter
{
    private LayoutInflater layoutInflater;
    ViewHolder holder;
    private ArrayList<Product> cartList=new ArrayList<Product>();
    int cartCounter;
    Context context;

    public custom_list_one(Context context, ArrayList<Product> cart_list) {
        layoutInflater = LayoutInflater.from(context);
        this.cartList=cart_list;
        this.cartCounter= cartList.size();
        this.context = context;
    }

    @Override
    public int getCount() {

        return cartCounter;
    }

    @Override
    public Object getItem(int arg0) {

        return cartList.get(arg0);
    }

    @Override
    public long getItemId(int arg0) {

        return arg0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent)
    {
        Product tempProduct = cart_list.get(position);

        if (convertView == null)
        {
            convertView = layoutInflater.inflate(R.layout.listone_custom, null);
            holder = new ViewHolder();
            holder.name = (TextView) convertView.findViewById(R.id.menu_name);
            holder.price = (TextView) convertView.findViewById(R.id.menu_price);
            holder.qty = (Spinner) convertView.findViewById(R.id.spinner1);
            holder.cancel = (ImageButton) convertView.findViewById(R.id.delete);
            holder.qty_text =(TextView) convertView.findViewById(R.id.qty_text);
            holder.final_value = (TextView) convertView.findViewById(R.id.menu_price);

            convertView.setTag(holder);
        }
        else
        {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.name.setText(tempProduct.getName());
        holder.price.setText("Rs "+tempProduct.getPrice());

        ArrayAdapter<String> aa=new ArrayAdapter<String>(context,R.layout.qty_spinner_item,qtyValues);
        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        holder.qty.setAdapter(aa);
        holder.qty.setSelection(Integer.parseInt(tempProduct.getMenuQty())-1);
        holder.final_value.setText("Rs "+Integer.parseInt(tempProduct.getPrice())*Integer.parseInt(tempProduct.getMenuQty()));
        holder.cancel.setOnClickListener(new MyPersonalClickListener("button_delete",tempProduct,context));
        holder.qty.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,int selectionIndex, long id)
            {
                if ((parent.getSelectedItemPosition()+1) != Integer.parseInt(cart_list.get(position).getMenuQty())) {
                    sqLite=context.openOrCreateDatabase("mahatiffin", context.MODE_PRIVATE, null);
                    sqLite.execSQL("UPDATE CART SET MENU_QTY ='"+ (parent.getSelectedItemPosition()+1)+"' WHERE NAME ='"+cart_list.get(position).getName()+"'");
                    sqLite.execSQL("UPDATE CART SET FINAL_VALUE='" + (parent.getSelectedItemPosition()+1) * Integer.parseInt(cart_list.get(position).getPrice())  +"' WHERE NAME ='"+cart_list.get(position).getName()+"'");
                    sqLite.close();
                    getCartData();
                    notifyDataSetChanged();
                    //refresh data outside the listview - Cart Total, Total Items, Shipping Cost etc
                    View parentView = (View) view.getParent().getParent().getParent().getParent();

                    TextView txtTotalItems = (TextView) parentView.findViewById(R.id.cart_item_count);
                    TextView txtTotalAmount = (TextView) parentView.findViewById(R.id.total_cart_amount);

                    try{
                        totalCartItemCount = (cart_list.size()+ecart_list.size());
                        totalCartValue =0;
                        for (int temp1=0; temp1 < cart_list.size(); temp1++) {
                            for (int temp2 = 0; temp2 < ecart_list.size(); temp2++) {
                                totalCartValue = totalCartValue + Integer.parseInt(cart_list.get(temp1).getFinalValue()) + Integer.parseInt(ecart_list.get(temp2).getExtraCheckoutPrice());
                            }
                        }
                    }catch(NumberFormatException n){n.printStackTrace();}

                    txtTotalItems.setText("("+ totalCartItemCount + ")");
                    txtTotalAmount.setText("("+ totalCartValue +")");

                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0)
            {

            }
        });
        // notifyDataSetChanged();
        return convertView;
    }
    class ViewHolder
    {
        TextView name;
        TextView price;
        TextView qty_text;
        ImageButton cancel;
        Spinner qty;
        TextView final_value;

    }
}

public class MyPersonalClickListener implements View.OnClickListener
{

    String button_name;
    Context context;
    Product name;

    public MyPersonalClickListener(String button_name, Product name, Context context)
    {
        this.context=context;
        this.name = name;
        this.button_name = button_name;
    }

    @Override
    public void onClick(View v)
    {
        if (button_name == "button_delete")
        {
            sqLite=context.openOrCreateDatabase("mahatiffin", context.MODE_PRIVATE, null);
            sqLite.execSQL("DELETE FROM CART WHERE NAME ='"+ name.getName()+"'");
            sqLite.close();
            Toast.makeText(context,"Item "+name.getName()+" delete from Cart", Toast.LENGTH_SHORT).show();

            getCartData();
            View lView = (View) v.getParent().getParent();
            ((ListView) lView).setAdapter(new custom_list_one(context,cart_list));

            TextView txtTotalAmount = (TextView) view.findViewById(R.id.total_cart_amount);
            TextView txtTotalItems = (TextView) view.findViewById(R.id.cart_item_count);
            TextView itemText = (TextView) view.findViewById(R.id.item_text);
            Button checkout_cart = (Button) view.findViewById(R.id.checkout_cart);
            ListView listview2=(ListView) view.findViewById(R.id.my_cart_list);
            TextView cartEmpty = (TextView) view.findViewById(R.id.mycart_empty);

            try{
                totalCartItemCount = (cart_list.size()+ecart_list.size());
                totalCartValue =0;
                for (int temp1=0; temp1 < cart_list.size(); temp1++) {
                    for (int temp2 = 0; temp2 < ecart_list.size(); temp2++) {
                        totalCartValue = totalCartValue + Integer.parseInt(cart_list.get(temp1).getFinalValue()) + Integer.parseInt(ecart_list.get(temp2).getExtraCheckoutPrice());
                    }
                }
            }catch(NumberFormatException n){n.printStackTrace();}

            txtTotalItems.setText("("+ totalCartItemCount + ")");
            txtTotalAmount.setText("("+ totalCartValue +")");

            if (totalCartItemCount == 0)
            {
                itemText.setVisibility(view.INVISIBLE);
                txtTotalItems.setVisibility(view.INVISIBLE);
                txtTotalAmount.setVisibility(view.INVISIBLE);
                checkout_cart.setVisibility(view.INVISIBLE);
                listview2.setVisibility(view.INVISIBLE);
                cartEmpty.setVisibility(view.VISIBLE);
            }

            else
            {
                itemText.setVisibility(view.VISIBLE);
                txtTotalItems.setVisibility(view.VISIBLE);
                txtTotalAmount.setVisibility(view.VISIBLE);
                checkout_cart.setVisibility(view.VISIBLE);
                listview2.setVisibility(view.VISIBLE);
                cartEmpty.setVisibility(view.INVISIBLE);

            }

        }

    }

}
public void getCartData()
{
    Product tempCartItem;
    cart_list.clear();
    sqLite=getActivity().openOrCreateDatabase("mahatiffin", getActivity().MODE_PRIVATE, null);
    sqLite.execSQL("CREATE TABLE IF NOT EXISTS TB_MENU (ID INTEGER primary key autoincrement,NAME VARCHAR, DESCRIPTION VARCHAR, PRICE INTEGER)");
    sqLite.execSQL("CREATE TABLE IF NOT EXISTS CART (ID INTEGER primary key autoincrement, NAME VARCHAR, DESCRIPTION VARCHAR, PRICE INTEGER, MENU_QTY INTEGER, FINAL_VALUE INTEGER)");
    Cursor c=sqLite.rawQuery("SELECT  * FROM CART",null);
    count=0;
    if(c.moveToFirst())
    {
        do{
            tempCartItem = new Product();
            tempCartItem.setName(c.getString(c.getColumnIndex("NAME")));
            tempCartItem.setPrice(c.getString(c.getColumnIndex("PRICE")));
            tempCartItem.setMenuQty(c.getString(c.getColumnIndex("MENU_QTY")));
            tempCartItem.setFinalValue(c.getString(c.getColumnIndex("FINAL_VALUE")));
            cart_list.add(tempCartItem);
            count++;
        }while(c.moveToNext());

    }
    sqLite.close();
}
}

我的代码是正确的,但当我点击进入购物车活动页面时,它会显示错误。这是我的logcat

  

06-09 20:18:46.260 30923-30923 / com.androidbelieve.MahaTiffin   E / AndroidRuntime:致命异常:主要                                                                                  显示java.lang.NullPointerException                                                                                      在   com.androidbelieve.MahaTiffin.My_Menu_List.onCreateView(My_Menu_List.java:84)                                                                                      在   android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)                                                                                      在   android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)                                                                                      在   android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)                                                                                      在   android.support.v4.app.BackStackRecord.run(BackStackRecord.java:742)                                                                                      在   android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)                                                                                      在   android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)                                                                                      在   android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)                                                                                      在android.support.v4.view.ViewPager.populate(ViewPager.java:1177)                                                                                      在android.support.v4.view.ViewPager.populate(ViewPager.java:1025)                                                                                      在android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1545)                                                                                      在android.view.View.measure(View.java:15172)                                                                                      在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4842)                                                                                      在   android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1390)                                                                                      在android.widget.LinearLayout.measureVertical(LinearLayout.java:681)                                                                                      在android.widget.LinearLayout.onMeasure(LinearLayout.java:574)                                                                                      在android.view.View.measure(View.java:15172)                                                                                      在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4842)                                                                                      在android.widget.FrameLayout.onMeasure(FrameLayout.java:310)                                                                                      在android.view.View.measure(View.java:15172)                                                                                      在   android.widget.RelativeLayout.measureChildHorizo​​ntal(RelativeLayout.java:617)                                                                                      在android.widget.RelativeLayout.onMeasure(RelativeLayout.java:399)                                                                                      在android.view.View.measure(View.java:15172)                                                                                      在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4842)                                                                                      在android.widget.FrameLayout.onMeasure(FrameLayout.java:310)                                                                                      在   android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)                                                                                      在android.view.View.measure(View.java:15172)                                                                                      在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4842)                                                                                      在   android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1390)                                                                                      在android.widget.LinearLayout.measureVertical(LinearLayout.java:681)                                                                                      在android.widget.LinearLayout.onMeasure(LinearLayout.java:574)                                                                                      在android.view.View.measure(View.java:15172)                                                                                      在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4842)                                                                                      在android.widget.FrameLayout.onMeasure(FrameLayout.java:310)                                                                                      在android.view.View.measure(View.java:15172)                                                                                      在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4842)                                                                                      在   android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1390)                                                                                      在android.widget.LinearLayout.measureVertical(LinearLayout.java:681)                                                                                      在android.widget.LinearLayout.onMeasure(LinearLayout.java:574)                                                                                      在android.view.View.measure(View.java:15172)                                                                                      在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4842)                                                                                      在android.widget.FrameLayout.onMeasure(FrameLayout.java:310)                                                                                      在   com.android.internal.policy.impl.PhoneWindow $ DecorView.onMeasure(PhoneWindow.java:2167)                                                                                      在android.view.View.measure(View.java:15172)                                                                                      在android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1850)                                                                                      在android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1102)                                                                                      在android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1275)                                                                                      在android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)                                                                                      在   android.view.ViewRootImpl $ TraversalRunnable.run(ViewRootImpl.java:4222)                                                                                      在   android.view.Choreographer $ CallbackRecord.run(Choreographer.java:725)                                                                                      在android.view.Choreographer.doCallbacks(Choreographer.java:555)                                                                                      在android.view.Choreographer.doFrame(Choreographer.java:525)                                                                                      在   android.view.Choreographer $ FrameDisplayEventReceiver.run(Choreographer.java:711)                                                                                      在android.os.Handler.handleCallback(Handler.java:615)                                                                                      在android.os.Handler.dispatchMessage(Handler.java:92)                                                                                      在android.os.Looper.loop(Looper.java:137)                                                                                      在android.app.ActivityThread.main(ActivityThread.java:4918)                                                                                      at java.lang.reflect.Method.invokeNative(Native Method)                                                                                     在java.lang.reflect.Method.invoke(

我是android的新手,这是我的第一个应用程序,所以请帮助解决这个错误。谢谢你提前。任何人请帮助我,我不知道我能为此NullPointerException错误做些什么。

这是我的第一个标签的XML文件,我的第二个标签xml文件也是相同的,只有名称是diff ..

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
xmlns:android="http://schemas.android.com/apk/res/android">

<ListView
    android:id="@+id/my_cart_list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_above="@+id/rr"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_weight="1"
    android:divider="#0af"/>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:id="@+id/rr"
    android:background="#FA0"
    android:layout_marginBottom="0dp">

    <TextView
        android:id="@+id/item_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Items"
        android:textColor="#000"
        android:textSize="17sp"
        android:layout_marginTop="15dp"
        android:layout_marginLeft="20dp"/>

    <TextView
        android:id="@+id/cart_item_count"
        android:layout_toRightOf="@+id/item_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="(2)"
        android:textColor="#000"
        android:textSize="17sp"
        android:layout_marginTop="15dp"
        android:layout_marginLeft="5dp"/>


    <TextView
        android:id="@+id/total_cart_amount"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000"
        android:textSize="20sp"
        android:layout_alignTop="@+id/cart_item_count"
        android:layout_centerHorizontal="true" />

    <Button
        android:id="@+id/checkout_cart"
        android:layout_width="wrap_content"
        android:layout_height="25dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="4dp"
        android:layout_marginTop="4dp"
        android:padding="3dp"
        android:text="Checkout >>"
        android:textSize="16dp" />

    <TextView
        android:id="@+id/mycart_empty"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="CART IS EMPTY"
        android:gravity="center"
        android:textColor="#000"
        android:textSize="22sp"
        android:layout_marginTop="12dp"/>
</RelativeLayout>

</RelativeLayout>

0 个答案:

没有答案