david
david

Reputation: 3228

Android URL and HTTP Post Error

I have a problem when I am trying to pass data to server using HTTP POST. I want to insert these data into database. But, when I tested it, the error shows like this "Unfortunately, ... has stopped."

TestActivity.java

public class TestActivity extends AppCompatActivity {
    ArrayList<Cart> cartList;
    String URL_SEND;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        cartList = new ArrayList<>();
        URL_SEND = "http://192.168.56.1/api.php";
        new SendOrder().execute();
    }

    class SendOrder extends AsyncTask<Void,Void,Void> {
        @Override
        protected Void doInBackground(Void... params) {
            Cart cart1 = new Cart("1", 3);
            cartList.add(cart1);
            Cart cart2 = new Cart("2", 2);
            cartList.add(cart2);
            try {
                URL url = new URL(URL_SEND);
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setRequestProperty("Content-Type", "application/json");
                httpURLConnection.connect();

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("idUser", "1");
                jsonObject.put("total", 50000);
                jsonObject.put("cartArray", new JSONArray(cartList));
                jsonObject.put("key", "12345");

                OutputStreamWriter writer = new OutputStreamWriter(httpURLConnection.getOutputStream());
                writer.write(jsonObject.toString());
                writer.flush();
                Toast.makeText(TestActivity.this, "Order success", Toast.LENGTH_LONG).show();
                cartList.clear();
            } catch (Exception e) {
                Toast.makeText(TestActivity.this, "Server error", Toast.LENGTH_LONG).show();
            }

            return null;
        }
    }
}

Cart.java

public class Cart {
    private String idMenu;
    private int quantity = 0;

    public Cart() {

    }

    public Cart(String idMenu, int quantity){
        this.idMenu = idMenu;
        this.quantity = quantity;
    }

    public String getIdMenu(){
        return idMenu;
    }

    public void setIdMenu(String idMenu) {
        this.idMenu = idMenu;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }
}

api.php

<?php
if ($_SERVER['REQUEST_METHOD']=='POST'){
    include_once('../admin/connect_database.php');
    $user_id = $_POST['idUser'];
    $cartArray = $_POST['cartArray'];
    $key = $_POST['key'];
    $total= $_POST['total'];
    $status = "PENDING";

    if ($key == $keyapi) {
        $sth = $dbh->prepare("INSERT INTO order(user_id, total, status_order, time)
            VALUES(:idUser, :total, :status, :waktu)");
        $res = $sth->execute(array(
            'idUser' => $user_id,
            'total' => $total,
            'status' => $status,
            'waktu' => date()
        ));
        $id = $dbh->lastInsertId();
        foreach ($cartArray as $cart) {
            $idProduct = $cart->idMenu;
            $qty = $cart->quantity;
            $sth = $dbh->prepare('INSERT INTO order_detail(id_order, id_product, qty) VALUES (:idOrder, :idProduct, :qty)');
            $res = $sth->execute(array(
                'idOrder' => $id,
                'idProduct' => $idProduct,
                'qty' => $qty
            ));
        }
    }
}

?>

It seems like the URL itself has a problem. When I run this with only URL url = new URL(URL_SEND);, the same error occurred. I have no idea why this code doesn't work.

EDIT

This is the error I get.

FATAL EXCEPTION: AsyncTask #1
Process: com.catering.catering, PID: 5219
java.lang.RuntimeException: An error occurred while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:309)
    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
    at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
    at android.os.Handler.<init>(Handler.java:200)
    at android.os.Handler.<init>(Handler.java:114)
    at android.widget.Toast$TN.<init>(Toast.java:345)
    at android.widget.Toast.<init>(Toast.java:101)
    at android.widget.Toast.makeText(Toast.java:259)
    at com.catering.catering.TestActivity$SendOrder.doInBackground(TestActivity.java:90)
    at com.catering.catering.TestActivity$SendOrder.doInBackground(TestActivity.java:57)
    at android.os.AsyncTask$2.call(AsyncTask.java:295)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
    at java.lang.Thread.run(Thread.java:818) 

Upvotes: 0

Views: 508

Answers (2)

Glenn
Glenn

Reputation: 12819

You shouldn't do UI stuff in background thread. Remove displaying of Toast in doInBackground(). If you want to determine whether the POST succeeded or not I suggest to return a Boolean object base on your implementation.

public class SendOrder extends AsyncTask<Void,Void,Boolean> {

            @Override
            public void onPostExecute(Boolean result) {

                if(result != null && result) {

                   Toast.makeText(TestActivity.this, "Order success", Toast.LENGTH_LONG).show();
                }
                else {
                   Toast.makeText(TestActivity.this, "Order error", Toast.LENGTH_LONG).show();
                }
            }


            @Override
            protected Boolean doInBackground(Void... params) {
                Cart cart1 = new Cart("1", 3);
                cartList.add(cart1);
                Cart cart2 = new Cart("2", 2);
                cartList.add(cart2);
                try {
                    URL url = new URL(URL_SEND);
                    HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                    httpURLConnection.setDoOutput(true);
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setRequestProperty("Content-Type", "application/json");
                    httpURLConnection.connect();

                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("idUser", "1");
                    jsonObject.put("total", 50000);
                    jsonObject.put("cartArray", new JSONArray(cartList));
                    jsonObject.put("key", "12345");

                    OutputStreamWriter writer = new OutputStreamWriter(httpURLConnection.getOutputStream());
                    writer.write(jsonObject.toString());
                    writer.flush();

                    cartList.clear();

                    return true;
                } catch (Exception e) {
                    // Your code to Log the error 

                    return false;
                }


            }
        }
}

Upvotes: 1

Divyesh Patel
Divyesh Patel

Reputation: 2576

Remove these line from doInBackground():

Toast.makeText(TestActivity.this, "Order success", Toast.LENGTH_LONG).show();

and

Toast.makeText(TestActivity.this, "Server error", Toast.LENGTH_LONG).show();

You can not do UI work in doInBackground(): You have to toast that data in onPostExecute():

see this link: https://stackoverflow.com/a/18948837/6756514

Upvotes: 1

Related Questions