开发者

Null pointer exception while using Parcelable

I have made a java class 'store' which simply stores the values that I give through 2 spinners n one edittext...I pass the object of this class using parcelable to the intermediate class Spinpizza.java followed by Bill.java....It is showing the correct output till SpinPizza..(displays the values entered through spinner n edittext) but it gives NULL POINTER EXCEPTION IN Bill.java :-( Please help me...I m stuck with this for over 4 days..

Here is my code...

Store.java

package com.Lak;

import android.os.Parcel;
import android.os.Parcelable;


public class store implements Parcelable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private String pizzaname;
    private String pizzasize;
    private int n;
    public void setOrder(String name,String size,int qty)
    {
        pizzaname = name;
        pizzasize = size;
        n = qty;
    }
    public String getPizzaName()
    {
        return pizzaname;

    }

    public int getQuantity()

    {return n;}
    public String getPizzaSize() {
        // TODO Auto-generated method stub
        return pizzasize;
    }
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }

     @SuppressWarnings("rawtypes")
    public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
            public store createFromParcel(Parcel in) {
                return new store(in);
            }

            public store[] newArray(int size) {
                return new store[size];
            }
        };

    public void writeToParcel(Parcel dest, int flags) {

          dest.writeInt(n);
          dest.writeString(pizzaname);
          dest.writeString(pizzasize);
    }


    public store()

    {}
      public store(Parcel source){
          /*
           * Reconstruct from the Parcel
           */

          n = source.readInt();
          pizzaname = source.readString();
          pizzasize = source.readString();

    }


    /** Called when the activity is first created. */
}

(SpinPizza.java)

package com.Lak;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class SpinPizza extends Activity{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    store B[]= new store[10];


    Spinner s=null,s1=null;
    EditText edittext=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.drop);


        s = (Spinner) findViewById(R.id.spinner);

        ArrayAdapter<?> adapter = ArrayAdapter.createFromResource(
                this, R.array.pizzaarray, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        s.setAdapter(adapter);


       s1 = (Spinner) findViewById(R.id.spinner1);
        ArrayAdapter<?> adapter1 = ArrayAdapter.createFromResource(
                this, R.array.sizearray, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        s1.setAdapter(adapter1);

        edittext = (EditText) findViewById(R.id.edittext);
        edittext.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // If the event is a key-down event on the "enter" button
               if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
                    (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER)) {
                  // Perform action on key press
                   int i=0;

                   B[i]=new store();
                      int n=Integer.parseInt(edittext.getText().toString());
            B[i].setOrder(s.getSelectedItem().toString(), s1.getSelectedItem().toString(),n );

                    TextView objText=(TextView) findViewById(R.id.pl);
                    TextView objText1=(TextView) findViewById(R.id.pl2);
                    objText.setText(B[i].getPizzaName());
                   objText1.setText(B[i].getPizzaSize());
                     i++;

                  Toast.makeText(SpinPizza.this, edittext.getText(), Toast.LENGTH_SHORT).show();
                  return true;
                }
                return false;
            }
        });


          Button next1 = (Button) findViewById(R.id.bill);

          next1.setOnClickListener(new View.OnClickListener() {
              public void onClick(View view) {

                  Intent myIntent = new Intent(view.getContext(), Bill.class);

                  for(int i =0;i<B.length;i++)
                  {
                      myIntent.putExtra("myclass"+i,B[i]);
                  }
                  myIntent.putExtra("length",B.length);
                  startActivityForResult(myIntent, 0); 

              }

          });

    }
}

(Bill.java)

package com.Lak;
import android.app.Activity;
import android.os.Bundle;
impor开发者_JAVA百科t android.view.ViewGroup.LayoutParams;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class Bill extends Activity {
     @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

    this.setContentView(R.layout.calc);
    store B[] = new store[10];
    Bundle bj=getIntent().getExtras();
    int length = bj.getInt("length");
    for(int i = 0 ;i<length;i++)
    {
        B[i] = (store)bj.getParcelable("myClass"+i);
    }
//  B =  (store[]) bj.get("myClass"); 

    /* Find Tablelayout defined in main.xml */
    TableLayout tl = (TableLayout)findViewById(R.id.myTable);
         /* Create a new row to be added. */
         TableRow tr = new TableRow(this);
         tr.setLayoutParams(new LayoutParams(
                        LayoutParams.FILL_PARENT,
                        LayoutParams.WRAP_CONTENT));

              /* Create TEXTVIEWS to be the row-content. */
            for(int i=0;i<length;i++)
            { TextView b = new TextView(this);
            b.setText(B[i].getPizzaName());  // NULL POINTER EXCEPTION :(

            TextView b1 = new TextView(this);
            b1.setText(B[i].getPizzaSize());

            TextView b2 = new TextView(this);
            b2.setText(B[i].getQuantity());

            b.setLayoutParams(new LayoutParams(
                        LayoutParams.FILL_PARENT,
                        LayoutParams.WRAP_CONTENT));

            b1.setLayoutParams(new LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT));

            b2.setLayoutParams(new LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT));

            /* Add TextViews to row. */
              tr.addView(b);

              tr.addView(b1);

              tr.addView(b2);


    /* Add row to TableLayout. */
    tl.addView(tr,new TableLayout.LayoutParams(
              LayoutParams.FILL_PARENT,
              LayoutParams.WRAP_CONTENT));
     }}
}


Well, if this line is throwing the exception:

b.setText(B[i].getPizzaName());

Then the options are:

  • b is null (definitely not; it's assigned a non-null value in the previous line)
  • B is null
  • B[i] is null

My money's on the last one. Here's how you initialize the array:

for(int i = 0 ;i<length;i++)
{
    B[i] = (store)bj.getParcelable("myClass"+i);
}

Is there anything to say that getParcelable won't return null?

From the documentation for Bundle.getParcelable():

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

So my guess is that getParcelable is returning null. Now you need to find out why, and fix it. I'd also suggest using more conventional and descriptive names for your classes and variables.


Very old question indeed, but I got here in 2018 via a simple search and am using Kotlin so am gonna answer this for the future.

you can't actually do pacel on a final\val fields as the Parcelable interface can't write and re-write the values in it, either drop the final\val fields or don't incorporate them with your parceling scenarios.


This post is old, but the most common problem here is implementing the Parcelable interface for your class and then touching the fields and the methods, which may require you to re-implement the Parcelable interface or just add the missing.

I recommend you to install the Parcelable plugin for Android Studio or Eclipse and recreate the boiler plate.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜