4

I am creating an Android application, and I am trying to retrieve data from a Restful Web-service through JSON.

I have performed a call with get and post JSON data from a Restful Web service(from a URL) By this Tutorial

So here I need to add price * quantity like the example below:

enter image description here

But I don't know how to Post this calculation for JSON data I googled and tried few Other options.... Can any one suggest me like this kind for Post JSON data..

I followed this to POST JSON Data

But this Should be Done OnClick, it should ask add enter quantity. Offline(db) its possible But for Custom Listview(Async listview-Online) I am Unable to Build

Please let me Know to Use for this kind... I google many options But I am Help less....

Michele La Ferla
  • 6,775
  • 11
  • 53
  • 79
Don't Be negative
  • 1,215
  • 3
  • 19
  • 46

6 Answers6

2

You can use this json-structure data to post to the server:

{
"date": "2015-07-03",
"item": [
    {
        "itemname": "xyz",
        "quantity": 6,
        "price": 80
    },
    {
        "itemname": "abc",
        "quantity": 6,
        "price": 80
    }
],
"total": "960",
"currency": "Rs."
}
Michele La Ferla
  • 6,775
  • 11
  • 53
  • 79
Angad Tiwari
  • 1,738
  • 1
  • 12
  • 23
2

Everything where money is involved you should use BigDecimal how you will post data to server really doesn't meather as long data are secured.

I would use volley lib. It take care of a lot of stuff instead of you and you should really dig into, it will save you a lot of time: http://www.androidhive.info/2014/05/android-working-with-volley-library-1/

Also, I would use GSON for json objects. Its also simple for example create class:

 public class Money{
    String name;
    int quantay;
    BigDecimal rate;
    BigDecimal total;

    /* make seters and getters */
}

and the just create json like this:

money = new Money("name", 100, 0.54, 54);
Gson gson = new Gson();
String json = gson.toJson(money);

thats it. Well you need constructor in Money class.

5er
  • 2,506
  • 7
  • 32
  • 49
2

As I understood your question I'm trying to provide answer as follow. I hope that you understand Model class concept, which makes life easier.

Step - 1 : First create one model class and make it Serializable to pass model object, because I can see that you have two activities one for products list and second for billing. In this you may add/remove some fields as per your requirements.

public class Product implements Serializable {
    public String productName;
    public int price;
    public int quantity;
    public int total;
}

Step - 2 : Now I'm assuming that you know how to assign data to ArrayList userProducts by using gson library, link1 and link2.

Step - 3 : Next step would be to calculate total = price * quantity in listview setOnItemClickListener like this,

Product product = userProducts.get(postiton);
product.total = product.price * product.quantity;

Step - 4 : Send arraylist with Serializable object from one activity to another,

    Intent intent = new Intent(ProductActivity.this, BillingActivity.class);
    intent.putExtra("user_products", userProducts);
    startActivity(intent);

Step - 5 : Get values in billing activity,

    if (getIntent() != null) {
        userProducts = (ArrayList<Product>) getIntent()
                .getSerializableExtra("user_products");
    }

Step - 6 : Now your question is how to post them ? The thing is that you've to create jsonarray for list of products and jsonobject for some other fields, and then you can send main jsonobject as a string, a very good tutorial.

    try {
        JSONObject mainJObject = new JSONObject();
        JSONArray productJArray = new JSONArray();
        for (int i = 0; i < userProducts.size(); i++) {
            JSONObject productJObject = new JSONObject();
            productJObject.put("productname", userProducts.get(i).productName);
            productJObject.put("price", userProducts.get(i).price);
            productJObject.put("quantity", userProducts.get(i).quantity);
            productJObject.put("total", userProducts.get(i).total);
            productJArray.put(productJObject);
        }
        mainJObject.put("products", productJArray);
        mainJObject.put("grandd_total", grandTotal);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

It should look like this,

        {
          "products": [
            {
              "productname": "p1",
              "price": "15",
              "quantity": "6",
              "total": 90
            },
            {
              "productname": "p2",
              "price": "25",
              "quantity": "4",
              "total": 100
            }
          ],
          "grandd_total": 190
        }
Community
  • 1
  • 1
Chitrang
  • 5,097
  • 1
  • 35
  • 58
1

how this answer help you. you can read json right?

so by json object try this :-

    Double Rate = Double.parseDouble(jsonobject.getString("Rate"));//put api parameter
    int Qty= Integer.parseInt(jsonobject.getString("Qty"));
    Double total = Rate * Qty;
   //set total on your textview lable
    textview.settext(""+total);

and save in your local database and when you need to post then post your database to server.

tej shah
  • 2,995
  • 2
  • 25
  • 35
1

I would rather calculate the data before posting it to the php database. You can use something like the following:

double a = 1.50;
double b = 2.00;
double c = a * b;

Using the HTTPPost medthod (which by the way is depreciated) you need to then do something similar to the below:

public void postData(){  
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www.yourdomain.com/post.php");  

        try {
            List nameValuePairs = new ArrayList(1);
            nameValuePairs.add(new BasicNameValuePair("data1", c));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));  

            HttpResponse response = httpclient.execute(httppost);

            InputStream is = response.getEntity().getContent();
            BufferedInputStream bis = new BufferedInputStream(is);
            ByteArrayBuffer baf = new ByteArrayBuffer(20);

            int current = 0;

            while((current = bis.read()) != -1){
                baf.append((byte)current);
            }  

            text = new String(baf.toByteArray());
            txtvw.setText(text);
        } catch (ClientProtocolException e) {
        } catch (IOException e) {
    }

Hope this helps :)

Michele La Ferla
  • 6,775
  • 11
  • 53
  • 79
  • Thanks @codeByMi,.. Sir I am doing This for Online JSON data so it Possible,,,, If so Can you Update me.... Here I am Dealing with Price* Quantity.. Here Price is Dynamic and Quantity is User Input I need to Calculate both and POST them... – Don't Be negative Jul 09 '15 at 04:21
  • ok understood. You can take 2 approaches to this. It all depends on whether you want to show the Price to the user or not. If yes, then I would recommend you to first call the php code to display the Price in the app. A good exmple is this: `http://stackoverflow.com/questions/11579693/how-to-get-json-data-from-php-server-to-android-mobile` Otherwise, if you don't wish to show the price in the app, you can perform the calculations on the php server. A good example for this is: `https://youtu.be/DqKkncDr-_k` – Michele La Ferla Jul 09 '15 at 08:08
  • If you use the first approach, then you don't need to change the code above. Otherwise, you only need the value parameter to be sent to the PHP server. – Michele La Ferla Jul 09 '15 at 08:27
1

Hope this helps you , as per above ans i have checked, you need Grand_Total to post on Bill Webservice. you just calculate and pass that data to Bill Screen like above given ans

if (getIntent() != null) {
        userProducts = (ArrayList<Product>) getIntent()
                .getSerializableExtra("user_products");
    }

Here is one Grand Total is missing to pass as per looks in Billing screen

(Here we trying to get Grand total Rs.905)

double Grand_total = 0.0;

for(int i=0;i<userProducts.size();i++)
{
Product product = userProducts.get(postiton);
product.total = product.price * product.quantity;
Grand_total +=product.total;
}

Now you can pass all required data to Billing webservice like

try {
        JSONObject mainJObject = new JSONObject();
        JSONArray productJArray = new JSONArray();
        for (int i = 0; i < userProducts.size(); i++) {
            JSONObject productJObject = new JSONObject();
            productJObject.put("productname", userProducts.get(i).productName);
            productJObject.put("price", userProducts.get(i).price);
            productJObject.put("quantity", userProducts.get(i).quantity);
            productJObject.put("total", userProducts.get(i).total);
            productJObject.put("total", userProducts.get(i).total);

            productJArray.put(productJObject);
        }
        mainJObject.put("products", productJArray);
        mainJObject.put("Grand_total", Grand_total);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
Ankitkumar Makwana
  • 3,475
  • 3
  • 19
  • 45