7

我正在尝试显示项目列表以及 GrandTotal Amount,但是每当我在获取NullPointerException的代码中使用此代码时,请参阅下面的代码:

if (Constants.sItem_Detail.size() > 0) {
    Double mGTotal = Double.parseDouble(Constants.sItem_Detail.get(0).get(com.example.sample.CartAdapter.KEY_TOTAL));
    for (int i = 1; i < Constants.sItem_Detail.size(); i++) {   
        mGTotal = mGTotal + Double.parseDouble(Constants.sItem_Detail.get(i).get(com.example.sample.CartAdapter.KEY_TOTAL));
    }

    mGrandTotal = String.valueOf(new DecimalFormat("##.#").format(mGTotal));
    mTxtViewGrandTotal.setText(mGrandTotal);
    myTextVeiwGrandTotal.setText(mGrandTotal);  

特别是,当我使用这些行得到错误时:

Double mGTotal = Double.parseDouble(Constants.sItem_Detail.get(0).get(com.example.sample.CartAdapter.KEY_TOTAL));

mGTotal = mGTotal + Double.parseDouble(Constants.sItem_Detail.get(i).get(com.example.sample.CartAdapter.KEY_TOTAL));

我试过下面的代码:

if (Constants.sItem_Detail.size() > 0) { 
    Toast.makeText(getApplicationContext(), "Constants is Greater Than 0", Toast.LENGTH_LONG).show(); 
} else { 
   Toast.makeText(getApplicationContext(), "Constants is Less Than < 0", Toast.LENGTH_LONG).show(); 
} 

并且获取常量大于 0,并且显示购物车中的项目数为 1,但是每当我在代码中使用此行时出现问题,这是从适配器获取价值的正确方法吗?

Double.parseDouble(Constants.sItem_Detail.get(0).get(com.example.sample.CartAdap‌​‌​ter.KEY_TOTAL));

实际上,我正在计算 Adapter 类中每个项目的总量,现在试图在 Activity 中将所有总量的总和显示为总计,但是遇到问题,告诉我我在哪里做错了?

这是完整的代码:

CartActivity.java:

protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cart);

    mLstView1 = (ListView) findViewById(R.id.listView1);
    mTxtViewGrandTotal = (TextView) findViewById(R.id.bill_amount);
    myTextVeiwGrandTotal =(TextView) findViewById(R.id.mTxtViewGrandTotalValue);
    mItems = (TextView) findViewById(R.id.total_items);

    mTax =(TextView) findViewById(R.id.taxes);
    mDeliveryCharges =(TextView) findViewById(R.id.delivery_charges);
    mDiscount =(TextView) findViewById(R.id.discount);
    mPackaging =(TextView) findViewById(R.id.packaging);

    if (Constants.sItem_Detail.size() > 0) {
        Double mGTotal = Double.parseDouble(Constants.sItem_Detail.get(0).get(com.example.sample.CartAdapter.KEY_TOTAL));
        for (int i = 1; i < Constants.sItem_Detail.size(); i++) {   
            mGTotal = mGTotal + Double.parseDouble(Constants.sItem_Detail.get(i).get(com.example.sample.CartAdapter.KEY_TOTAL));
        }

        mGrandTotal = String.valueOf(new DecimalFormat("##.#").format(mGTotal));
        mTxtViewGrandTotal.setText(mGrandTotal);
        myTextVeiwGrandTotal.setText(mGrandTotal);      

        mTaxes = String.valueOf(mTax);
        mTax.setText("0");
        mDelivery = String.valueOf(mDeliveryCharges);
        mDeliveryCharges.setText("0");

        mTotal = String.valueOf(Constants.sItem_Detail.size());
        mItems.setText(mTotal);                 
    }

    mViewCartAdpt = new CartAdapter(CartActivity.this);

    mLstView1.setAdapter(mViewCartAdpt);
    mLstView1.setOnItemClickListener(new OnItemClickListener() {            
        public void onItemClick(AdapterView<?> parent, View v, final int position, long id) {
                // 
            }
        }); 
    }

    // Called when the activity begins interacting with the user
    @Override
    protected void onResume() {
        super.onResume();
        mViewCartAdpt.notifyDataSetChanged();
    }   
}

CartAdapter.java:

 public class CartAdapter extends BaseAdapter {



  public static final String LOG_TAG = "CartAdapter";

    public static final String KEY_TITLE = "title";
    public static final String KEY_COST = "cost";
    public static final String KEY_QTY = "qty";
    public static final String KEY_TOTAL = "total";

    Activity activity;
    LayoutInflater inflater;
    ImageButton mImgBtnDelete;  
    ListView listView;

    private double itemamount = 0;
    private int itemquantity = 0;



    public CartAdapter(Activity a) {
        // TODO Auto-generated constructor stub
        activity = a;
        inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public int getCount() {
        // TODO Auto-generated method stub
        return Constants.sItem_Detail.size();
    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View vi = convertView;
        if (convertView == null)
            vi = inflater.inflate(R.layout.listrow_cart, null);  // listrow_cart

            vi.setClickable(true);
            vi.setFocusable(true);          

            vi.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) 
                {                       

                }       
            }); 

            mImgBtnDelete = (ImageButton) vi
                    .findViewById(R.id.mImgBtnDelete);
                mImgBtnDelete.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    // TODO Auto-generated method stub              
                    Constants.sItem_Detail.remove(position);
                    notifyDataSetChanged();
                    Intent mInViewCartRefresh = new Intent(activity,
                            CartActivity.class);
                    activity.startActivity(mInViewCartRefresh);
                    activity.finish();          
                }
            });

            final TextView title = (TextView) vi.findViewById(R.id.title);
            final EditText qty = (EditText) vi.findViewById(R.id.qty);
            final TextView cost = (TextView) vi.findViewById(R.id.cost);
            final TextView total = (TextView) vi.findViewById(R.id.total);


            HashMap<String, String> item = new HashMap<String, String>();
            item = Constants.sItem_Detail.get(position);

            // Setting all values in listview

            title.setText(item.get(com.example.sample.ItemsActivity.KEY_TITLE));
            cost.setText(item.get(com.example.sample.ItemsActivity.KEY_COST));
            qty.setText("1");

            itemquantity = Integer.parseInt(qty.getText().toString());
            itemamount = Double.parseDouble(cost.getText().toString());
            total.setText(new DecimalFormat("##.#").format(itemamount*itemquantity));

            qty.addTextChangedListener(new TextWatcher() {
                public void onTextChanged(CharSequence s, int start, int before,
                        int count) {
                    // TODO Auto-generated method stub
                    if (!qty.getText().toString().equals("")
                            || !qty.getText().toString().equals("")) {

                        // accept quantity by user
                        itemquantity = Integer.parseInt(qty.getText()
                                .toString());

                        // changes in total amount as per change in qty (entered by user)
                        total.setText(new DecimalFormat("##.#").format(itemamount*itemquantity));
                    } else {
                        total.setText("0.00");
                    }
                }

                public void beforeTextChanged(CharSequence s, int start, int count,
                        int after) {
                    // TODO Auto-generated method stub
                }

                public void afterTextChanged(Editable s) {
                }
            });

        return vi;

    }   
}

日志猫:

07-02 05:05:29.411: D/AndroidRuntime(802): Shutting down VM
07-02 05:05:29.420: W/dalvikvm(802): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
07-02 05:05:29.501: E/AndroidRuntime(802): FATAL EXCEPTION: main
07-02 05:05:29.501: E/AndroidRuntime(802): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sample/com.example.sample.CartActivity}: java.lang.NullPointerException
07-02 05:05:29.501: E/AndroidRuntime(802):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
07-02 05:05:29.501: E/AndroidRuntime(802):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
07-02 05:05:29.501: E/AndroidRuntime(802):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
07-02 05:05:29.501: E/AndroidRuntime(802):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
07-02 05:05:29.501: E/AndroidRuntime(802):  at android.os.Handler.dispatchMessage(Handler.java:99)
07-02 05:05:29.501: E/AndroidRuntime(802):  at android.os.Looper.loop(Looper.java:137)
07-02 05:05:29.501: E/AndroidRuntime(802):  at android.app.ActivityThread.main(ActivityThread.java:5041)
07-02 05:05:29.501: E/AndroidRuntime(802):  at java.lang.reflect.Method.invokeNative(Native Method)
07-02 05:05:29.501: E/AndroidRuntime(802):  at java.lang.reflect.Method.invoke(Method.java:511)
07-02 05:05:29.501: E/AndroidRuntime(802):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-02 05:05:29.501: E/AndroidRuntime(802):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-02 05:05:29.501: E/AndroidRuntime(802):  at dalvik.system.NativeStart.main(Native Method)
07-02 05:05:29.501: E/AndroidRuntime(802): Caused by: java.lang.NullPointerException
07-02 05:05:29.501: E/AndroidRuntime(802):  at java.lang.StringToReal.parseDouble(StringToReal.java:244)
07-02 05:05:29.501: E/AndroidRuntime(802):  at java.lang.Double.parseDouble(Double.java:295)
07-02 05:05:29.501: E/AndroidRuntime(802):  at com.example.sample.CartActivity.onCreate(CartActivity.java:54)
07-02 05:05:29.501: E/AndroidRuntime(802):  at android.app.Activity.performCreate(Activity.java:5104)
07-02 05:05:29.501: E/AndroidRuntime(802):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
07-02 05:05:29.501: E/AndroidRuntime(802):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
07-02 05:05:29.501: E/AndroidRuntime(802):  ... 11 more
07-02 05:05:33.180: I/Process(802): Sending signal. PID: 802 SIG: 9
4

5 回答 5

21

(1) 有一种方法可以将值从适配器传递到设置了适配器的 Activity,

即我们写 listview.setadapter(xyzadapter); 在MainActivity中,我们想将值从xyzaapter传递给MainActivity,那么我只知道一种方法,制作一个接口,在其中定义一个带有参数的方法用于传递值,然后在适配器类上实现它,

(2) 如果我们想将值从适配器传递到另一个没有设置它的活动,那么我们可以使用 putExtra 方法来传递值,

如果您有任何问题,请告诉我...

编辑:(1)答案

在主包中创建一个界面:

public interface DataTransferInterface {
    public void setValues(ArrayList<?> al);
}

在您的适配器类中创建接口对象:

在此行下方 public class CartAdapter extends BaseAdapter { 和在构造函数之前:

DataTransferInterface dtInterface;

在您的构造中传递此接口

在 CartAdapter 中使用此构造函数:

public CartAdapter(Activity a, DataTransferInterface dtInterface) {
    // TODO Auto-generated constructor stub
    activity = a;
    this.dtInterface = dtInterface;
    inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

并使用 dtInterface.setValues(你的值传递给 Activity)

现在在你的 CartActivity.java

实现该接口,如:

public class CartActivity extends Activity implements DataTransferInterface {

和改变

mViewCartAdpt = new CartAdapter(CartActivity.this); 

mViewCartAdpt = new CartAdapter(CartActivity.this, this);

现在您将在 CartActivity 下方看到红线(只需将鼠标光标移到 CartActivity 上),显示添加未实现的方法,单击它将覆盖 setValues 方法

@Override
public void setValues(ArrayList<?> al) {
    // TODO Auto-generated method stub

} 

您可以使用任何类型的数据来传递而不是 ArrayList

如果您有任何问题,请告诉我:

于 2013-07-02T07:03:37.613 回答
2

使用共享首选项将数据从适配器获取到活动

于 2014-01-03T06:11:52.197 回答
0

那行代码的问题是你有很多调用安静,其中一个函数返回 null。你应该像这样拆分它:

SomeType1 detail = Constants.sItem_Detail;
SomeType2 something = detail.get(i);
String strValue = something.get(com.example.sample.CartAdapter.KEY_TOTAL);
mGTotal += Double.parseDouble(strValue);

所以你会更快地发现你的问题。顺便说一句,如果值为空,您还应该检查每一行。

另请注意,longVar = longVar + longValue可以简化为longVar += longValue.

于 2013-07-02T05:19:10.930 回答
0

还有一种方法。

您可以在构造函数中传递viewIDorview object并从适配器设置更新的值。

它将 100% 工作。它对我有用。

于 2015-01-09T12:25:08.400 回答
0

它们是我使用的一种方式,我在我的类中定义了一个静态数组并从适配器类访问该数组。因此,只要它们是适配器中的值更改,我的列表值就会反映在类本身中。

于 2018-01-27T09:31:54.277 回答