简体   繁体   中英

JSON Parsing with Gson in Android

Hi I am trying to Parsing JSON object with using Gson and for this I wrote the code bellow, but when I run my app I am getting an Exception:

java.lang.NullPointerException: Attempt to invoke virtual method 'com.example.venkat.checkingservicesexample2.TerritoryBean com.example.venkat.checkingservicesexample2.Header.getAlerts()' on a null object reference

Json Object response:-

  {
        "Header": {
            "CutQuantity": 0,
            "ETAQuantity": 0,
            "IDRPrice": 229000,
            "MasterId": 65639,
            "Name": "VENICE SATIN DBY 21491 COL 25894",
            "POQuantity": 0,
            "ProductCode": "GG01054-14B",
            "QtyOnHand": 332.1,
            "ReservedQuantity": "332.1",
            "SellingPrice": 229000,
            "TotalAvlQuantity": 0,
            "USDPrice": 26
        },
        "Batches": [{
            "AvailableQty": 25.8,
            "BatchNo": "A001",
            "BinId": 128430,
            "BinName": "Dummy-700",
            "DeptId": 23,
            "DeptName": "G.700",
            "MaxBodyId": 128430,
            "ProductCode": "GG01054-14B",
            "ProductCodeBatch": "GG01054-14B-A001",
            "ProductId": 65639,
            "ProductName": "VENICE SATIN DBY 21491 COL 25894"
        }, {
            "AvailableQty": 40,
            "BatchNo": "A002",
            "BinId": 128433,
            "BinName": "Dummy-700",
            "DeptId": 23,
            "DeptName": "G.700",
            "MaxBodyId": 128433,
            "ProductCode": "GG01054-14B",
            "ProductCodeBatch": "GG01054-14B-A002",
            "ProductId": 65639,
            "ProductName": "VENICE SATIN DBY 21491 COL 25894"
        }]
    }

MainActivity:-

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);
        getAllTips();
  }

    private void getAllTips() {
        try {

            JSONObject json = new JSONObject();
            json.put("scancode", "GG01054-14B");

            if (CommonUtilities.isNetWorkStateAvailble(MainActivity.this)) {

                AsyncTaskClass task = new AsyncTaskClass(this, MainActivity.this,
                        json);
                task.execute(ServiceUrl.GET_STOCKDETAILS_ID_URL, "1",
                        "");
            } else {
                Log.d("==========>", "There is Network Error");
            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void doPostExecute(StatusObject statusObject) {

        // TODO Auto-generated method stub
        if (statusObject != null) {

            if (statusObject.getResponseCode() == 401) {
                Log.d("==========>", "Session Has been Expired");

            } else if (statusObject.getResponseCode() == 200) {
                handleResponseData(statusObject.getMessage());
            } else {
                Log.d("==========>", "Server not responding. Please try again later.");
            }

        } else {
            Log.d("==========>", "Server not responding. Please try again later.");
        }
    }

    // handle the response
    private void handleResponseData(String result) {

        Log.d("Final is==========>", result);

        if (result != null) {
            try {
                JSONObject json = new JSONObject(result);

                if (json.has("Header")) {

                    if (json.getString("Header").equalsIgnoreCase("null")
                            || json.getString("Header") == null) {

                        CommonUtilities
                                .showToastMessage(MainActivity.this,
                                        "Product Information unavailable with this Barcode");

                    } else {
                        System.out.println("your here");
                        handleTripsResponse(result);
                    }
                } else if (json.has("error")) {

                    if (json.has("message")) {

                        CommonUtilities.showToastMessage(MainActivity.this,
                                "" + json.getString("message"));
                    }
                }
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        } else {

            CommonUtilities.showToastMessage(MainActivity.this,
                    "Product Information unavailable with this Barcode");
        }
    }

    // handle the json array data
    private void handleTripsResponse(String result) {


        try {
            Type type = new TypeToken<Response>() {
            }.getType();

            GsonBuilder gsonBuilder = new GsonBuilder();
            Gson gson = gsonBuilder.create();

            Response post = gson.fromJson(result,type);

            System.out.println("Response is"+post);

            friendArrayList.add(post);

            int listSize = friendArrayList.size();
            Log.d("ADebugTag", "Value: " + Float.toString(listSize));

            if (friendArrayList.size() != 0) {
                Log.d("=======>" ," data Available");
                 listView = (ListView) findViewById(R.id.list);
                 adapter = new CustomListViewAdapter(MainActivity.this,
                         R.layout.list_item, friendArrayList);
                 listView.setAdapter(adapter);

            }else{
                Log.d("=======>" ,"No data Available");
            }
        } catch (Throwable throwable) {

            System.out.println("Exception is " + throwable);
        }
    }
}

CustomListViewAdapter:-

public class CustomListViewAdapter extends ArrayAdapter<Response> {

    LayoutInflater inflater;
    Context context;
    ArrayList<Response> coridersList = new ArrayList<Response>();

    public CustomListViewAdapter(Activity context, int resourceId,
                                 ArrayList<Response> items) {

        super(context,resourceId, items);

        this.context = context;
        inflater = context.getLayoutInflater();
        this.coridersList = items;
    }

    @Override
    public View getView(final int position, View view, ViewGroup parent) {

        Response rowItem = getItem(position);

        System.out.println("rowItem is"+rowItem);

        View rowView= inflater.inflate(R.layout.list_item, null, true);

        TextView txtTitle = (TextView) rowView.findViewById(R.id.title);
        txtTitle.setText(rowItem.getHeader().getAlerts().getDeptName());

        TextView desc = (TextView) rowView.findViewById(R.id.desc);
        desc.setText(rowItem.getHeader().getAlerts().getProductCode());

       // ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
       // imageView.setImageResource(rowItem.getImageId());

        return rowView;
    }
}

Response:-

public class Response {

    private Header header;

    public Header getHeader(){
        return header;
    }
    public void setHeader(Header header){
        this.header = header;
    }
}

Header:-

public class Header {

    private TerritoryBean alerts;
    private String Name;
    private String ProductCode;
    private int MasterId;
    private int SellingPrice;
    private int IDRPrice;
    private int USDPrice;
    private int POQuantity;
    private int ReservedQuantity;
    private float ETAQuantity;
    private float CutQuantity;
    private float TotalAvlQuantity;
    private float QtyOnHand;

    public TerritoryBean getAlerts(){
        return alerts;
    }

    public void setAlerts(TerritoryBean alerts){
        this.alerts = alerts;
    }
    public String getName(){
        return Name;
    }

    public void setName(String Name){
        this.Name = Name;
    }

    public String getProductCode(){
        return ProductCode;
    }

    public void setProductCode(String ProductCode){
        this.ProductCode = ProductCode;
    }
}

TerritoryBean:-
--
public class TerritoryBean {

    private int DeptId;
    private String DeptName;
    private int ProductId;
    private String ProductCode;
    private String ProductName;
    private String BatchNo;
    private String ProductCodeBatch;
    private int MaxBodyId;
    private float AvailableQty;
    private String BinId;
    private String BinName;

    public int getDeptId(){
        return DeptId;
    }

    public void setDeptId(int DeptId){
        this.DeptId = DeptId;
    }

    public String getDeptName(){
        return DeptName;
    }

    public void setDeptName(String DeptName){
        this.DeptName = DeptName;
    }

    public int getProductId(){
        return ProductId;
    }

    public void setProductId(int ProductId){
        this.ProductId = ProductId;
    }

    public String getProductCode(){
        return ProductCode;
    }

    public void setProductCode(String ProductCode){
        this.ProductCode = ProductCode;
    }

    public String getProductName(){
        return ProductName;
    }

    public void setProductName(String ProductName){
        this.ProductName = ProductName;
    }
}

You response POJO is wrong and TerritoryBean does not part of Header object.

Batch.java

public class Batch {

    @SerializedName("AvailableQty")
    @Expose
    private Double AvailableQty;
    @SerializedName("BatchNo")
    @Expose
    private String BatchNo;
    @SerializedName("BinId")
    @Expose
    private Integer BinId;
    @SerializedName("BinName")
    @Expose
    private String BinName;
    @SerializedName("DeptId")
    @Expose
    private Integer DeptId;
    @SerializedName("DeptName")
    @Expose
    private String DeptName;
    @SerializedName("MaxBodyId")
    @Expose
    private Integer MaxBodyId;
    @SerializedName("ProductCode")
    @Expose
    private String ProductCode;
    @SerializedName("ProductCodeBatch")
    @Expose
    private String ProductCodeBatch;
    @SerializedName("ProductId")
    @Expose
    private Integer ProductId;
    @SerializedName("ProductName")
    @Expose
    private String ProductName;

    /**
     * 
     * @return
     *     The AvailableQty
     */
    public Double getAvailableQty() {
        return AvailableQty;
    }

    /**
     * 
     * @param AvailableQty
     *     The AvailableQty
     */
    public void setAvailableQty(Double AvailableQty) {
        this.AvailableQty = AvailableQty;
    }

    /**
     * 
     * @return
     *     The BatchNo
     */
    public String getBatchNo() {
        return BatchNo;
    }

    /**
     * 
     * @param BatchNo
     *     The BatchNo
     */
    public void setBatchNo(String BatchNo) {
        this.BatchNo = BatchNo;
    }

    /**
     * 
     * @return
     *     The BinId
     */
    public Integer getBinId() {
        return BinId;
    }

    /**
     * 
     * @param BinId
     *     The BinId
     */
    public void setBinId(Integer BinId) {
        this.BinId = BinId;
    }

    /**
     * 
     * @return
     *     The BinName
     */
    public String getBinName() {
        return BinName;
    }

    /**
     * 
     * @param BinName
     *     The BinName
     */
    public void setBinName(String BinName) {
        this.BinName = BinName;
    }

    /**
     * 
     * @return
     *     The DeptId
     */
    public Integer getDeptId() {
        return DeptId;
    }

    /**
     * 
     * @param DeptId
     *     The DeptId
     */
    public void setDeptId(Integer DeptId) {
        this.DeptId = DeptId;
    }

    /**
     * 
     * @return
     *     The DeptName
     */
    public String getDeptName() {
        return DeptName;
    }

    /**
     * 
     * @param DeptName
     *     The DeptName
     */
    public void setDeptName(String DeptName) {
        this.DeptName = DeptName;
    }

    /**
     * 
     * @return
     *     The MaxBodyId
     */
    public Integer getMaxBodyId() {
        return MaxBodyId;
    }

    /**
     * 
     * @param MaxBodyId
     *     The MaxBodyId
     */
    public void setMaxBodyId(Integer MaxBodyId) {
        this.MaxBodyId = MaxBodyId;
    }

    /**
     * 
     * @return
     *     The ProductCode
     */
    public String getProductCode() {
        return ProductCode;
    }

    /**
     * 
     * @param ProductCode
     *     The ProductCode
     */
    public void setProductCode(String ProductCode) {
        this.ProductCode = ProductCode;
    }

    /**
     * 
     * @return
     *     The ProductCodeBatch
     */
    public String getProductCodeBatch() {
        return ProductCodeBatch;
    }

    /**
     * 
     * @param ProductCodeBatch
     *     The ProductCodeBatch
     */
    public void setProductCodeBatch(String ProductCodeBatch) {
        this.ProductCodeBatch = ProductCodeBatch;
    }

    /**
     * 
     * @return
     *     The ProductId
     */
    public Integer getProductId() {
        return ProductId;
    }

    /**
     * 
     * @param ProductId
     *     The ProductId
     */
    public void setProductId(Integer ProductId) {
        this.ProductId = ProductId;
    }

    /**
     * 
     * @return
     *     The ProductName
     */
    public String getProductName() {
        return ProductName;
    }

    /**
     * 
     * @param ProductName
     *     The ProductName
     */
    public void setProductName(String ProductName) {
        this.ProductName = ProductName;
    }

} 

Header.java

public class Header {

    @SerializedName("CutQuantity")
    @Expose
    private Integer CutQuantity;
    @SerializedName("ETAQuantity")
    @Expose
    private Integer ETAQuantity;
    @SerializedName("IDRPrice")
    @Expose
    private Integer IDRPrice;
    @SerializedName("MasterId")
    @Expose
    private Integer MasterId;
    @SerializedName("Name")
    @Expose
    private String Name;
    @SerializedName("POQuantity")
    @Expose
    private Integer POQuantity;
    @SerializedName("ProductCode")
    @Expose
    private String ProductCode;
    @SerializedName("QtyOnHand")
    @Expose
    private Double QtyOnHand;
    @SerializedName("ReservedQuantity")
    @Expose
    private String ReservedQuantity;
    @SerializedName("SellingPrice")
    @Expose
    private Integer SellingPrice;
    @SerializedName("TotalAvlQuantity")
    @Expose
    private Integer TotalAvlQuantity;
    @SerializedName("USDPrice")
    @Expose
    private Integer USDPrice;

    /**
     * 
     * @return
     *     The CutQuantity
     */
    public Integer getCutQuantity() {
        return CutQuantity;
    }

    /**
     * 
     * @param CutQuantity
     *     The CutQuantity
     */
    public void setCutQuantity(Integer CutQuantity) {
        this.CutQuantity = CutQuantity;
    }

    /**
     * 
     * @return
     *     The ETAQuantity
     */
    public Integer getETAQuantity() {
        return ETAQuantity;
    }

    /**
     * 
     * @param ETAQuantity
     *     The ETAQuantity
     */
    public void setETAQuantity(Integer ETAQuantity) {
        this.ETAQuantity = ETAQuantity;
    }

    /**
     * 
     * @return
     *     The IDRPrice
     */
    public Integer getIDRPrice() {
        return IDRPrice;
    }

    /**
     * 
     * @param IDRPrice
     *     The IDRPrice
     */
    public void setIDRPrice(Integer IDRPrice) {
        this.IDRPrice = IDRPrice;
    }

    /**
     * 
     * @return
     *     The MasterId
     */
    public Integer getMasterId() {
        return MasterId;
    }

    /**
     * 
     * @param MasterId
     *     The MasterId
     */
    public void setMasterId(Integer MasterId) {
        this.MasterId = MasterId;
    }

    /**
     * 
     * @return
     *     The Name
     */
    public String getName() {
        return Name;
    }

    /**
     * 
     * @param Name
     *     The Name
     */
    public void setName(String Name) {
        this.Name = Name;
    }

    /**
     * 
     * @return
     *     The POQuantity
     */
    public Integer getPOQuantity() {
        return POQuantity;
    }

    /**
     * 
     * @param POQuantity
     *     The POQuantity
     */
    public void setPOQuantity(Integer POQuantity) {
        this.POQuantity = POQuantity;
    }

    /**
     * 
     * @return
     *     The ProductCode
     */
    public String getProductCode() {
        return ProductCode;
    }

    /**
     * 
     * @param ProductCode
     *     The ProductCode
     */
    public void setProductCode(String ProductCode) {
        this.ProductCode = ProductCode;
    }

    /**
     * 
     * @return
     *     The QtyOnHand
     */
    public Double getQtyOnHand() {
        return QtyOnHand;
    }

    /**
     * 
     * @param QtyOnHand
     *     The QtyOnHand
     */
    public void setQtyOnHand(Double QtyOnHand) {
        this.QtyOnHand = QtyOnHand;
    }

    /**
     * 
     * @return
     *     The ReservedQuantity
     */
    public String getReservedQuantity() {
        return ReservedQuantity;
    }

    /**
     * 
     * @param ReservedQuantity
     *     The ReservedQuantity
     */
    public void setReservedQuantity(String ReservedQuantity) {
        this.ReservedQuantity = ReservedQuantity;
    }

    /**
     * 
     * @return
     *     The SellingPrice
     */
    public Integer getSellingPrice() {
        return SellingPrice;
    }

    /**
     * 
     * @param SellingPrice
     *     The SellingPrice
     */
    public void setSellingPrice(Integer SellingPrice) {
        this.SellingPrice = SellingPrice;
    }

    /**
     * 
     * @return
     *     The TotalAvlQuantity
     */
    public Integer getTotalAvlQuantity() {
        return TotalAvlQuantity;
    }

    /**
     * 
     * @param TotalAvlQuantity
     *     The TotalAvlQuantity
     */
    public void setTotalAvlQuantity(Integer TotalAvlQuantity) {
        this.TotalAvlQuantity = TotalAvlQuantity;
    }

    /**
     * 
     * @return
     *     The USDPrice
     */
    public Integer getUSDPrice() {
        return USDPrice;
    }

    /**
     * 
     * @param USDPrice
     *     The USDPrice
     */
    public void setUSDPrice(Integer USDPrice) {
        this.USDPrice = USDPrice;
    }

}

Response.java

public class Response {

    @SerializedName("Header")
    @Expose
    private com.example.Header Header;
    @SerializedName("Batches")
    @Expose
    private List<Batch> Batches = new ArrayList<Batch>();

    /**
     * 
     * @return
     *     The Header
     */
    public com.example.Header getHeader() {
        return Header;
    }

    /**
     * 
     * @param Header
     *     The Header
     */
    public void setHeader(com.example.Header Header) {
        this.Header = Header;
    }

    /**
     * 
     * @return
     *     The Batches
     */
    public List<Batch> getBatches() {
        return Batches;
    }

    /**
     * 
     * @param Batches
     *     The Batches
     */
    public void setBatches(List<Batch> Batches) {
        this.Batches = Batches;
    }

}

Now use this Response.java

To generate java POJO corresponding to JSON use http://www.jsonschema2pojo.org/

Adding Custom Adapter

public class CustomListViewAdapter extends ArrayAdapter<Batch> {

    LayoutInflater inflater;
    Context context;
    ArrayList<Batch> batchList = new ArrayList<Batch>();

    public CustomListViewAdapter(Activity context, int resourceId,
                                 ArrayList<Batch> batchList) {

        super(context,resourceId, items);

        this.context = context;
        inflater = context.getLayoutInflater();
        this.batchList = items;
    }

    @Override
    public View getView(final int position, View view, ViewGroup parent) {

        Batch batch = batchList.get(position);

        System.out.println("rowItem is"+rowItem);

        View rowView= inflater.inflate(R.layout.list_item, null, true);

        TextView txtTitle = (TextView) rowView.findViewById(R.id.title);
        txtTitle.setText(batch.getDeptName());

        TextView desc = (TextView) rowView.findViewById(R.id.desc);
        desc.setText(batch.getProductCode());

       // ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
       // imageView.setImageResource(rowItem.getImageId());

        return rowView;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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