2015-02-11 81 views
1

我在本地網絡上的WAMP服務器上運行的php表單...但是當我嘗試運行該文件時,它給了我截圖中的錯誤。我試圖從我的Android應用程序發送數據到Php表單。在按下「發送」按鈕從Android應用程序發送數據到Php

我已經確定也是我的Android應用程序崩潰:

  1. 兩個WAMP和Android應用程序都在同一網絡上
  2. 我也試圖直接訪問從Android上的網址瀏覽器,它帶來了頁面,所以URL不應該是一個麻煩
  3. 我試過使用一個真實的設備和它的相同的錯誤。
  4. 我還在Android Manifest中添加了INTERNET權限!

enter image description here

PHP代碼:

<?php 
// get the "message" variable from the post request 
// this is the data coming from the Android app 
$message=$_POST["message"]; 
// specify the file where we will save the contents of the variable message 
$filename="androidmessages.html"; 
// write (append) the data to the file 
file_put_contents($filename,$message."<br />",FILE_APPEND); 
// load the contents of the file to a variable 
$androidmessages=file_get_contents($filename); 
// display the contents of the variable (which has the contents of the file) 
echo $androidmessages; 
?> 

這裏是Android應用程序的代碼:

public class HelloWorldActivity extends Activity { 

    Button sendButton; 

    EditText msgTextField; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     // load the layout 
     setContentView(R.layout.main);   

     // make message text field object 
     msgTextField = (EditText) findViewById(R.id.msgTextField); 
     // make send button object 
     sendButton = (Button) findViewById(R.id.sendButton); 

    } 

    // this is the function that gets called when you click the button 
    public void send(View v) 
    { 
     // get the message from the message text box 
     String msg = msgTextField.getText().toString(); 

     // make sure the fields are not empty 
     if (msg.length()>0) 
     { 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost("http://192.168.0.40/yourPhpScript.php"); 
     try { 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
      nameValuePairs.add(new BasicNameValuePair("id", "12345")); 
      nameValuePairs.add(new BasicNameValuePair("message", msg)); 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      httpclient.execute(httppost); 
      msgTextField.setText(""); // clear text box 
     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
     } 

     } 
     else 
     { 
      // display message if text fields are empty 
      Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show(); 
     } 

    } 
} 

編輯1:這是根據要求提供原代碼

的logcat的
02-10 23:44:06.570: D/dalvikvm(1919): Not late-enabling CheckJNI (already on) 
02-10 23:44:06.720: D/dalvikvm(1919): GC_CONCURRENT freed 73K, 10% free 2785K/3092K, paused 13ms+0ms, total 16ms 
02-10 23:44:07.550: D/gralloc_goldfish(1919): Emulator without GPU emulation detected. 
02-10 23:44:17.428: D/AndroidRuntime(1919): Shutting down VM 
02-10 23:44:17.428: W/dalvikvm(1919): threadid=1: thread exiting with uncaught exception (group=0xb0f3e648) 
02-10 23:44:17.428: E/AndroidRuntime(1919): FATAL EXCEPTION: main 
02-10 23:44:17.428: E/AndroidRuntime(1919): java.lang.IllegalStateException: Could not execute method of the activity 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at android.view.View$1.onClick(View.java:3633) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at android.view.View.performClick(View.java:4240) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at android.view.View$PerformClick.run(View.java:17721) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at android.os.Handler.handleCallback(Handler.java:730) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at android.os.Handler.dispatchMessage(Handler.java:92) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at android.os.Looper.loop(Looper.java:137) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at android.app.ActivityThread.main(ActivityThread.java:5103) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at java.lang.reflect.Method.invokeNative(Native Method) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at java.lang.reflect.Method.invoke(Method.java:525) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at dalvik.system.NativeStart.main(Native Method) 
02-10 23:44:17.428: E/AndroidRuntime(1919): Caused by: java.lang.reflect.InvocationTargetException 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at java.lang.reflect.Method.invokeNative(Native Method) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at java.lang.reflect.Method.invoke(Method.java:525) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at android.view.View$1.onClick(View.java:3628) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  ... 11 more 
02-10 23:44:17.428: E/AndroidRuntime(1919): Caused by: android.os.NetworkOnMainThreadException 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at libcore.io.IoBridge.connectErrno(IoBridge.java:127) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at libcore.io.IoBridge.connect(IoBridge.java:112) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at java.net.Socket.connect(Socket.java:842) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  at com.diwesh.helloworldactivity.HelloWorldActivity.send(HelloWorldActivity.java:73) 
02-10 23:44:17.428: E/AndroidRuntime(1919):  ... 14 more 

編輯2:從推薦的代碼更改後的logcat

02-11 19:28:35.991: D/AndroidRuntime(1945): Shutting down VM 
02-11 19:28:35.991: W/dalvikvm(1945): threadid=1: thread exiting with uncaught exception (group=0xb0f16648) 
02-11 19:28:35.991: E/AndroidRuntime(1945): FATAL EXCEPTION: main 
02-11 19:28:35.991: E/AndroidRuntime(1945): java.lang.IllegalStateException: Could not execute method of the activity 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at android.view.View$1.onClick(View.java:3633) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at android.view.View.performClick(View.java:4240) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at android.view.View$PerformClick.run(View.java:17721) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at android.os.Handler.handleCallback(Handler.java:730) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at android.os.Handler.dispatchMessage(Handler.java:92) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at android.os.Looper.loop(Looper.java:137) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at android.app.ActivityThread.main(ActivityThread.java:5103) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at java.lang.reflect.Method.invokeNative(Native Method) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at java.lang.reflect.Method.invoke(Method.java:525) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at dalvik.system.NativeStart.main(Native Method) 
02-11 19:28:35.991: E/AndroidRuntime(1945): Caused by: java.lang.reflect.InvocationTargetException 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at java.lang.reflect.Method.invokeNative(Native Method) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at java.lang.reflect.Method.invoke(Method.java:525) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at android.view.View$1.onClick(View.java:3628) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  ... 11 more 
02-11 19:28:35.991: E/AndroidRuntime(1945): Caused by: android.os.NetworkOnMainThreadException 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at libcore.io.IoBridge.connectErrno(IoBridge.java:127) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at libcore.io.IoBridge.connect(IoBridge.java:112) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at java.net.Socket.connect(Socket.java:842) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  at com.diwesh.helloworldactivity.HelloWorldActivity.send(HelloWorldActivity.java:93) 
02-11 19:28:35.991: E/AndroidRuntime(1945):  ... 14 more 
+0

使用'AsyncTask'將數據發佈到服務器 – 2015-02-11 02:15:53

+0

@язык:謝謝你的建議。但我想知道我要去哪裏錯了 – user3828453 2015-02-11 02:27:13

+0

如果應用程序崩潰,然後添加logcat結果的問題,以檢查問題的位置 – 2015-02-11 02:33:30

回答

0

我想這應該爲你在你的Android代碼,這方面的工作,改變http請求,

private void startHttpRequest() 
    { 
    try 
    { 
     new Thread(new Runnable() 
     { 
      public void run() 
      { 

      // get the message from the message text box 
      String msg = msgTextField.getText().toString(); 

      // make sure the fields are not empty 
      if (msg.length()>0) 
      { 
       HttpClient httpclient = new DefaultHttpClient(); 
       HttpPost httppost = new     HttpPost("http://192.168.0.40/yourPhpScript.php"); 
       try 
       { 
       StringEntity se = new StringEntity("id=12345&message="+msg); 
       httppost.setEntity(se); 
       HttpResponse response = httpclient.execute(httppost); 
       msgTextField.setText(""); // clear text box 

       StatusLine statusLine = response.getStatusLine(); 
       if(statusLine.getStatusCode() == HttpStatus.SC_OK) 
       { 
       ByteArrayOutputStream out = new ByteArrayOutputStream(); 
       response.getEntity().writeTo(out); 

       //* this should be the return from your php script $androidmessages 
       String responseString = out.toString(); 
       out.close(); 
       } 
       } 
       catch (ClientProtocolException e) 
       { 
        // TODO Auto-generated catch block 
       } 
       catch (IOException e) { 
        // TODO Auto-generated catch block 
       } 
      } 
      } 
     }).start(); 

    } 
    catch(Exception e) 
    { 
    } 
    } 

然後更改代碼在你php腳本,

<?php 
// get the "message" variable from the post request 
// this is the data coming from the Android app 
$id=$_REQUEST["id"]; 
$message=$_REQUEST["message"]; 
// specify the file where we will save the contents of the variable message 
$filename="androidmessages.html"; 
// write (append) the data to the file 
file_put_contents($filename,$message."<br />",FILE_APPEND); 
// load the contents of the file to a variable 
$androidmessages=file_get_contents($filename); 
// display the contents of the variable (which has the contents of the file) 
echo $androidmessages; 
?> 
+0

謝謝我正在嘗試你的代碼,但我需要導入什麼庫,以使「response.getStatusLine )「工作....它說響應無法解決 – user3828453 2015-02-11 04:35:31

+0

對不起,延遲,我的答案缺失的項目讓我修復它,這應該回答你的問題 – faljbour 2015-02-11 14:34:11

+0

謝謝我會檢查它,並讓你回到......我也應該在同一個目錄中創建一個名爲「androidmessages.html」的文件嗎?或者它會爲我創造,如果萬一它沒有找到?另外如果我創建它,我需要在它內部有一些HTML代碼或保存它只是空白? – user3828453 2015-02-11 23:18:05

0

首先,確保你的PHP腳本是正確的。 然後,刪除該按鈕的XML配置中的'onClick'。 使用下面的代碼。它會工作

public class HelloWorldActivity extends Activity { 

    Button sendButton; 

    EditText msgTextField; 

    /** 
    * Called when the activity is first created. 
    */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     // load the layout 
     setContentView(R.layout.main); 

     // make message text field object 
     msgTextField = (EditText) findViewById(R.id.msgTextField); 
     // make send button object 
     sendButton = (Button) findViewById(R.id.sendButton); 

     sendButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       // check for empty message 
       if (msgTextField.getText().toString().trim().length() > 0) { 
        new sendMessage().execute(); 
       } else { 
        // display message if text fields are empty 
        Toast.makeText(HelloWorldActivity.this, "All field are required", Toast.LENGTH_SHORT).show(); 
       } 
      } 
     }); 

    } 

    private class sendMessage extends AsyncTask<String, String, String> { 

     ProgressDialog dialog; 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      dialog = new ProgressDialog(HelloWorldActivity.this); 
      dialog.setIndeterminate(true); 
      dialog.setMessage("Sending Message..."); 
      dialog.setCancelable(false); 
      dialog.show(); 

     } 

     @Override 
     protected String doInBackground(String... params) { 


      // get the message from the message text box 
      String msg = msgTextField.getText().toString(); 

      // desired URL 
      final String mURL = "http://192.168.0.40/yourPhpScript.php"; 

      // Create a new HttpClient and Post Header 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost(mURL); 
      HttpResponse response; 

      // Add data 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 

      nameValuePairs.add(new BasicNameValuePair("id", "12345")); 
      nameValuePairs.add(new BasicNameValuePair("message", msg)); 


      try { 
       httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
       response = httpclient.execute(httppost); 
       String responseBody = EntityUtils 
         .toString(response.getEntity()); 
       Log.d("Http Post Response:", responseBody); 

      } catch (ClientProtocolException e) { 
       // TODO Auto-generated catch block 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
      } 
      return null; 
     } 

     @Override 
     protected void onPostExecute(String s) { 
      super.onPostExecute(s); 
      dialog.dismiss(); 

      // Toast user for a successful operation 
      Toast.makeText(HelloWorldActivity.this, "Message sent successfully", Toast.LENGTH_LONG).show(); 

      // clear text box 
      msgTextField.setText(""); 

     } 
    } 


} 
相關問題