2013-07-02 10 views
5

sto cercando di mostrare la lista dei prodotti che insieme a GrandTotal Importo, ma ogni volta che uso questo codice nel mio codice ottenere NullPointerException, vedere di seguito che il codice:Come passare i valori da adattatore di attività

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

In particolare, mentre io uso queste righe ottenendo l'errore:

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

ho provato con il codice qui sotto:

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

e ottenere costanti è maggiore di 0 e mostrare il numero di elementi nel carrello è 1 ma ogni volta che uso questa riga nel mio codice per ottenere problemi, è il modo giusto per ottenere valore dall'adattatore all'attività?

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

In realtà sto calcolando quantità totale di ogni elemento in classe Adapter e ora cercando di mostrare somma di tutti somma totale come totale in attività, ma di fronte a problemi, dimmi dove sto facendo errore?

Ecco codice completo:

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 
+0

quale linea numero-54 in CartActivity –

+0

@sunil ciao come ho scritto sopra: mGTotal = mGTotal + Double.parseDouble (Constants.sItem_Detail.get (i) .get (com.example.sample.CartAdapter.KEY_TOTAL)) ; – Sneha

+0

@Sneha controlla questa domanda http://stackoverflow.com/questions/15286456/android-app-stopped-when-try-to-fetch-data-from-internet – Navi

risposta

0

Il problema con quella riga di codice è che si hanno qui molte chiamate in cui una funzione restituisce null. Dovresti dividerlo in questo modo:

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

Quindi troverai più veloce il tuo problema. Tra l'altro dovresti anche controllare in ogni riga se il valore è nullo.

Si noti inoltre che longVar = longVar + longValue può essere semplificato in longVar += longValue.

14

(1) C'è un modo per passare il valore da adattatore di attività su cui è impostato l'adattatore,

cioè noi scrivere listview.setadapter (xyzadapter); in MainActivity, e vogliamo passare il valore da xyzadapter a MainActivity, quindi solo un modo che conosco, creare un'interfaccia, definire un metodo in quello con parametri per il passaggio del valore e quindi implementarlo sulla classe adattatore,

(2 Se vogliamo passare i valori dall'adattatore ad un'altra attività in cui non è impostato, possiamo usare il metodo putExtra per passare il valore,

Fatemi sapere se avete qualche problema ...

Modificato: per (1) risposta

fare un'unica interfaccia nel pacchetto principale:

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

l'adattatore classe di marca oggetto di interfaccia:

di sotto di questa public class linea CartAdapter estende BaseAdapter { e prima del costruttore:

DataTransferInterface dtInterface; 

nella vostra costruzione di passare questa interfaccia

in CartAdapter utilizzare questo costruttore:

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

e utilizzare dtInterface.setValues ​​(i valori da passare a Attività)

Ora nel tuo CartActivity.java

implementare tale interfaccia come:

public class CartActivity extends Activity implements DataTransferInterface { 

e cambiare

mViewCartAdpt = new CartAdapter(CartActivity.this); 

a

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

ora vedrete linea rossa sotto CartActivity (basta spostare il cursore del mouse su CartActivity) che mostra aggiungere metodi non implementati, cliccare su quel annulleranno setValues metodo

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

} 

è possibile utilizzare Qualsiasi tipo di dati da passare invece di ArrayList

Fatemi sapere se avete qualsiasi ussue:

+0

ho provato diverse volte, ma con il tuo concetto penso che tu abbia ragione, per favore usa il mio codice sopra e mostrami come posso raggiungere il mio obiettivo? – Sneha

+0

@ Sneha: controllare la risposta modificata – Jayesh

+0

Soluzione eccellente. Ha funzionato come un fascino – ChandrasekarG

1

Usa preferance condivisa per ottenere dati da adattatore per l'attività

0

C'è un altro modo.

È possibile passare lo viewID o view object nel costruttore e impostare il valore aggiornato dall'adattatore.

Funzionerà al 100%. Stava funzionando per me.

+0

@matsjoyce perché no? – Alfabravo

+0

@Alfabravo Sembrava un commento prima della modifica. Adesso va bene. – matsjoyce

0

Il loro è un modo che ho usato, Ho definito un array statico nella mia classe e accedere a quell'array dalla classe dell'adattatore. Quindi ogni volta che il loro è un cambio di valore in Adapter i miei valori di lista si riflettono nella classe stessa.

Problemi correlati