-1

Hi I am very new for android and in my app I am parsing Json obejct using Gson and I am displaying result in listView for this I used below code but I am getting exception like

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

please help me some one

json 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(); //Getting friendArrayList data from Services
    }

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

        private void handleTripsResponse(String result) {

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

            GsonBuilder gsonBuilder = new GsonBuilder();
            gsonBuilder.setDateFormat("M/d/yy hh:mm a");
            Gson gson = gsonBuilder.create();
            Response post = gson.fromJson(result,type);
            friendArrayList.add(post);
                int listSize = friendArrayList.size();

                if (friendArrayList.size() != 0) {
                     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);

        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;
    }
}
Community
  • 1
  • 1
Krish
  • 4,166
  • 11
  • 58
  • 110
  • same issue as this http://stackoverflow.com/questions/20991386/expected-begin-array-but-was-begin-object-at-line-1-column-2 – AnOldSoul Apr 20 '16 at 10:26
  • no i tried but that is not working for me – Krish Apr 20 '16 at 10:34
  • 1
    your json file is not in a correct format – Pooya Apr 20 '16 at 10:47
  • hi i chnaged my code now i am getting exception like java.lang.NullPointerException: Attempt to invoke virtual method 'com.example.venkat.checkingservicesexample2.TerritoryBean com.example.venkat.checkingservicesexample2.Header.getAlerts()' on a null object reference – Krish Apr 20 '16 at 10:51
  • That data is not in JSON format. Feed it to http://jsonlint.com/ to see what's wrong with it –  Apr 20 '16 at 10:52
  • u mean server not sending JSON format response? – Krish Apr 20 '16 at 10:55
  • Possible duplicate of [Why does Gson fromJson throw a JsonSyntaxException: Expected some type but was some other type?](https://stackoverflow.com/questions/33621808/why-does-gson-fromjson-throw-a-jsonsyntaxexception-expected-some-type-but-was-s) – Sotirios Delimanolis Apr 16 '18 at 04:08

2 Answers2

0

I think issue is in your json responce your json object responce should like

 "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;
}

and Json array like

 "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";
    }
]
Pitty
  • 1,907
  • 5
  • 16
  • 34
  • i chnaged my code now i am getting exception like java.lang.NullPointerException: Attempt to invoke virtual method 'com.example.venkat.checkingservicesexample2.TerritoryBean com.example.venkat.checkingservicesexample2.Header.getAlerts()' on a null object reference – Krish Apr 20 '16 at 10:52
  • can u please help me pitty? – Krish Apr 20 '16 at 10:52
  • In your customListViewAdapter getView() method you get null value of rowItem.getHeader() – Pitty Apr 20 '16 at 10:59
  • yes your parsing is done now you get the response you just have to get proper data. print what exactly you will get in Response rowItem. – Pitty Apr 20 '16 at 11:06
  • just have a look to this Example as you are a beginner in android https://www.codeofaninja.com/2013/11/android-json-parsing-tutorial.html – Pitty Apr 20 '16 at 11:13
0

Your biggest problem is that your JSON does not look right, please copy and paste it in the JSON validator and make sure that it is correct. Furthermore, please invest sometime to learn JSON - go through a JSON tutorial here.

Also, please check the accepted answer on this question - it looks like something you can really use, especially since you also have/expect array/list of values.

Your JSON should look like this:

{
    "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"
    }]
}
Community
  • 1
  • 1
ishmaelMakitla
  • 3,784
  • 3
  • 26
  • 32
  • hi @ishmaelMakitla ur free? – Krish Apr 20 '16 at 11:00
  • Yep, you need further help with this? – ishmaelMakitla Apr 20 '16 at 11:10
  • yes is ur free i will send my sample project please see where is mistack just 10mins enough because i am very beginner in android please help me – Krish Apr 20 '16 at 11:11
  • OK, let me know how I can help, I can then past the solution as an answer here to the community can also weigh in to suggest improvements, etc. – ishmaelMakitla Apr 20 '16 at 11:18
  • It would be more useful to show us where you are generating the response JSON, because the JSON that you generate is not correct - once this is corrected, then we can help you solve whatever errors you get. Specifically, show me where you call `handleTripsResponse(result)` - because from looking at the code, I assume the `result` is your JSON string (which is not properly formatted for a JSON). – ishmaelMakitla Apr 20 '16 at 13:18
  • hi if u agree i will send my sample app please see once – Krish Apr 20 '16 at 13:20
  • please help me u can easily find problem within minutes i hope – Krish Apr 20 '16 at 13:21
  • i am struggling with this problem since morning – Krish Apr 20 '16 at 13:21
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/109688/discussion-between-ishmaelmakitla-and-krish). – ishmaelMakitla Apr 20 '16 at 13:27