简体   繁体   English

使用Parcelable时出现空指针异常

[英]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.. 我做了一个Java类'store',它只存储我通过2个微调器提供的值和一个edittext ...我使用parcelable将此类的对象传递给中间类Spinpizza.java和Bill.java ... 。它将显示正确的输出,直到SpinPizza ..(显示通过spinner n edittext输入的值),但它在Bill.java中给出了NULL POINTER EXCEPTION::-(请帮助我...我坚持了4天以上。 。

Here is my code... 这是我的代码...

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

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为null(绝对不是;在前一行中为其分配了非null值)
  • B is null B为空
  • B[i] is null B[i]为空

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? 有什么说法说getParcelable不会返回null吗?

From the documentation for Bundle.getParcelable() : 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. 返回与给定键关联的值;如果不存在给定键的所需类型的映射,或者为该键显式关联一个空值,则返回null。

So my guess is that getParcelable is returning null. 所以我的猜测是getParcelable返回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. 我还建议为类和变量使用更常规和更具描述性的名称。

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. 这篇文章很老,但是这里最常见的问题是为您的类实现Parcelable接口,然后触摸字段和方法,这可能需要您重新实现Parcelable接口或仅添加缺失的接口。

I recommend you to install the Parcelable plugin for Android Studio or Eclipse and recreate the boiler plate. 我建议您为Android Studio或Eclipse安装Parcelable插件,然后重新创建样板。

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. 确实,这是一个非常古老的问题,但我是通过简单的搜索于2018年到达这里的,并且正在使用Kotlin,因此将来会对此进行回答。

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. 您实际上无法对final \\ val字段进行修改,因为Parcelable接口无法在其中写入和重新写入其中的值,要么丢弃final \\ val字段,要么不将它们与您的包裹方案合并。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM