java - 带有空字段的 Parcelable 对象

标签 java android parcelable

我正在使用可打包对象来传递 Intent 。传递方使用此代码:

    Parcelable product = new Product(res.getData(), alcohol.toLowerCase(Locale.ENGLISH).trim(), selectedSize, location);

    Intent intent = new Intent(Search.this, ProductPage.class);
    intent.putExtra("Product", product);
    startActivity(intent);

我正在使用以下方法取回对象:

    Intent parentIntent = getIntent();
    Product newProduct = (Product)parentIntent.getParcelableExtra("Product");

我遇到的问题是 newProduct 的数据成员都是空的。通过检查调试器,我知道该产品在其字段中有真实数据。这是我的产品类别:

public class Product implements Parcelable {
    private int mData;
    private Location location;
    /** Product name of this alcohol. */
    private String productName;
    /** Size of this alcohol. */
    private String size;
    /** The list of ProductInfo's for the given product. */
    private ArrayList<ProductInfo> productInfos;
    // Test string
    String jsonStr = "{\"result\":{\"status\":200,\"message\":\"OK\"},\"data\":[{\"storeID\":2,\"store_name\":\"safeway\",\"store_gps\":\"still dont know\",\"price\":3.99},{\"storeID\":1,\"store_name\":\"Hammy\",\"store_gps\":\"don't know\",\"price\":4.99}]}";

    /**
     * Takes a JSON string and parses its data field turning it into an array
     * of ProducInfo's. Note any exception thrown here is caught and not 
     * thrown again. It's assumed that the JSON string is correctly formated.
     * 
     * @param jsonStr
     *          The JSON string being parsed for it's data field.
     */
    public Product(JSONArray productInfo, String productName, String size, Location location) {
        this.location = location;
        productInfos = new ArrayList<ProductInfo>();
        this.productName = productName;
        this.size = size;

        try {
            parseData(productInfo);
        } catch (JSONException e) {
            // Response now handles the parse error
            // TODO: if data is in incorrect format it can throw an error...
        }
    }

    /**
     * Parses the data field of a JSONObject. If this field is not found or any
     * of the fields assumed to be contained in this field, {storeID, store_name,
     * price, store_gps} a JSONException is thrown.
     * 
     * @param dataObj
     *          The JSONObject containing a data field.
     * @throws JSONException
     *          If it can't find the data field, or any of data's fields.
     */
    private void parseData(JSONArray dataObj) throws JSONException {
        for (int i = 0; i < dataObj.length(); i++) {
            JSONObject dataField = dataObj.getJSONObject(i);
            int storeID = Integer.parseInt(dataField.getString("storeID"));
            String storeName = dataField.getString("store_name");
            double price = Double.parseDouble(dataField.getString("price"));
            double dist = calculateGPSDistance(dataField.getString("store_gps"));

            productInfos.add(new ProductInfo(storeID, storeName, price, dist));
        }
    }

    /**
     * Calculates the distance between GPSCoord and the users current GPS
     * coordinates.
     * 
     * @param GPSCoord
     *          GPS coordinates. Assumes that GPSCoord follows the following
     * format "latitude, longitude"
     * @return the distance between GPSCoord and the users current GPS coordinates.
     */
    private double calculateGPSDistance(String GPSCoord) {
        double lat1 = location.getLatitude();
        double long1 = location.getLongitude();
        String[] coordinates = GPSCoord.split(",");
        double lat2 = Double.parseDouble(coordinates[0]);
        double long2 = Double.parseDouble(coordinates[1]);

        // Check http://www.smokycogs.com/blog/finding-the-distance-between-two-gps-coordinates/
        // for details.
        lat1 = degToRad(lat1);
        long1 = degToRad(long1);
        lat2 = degToRad(lat2);
        long2 = degToRad(long2);

        double earthRadius = 6371; // km
        double deltaLat = lat2 - lat1;
        double deltaLong = long2 - long1;
        double a = Math.sin(deltaLat / 2.0) * Math.sin(deltaLat / 2.0) + 
                Math.cos(lat1) * Math.cos(lat2) *
                Math.sin(deltaLong / 2.0) * Math.sin(deltaLong / 2.0);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double distance = earthRadius * c;
        return distance;
    }

    private double radToDeg(double radians) {
        return radians * (180 / Math.PI);
    }

    private double degToRad(double degrees) {
        return degrees * (Math.PI / 180);
    }

    /*
     * GETTER METHODS
     */

    public String getProductName() {
        return productName;
    }

    public String getSize() {
        return size;
    }

    /*
     * Check http://developer.android.com/reference/android/os/Parcelable.html
     * for details. These are all methods for Parcelable.
     */

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel out, int flags) {
        out.writeInt(mData);
    }

    public static final Parcelable.Creator<Product> CREATOR = new Parcelable.Creator<Product>() {
        public Product createFromParcel(Parcel in) {
            return new Product(in);
        }

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

    };

    private Product(Parcel in) {
        mData = in.readInt();
    }

    /**
     *  productInfos getter 
     */
    public ArrayList<ProductInfo> getProductInfos() {
        return productInfos;
    }
}

Parcelables 已经让我感到困惑,所以我不太确定这里发生了什么......谢谢

另请注意,因此我的代码中出现空指针异常。

最佳答案

 Product product = new Product(res.getData(), alcohol.toLowerCase(Locale.ENGLISH).trim(), selectedSize, location);

    Intent intent = new Intent(Search.this, ProductPage.class);
    intent.putExtra("Product", product);
    startActivity(intent);


    Bundle bundle = getIntent().getExtras();

Product newProduct = bundle.getParcelable("Product");

关于java - 带有空字段的 Parcelable 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13988151/

相关文章:

java - 如何为双ArrayList实现Parcelable?

android - Parcelables 不支持默认值。 Android 导航深层链接参数

Android WebView 键盘在 android 的 fragment 中隐藏了输入字段

android - 添加联系人时如何显示 toast ?

java - 如何将整个 Parseobject 从 fragment 传递到 Activity ?

android - ParcelCreator lint 抑制不起作用

java - 在 Eclipse 3.7.1 中使用 Java 7 闭包语法

java - freemarker 宏参数内的 if-else 语句?

java - JDBC 执行大型 T-SQL 查询

java - 如何将 Telugu 字符转换为 Java 中的 UTF-8 编码字符?