7

I am trying to show list of Items along with GrandTotal Amount, but whenever i use this code in my code getting NullPointerException, see below that code:

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

Particularly, while i use these lines getting Error:

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

i have tried with below code:

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

and getting Constants is Greater Than 0, and showing number of items in Cart is 1 but whenever i use this line in my code getting problem, is it the right way to get value from adapter to activity ?

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

Actually i am calculating total amount of each and every item in Adapter class and now trying to show sum of all total amount as grand total in Activity, but facing problem, tell me where i am doing mistake?

Here is complete code:

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;

    }   
}

Logcat:

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
Lars
  • 1,006
  • 1
  • 9
  • 29
Sneha
  • 1,051
  • 4
  • 14
  • 23
  • which line number-54 in CartActivity – Sunil Kumar Jul 02 '13 at 05:16
  • @sunil hello like i have written above: mGTotal = mGTotal + Double.parseDouble(Constants.sItem_Detail.get(i).get(com.example.sample.CartAdapter.KEY_TOTAL)); – Sneha Jul 02 '13 at 05:17
  • @Sneha check this question http://stackoverflow.com/questions/15286456/android-app-stopped-when-try-to-fetch-data-from-internet – Navi Jul 02 '13 at 05:19
  • do not get with static keyword – Sunil Kumar Jul 02 '13 at 05:19
  • @Sneha http://stackoverflow.com/questions/6119048/android-development-thread-exiting-with-uncaught-exception – Navi Jul 02 '13 at 05:20
  • did u checked whether Constants.sItem_Detail.get(i) has any value? – R9J Jul 02 '13 at 05:39
  • Does this answer your question? [Kotiln: pass data from adapter to activity](https://stackoverflow.com/questions/56826346/kotiln-pass-data-from-adapter-to-activity) – milad salimi Jan 21 '20 at 06:30

5 Answers5

21

(1) There is one way to pass value from Adapter to Activity on which adapter is set,

i.e we write listview.setadapter(xyzadapter); in MainActivity, and we want to pass value from xyzadapter to MainActivity, then only one way I know, make one interface, define one method in that with parameters for passing value, and then implement it on adapter class,

(2) If we want to pass values from adapter to another activity in which it is not set, then we can use putExtra method to pass value,

Let me know if you have any issue...

Edited: for (1) answer

make one interface in your main package:

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

in your adapter class make object of Interface:

below this line public class CartAdapter extends BaseAdapter { and before constructor:

DataTransferInterface dtInterface;

in your construction pass this interface

in CartAdapter use this constructor:

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

and use dtInterface.setValues(your Values to pass to Activity)

Now in your CartActivity.java

implement that interface like:

public class CartActivity extends Activity implements DataTransferInterface {

and change

mViewCartAdpt = new CartAdapter(CartActivity.this); 

to

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

now you will see red line below CartActivity (just move your mouse cursor on CartActivity) that shows add unimplemented methods, click on that will override setValues method

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

} 

you can use Any type of data to pass instead of ArrayList

Let me know if you have any ussue:

Jayesh
  • 3,661
  • 10
  • 46
  • 76
  • i have tried several times,but with your concept i think you are right, please use my above code and show me the way how can i achieve my target? – Sneha Jul 02 '13 at 07:12
  • Excellent solution. Worked like a charm – ChandrasekarG Apr 21 '16 at 19:40
  • use of the interfaces is communication and this is how it is done. excellent explanation @Jayesh – Tiger98 Nov 10 '16 at 10:00
  • 2
    i follow your code, and i have to pass the list from Adapter to the setAdapter activity and i setValues but how can i retrieve in Activity.. please hep – techDigi Feb 06 '17 at 07:38
  • Nice explanation, you said in the end "you can use Any type of data to pass instead of ArrayList", but the parameter is in interface definition is an ArrayList? – shehzy Mar 22 '17 at 07:29
  • How do you retrieve the values ? – yardie Jul 01 '18 at 20:27
2

Use shared preferance to get data from adapter to activity

venkateswaran
  • 233
  • 2
  • 11
0

The problem with that line of code is that you have there quiet many calls where one function returns null. You should split it up like this:

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

So you will find faster your problem. By the way you should also check in each line if the value is null.

Please note also that longVar = longVar + longValue can be simplified to longVar += longValue.

rekire
  • 47,260
  • 30
  • 167
  • 264
0

There is one more way.

You can pass the viewID or view object in your constructor and set the updated value from the adapter.

It will work 100%. It was working for me.

parakmiakos
  • 2,994
  • 9
  • 29
  • 43
Vivek Samele
  • 340
  • 4
  • 8
0

Their is one way that I used, I have defined a static array in my Class and access that array from the adapter class. Hence whenever their is a value change in Adapter my list values are reflected in the Class itself.

Deepak Yadav
  • 632
  • 7
  • 14