使用Parcelable时出现空指针异常

时间:2011-03-25 16:49:24

标签: java nullpointerexception

我创建了一个java类'store',它只存储我通过2个微调器给出的值和一个edittext ...我使用parcelable将该类的对象传递给中间类Spinpizza.java,然后是Bill.java ....它显示正确的输出,直到SpinPizza ...(显示通过微调器编辑文本输入的值),但它在Bill.java中给出了NULL POINTER EXCEPTION :-(请帮助我...我坚持这个为了结束4天..

这是我的代码......

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

3 个答案:

答案 0 :(得分:5)

好吧,如果这一行抛出异常:

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

然后选项是:

  • b为空(绝对不是;它在上一行中分配了一个非空值)
  • B为空
  • B[i]为空

我的钱在最后一个。以下是初始化数组的方法:

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

有什么可说getParcelable不会返回null吗?

来自documentation for Bundle.getParcelable()

  

返回与给定键关联的值,如果给定键不存在所需类型的映射,或者null值与键明确关联,则返回null。

所以我的猜测是getParcelable返回null。现在你需要找出原因并解决它。我还建议为你的类和变量使用更传统和描述性的名称。

答案 1 :(得分:0)

这篇文章很老,但这里最常见的问题是为你的类实现Parcelable接口,然后触摸字段和方法,这可能需要你重新实现Parcelable接口或者只是添加缺失的。

我建议你为Android Studio或Eclipse安装Parcelable插件并重新创建样板。

答案 2 :(得分:0)

确实是一个很老的问题,但是我是通过一个简单的搜索在2018年到达这里的,并且正在使用Kotlin,所以将来会回答这个问题。

您实际上无法对final \ val字段进行操作,因为Parcelable接口无法在其中写入和重新写入值,请丢弃final \ val字段或不将其合并到包裹方案中