dongqiang1226 2015-10-28 14:26
浏览 98

HttpUrlConnect不向PhP发送数据

I am a starter in Android Programming and trying to learn by developing an app. What i wish to do is send data to a webserver which will further process it accordingly. Now I earlier Used HttpClient function but seems to be deprecated. Some research took me to this HttpUrlConnect Class, it did not throw any error but didnt really work too! The data is not being received by PhP. Please help! Code is Below:

  @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
   SendData sendData = new SendData();
    Toast t4 = Toast.makeText(getApplicationContext(), "Started", Toast.LENGTH_LONG);
    t4.show();
    sendData.execute("21.43","23.23");
}
class SendData extends AsyncTask<String, Void, String>{
    @Override
    protected String doInBackground(String... params) {
        // a-> Lat | b-> Lon
    try {
        String a_str = params[0];
        String b_str = params[1];
        String result = null;
        URL url = null;
        String text = "";
        BufferedReader reader = null;
        try {
            String data = URLEncoder.encode("lon", "UTF-8") + "=" + URLEncoder.encode(a_str, "UTF-8");
            data += "&" + URLEncoder.encode("lat", "UTF-8") + "=" + URLEncoder.encode(b_str, "UTF-8");
            url = new URL("http://chalkbox.in/recieve.php");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Host", "chalkbox.in");
            try {
                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                wr.write(data);
                wr.flush();
                Toast t0 = Toast.makeText(getApplicationContext(), "Pushed", Toast.LENGTH_LONG);
                t0.show();
            } catch (Exception e) {
                Toast t1 = Toast.makeText(getApplicationContext(), String.valueOf(e), Toast.LENGTH_LONG);
                t1.show();
            }
            conn.connect();
        } catch (Exception e) {
                Toast t5 = Toast.makeText(getApplicationContext(), String.valueOf(e), Toast.LENGTH_LONG);
            t5.show();
        }
    }
    catch (Exception e){
        Toast t11 = Toast.makeText(getApplicationContext(), String.valueOf(e), Toast.LENGTH_LONG);
        t11.show();
    }
        return null;
    }
}
}

Now, it just toasts "Started" and and nothing then. I have checked the internet connection, permissions for internet access and everything. It Doesnt push data and doesnt toast any error either. eventually it stops working.

The PhP code is:

<?php
$long = $_POST['lon'];
$lati = $_POST['lat'];

$con = mysqli_connect($host",$user,$pass,$dB);
$sql = "INSERT INTO table (long, lati) VALUES('$long', '$lati')";
if(mysqli_query($con, $sql)){
    mysqli_close($con);
}
?>

LogCat:

10-29 06:27:10.528 1919-1919/com.employeetracker.theworkstation.attempt2 I/art﹕ Not late-enabling -Xcheck:jni (already on)

10-29 06:27:10.849 1919-1941/com.employeetracker.theworkstation.attempt2 D/OpenGLRenderer﹕ Use EGL_SWAP_BEHAVIOR_PRESERVED: true

10-29 06:27:10.852 1919-1919/com.employeetracker.theworkstation.attempt2 D/﹕ HostConnection::get() New Host Connection established 0xb3eb3ef0, tid 1919

10-29 06:27:10.876 1919-1927/com.employeetracker.theworkstation.attempt2 W/art﹕ Suspending all threads took: 12.031ms

10-29 06:27:10.890 1919-1919/com.employeetracker.theworkstation.attempt2 D/Atlas﹕ Validating map...

10-29 06:27:10.919 1919-1941/com.employeetracker.theworkstation.attempt2 D/﹕ HostConnection::get() New Host Connection established 0xb3ffd110, tid 1941

10-29 06:27:10.959 1919-1941/com.employeetracker.theworkstation.attempt2 I/OpenGLRenderer﹕ Initialized EGL, version 1.4

10-29 06:27:11.009 1919-1941/com.employeetracker.theworkstation.attempt2 D/OpenGLRenderer﹕ Enabling debug mode 0

10-29 06:27:11.036 1919-1941/com.employeetracker.theworkstation.attempt2 W/EGL_emulation﹕ eglSurfaceAttrib not implemented

10-29 06:27:11.036 1919-1941/com.employeetracker.theworkstation.attempt2 W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xb3f1d580, error=EGL_SUCCESS

10-29 06:27:11.409 1919-1922/com.employeetracker.theworkstation.attempt2 W/art﹕ Suspending all threads took: 250.499ms

10-29 06:27:11.473 1919-1941/com.employeetracker.theworkstation.attempt2 W/EGL_emulation﹕ eglSurfaceAttrib not implemented

10-29 06:27:11.474 1919-1941/com.employeetracker.theworkstation.attempt2 W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xb3eabf80, error=EGL_SUCCESS

10-29 06:27:11.566 1919-1927/com.employeetracker.theworkstation.attempt2 I/art﹕ Background partial concurrent mark sweep GC freed 2566(119KB) AllocSpace objects, 0(0B) LOS objects, 50% free, 1000KB/2024KB, paused 4.554ms total 147.763ms

10-29 06:27:11.588 1919-1927/com.employeetracker.theworkstation.attempt2 W/art﹕ Suspending all threads took: 11.688ms

10-29 06:27:11.669 1919-1919/com.employeetracker.theworkstation.attempt2 I/Choreographer﹕ Skipped 31 frames! The application may be doing too much work on its main thread.

UPDATE:

10-30 01:39:39.374 10716-10731/com.employeetracker.theworkstation.attempt2 E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1 Process: com.employeetracker.theworkstation.attempt2, PID: 10716 java.lang.RuntimeException: An error occured while executing doInBackground()

at android.os.AsyncTask$3.done(AsyncTask.java:304)

        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)

        at java.util.concurrent.FutureTask.setException(FutureTask.java:222)

        at java.util.concurrent.FutureTask.run(FutureTask.java:242)

        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)

        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)

        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)

        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:344)

        at android.widget.Toast.<init>(Toast.java:100)

        at android.widget.Toast.makeText(Toast.java:258)

        at com.employeetracker.theworkstation.attempt2.MainActivity.show(MainActivity.java:39)

        at com.employeetracker.theworkstation.attempt2.MainActivity$SendData.doInBackground(MainActivity.java:80)

        at com.employeetracker.theworkstation.attempt2.MainActivity$SendData.doInBackground(MainActivity.java:42)

        at android.os.AsyncTask$2.call(AsyncTask.java:292)

         at java.util.concurrent.FutureTask.run(FutureTask.java:237)

              at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)

             at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)

             at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)

             at java.lang.Thread.run(Thread.java:818) 10-30 01:39:43.082 10716-10731/com.employeetracker.theworkstation.attempt2 I/Process﹕ Sending signal. PID: 10716 SIG: 9

  • 写回答

2条回答 默认 最新

  • dryk50495 2015-10-28 15:04
    关注

    I have completely changed my answer, because the issue here is clear now. As I mentioned in the comments below, you cannot run a connection to the server on the main thread(meaning your activity or fragment currently running). What needs to be done is run it in an async class. Create a class as follows:

    class SendData extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {
         try{
                //Your code 
                }
        return null;
    }
    }
    

    Then you can call this class by creating an instance from it in your activity/fragment, and execute it.

    You can find details on this blog post on how to do it correctly

    评论

报告相同问题?

悬赏问题

  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 github训练的模型参数无法下载
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题