dongwuchu0314 2014-05-27 16:22
浏览 72
已采纳

如何显示从Android到PHP的消息? [重复]

This question already has an answer here:

I am trying to create a function in an Android app that sends a message to a PHP file on a webserver (in my case, localhost) and have the PHP display the text. I am able to connect with the PHP file but only read JSON data from the file. I want to send data to the file and display it. Any ideas on how I can do this? I have tried a tutorial but my app is crashing.

Here is my code for this tutorial:

PHP code:

<?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;
?>

Activity:

package com.yoursite.helloworld;

import java.io.IOException;
import org.apache.http.client.ClientProtocolException;


import java.util.ArrayList;
import java.util.List;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;


import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;

// import everything you need
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


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://10.0.0.9/testPHP.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();
    }

}

}

Logcat:

05-27 12:27:18.400: I/Process(9241): Sending signal. PID: 9241 SIG: 9
05-27 12:27:24.705: D/libEGL(9361): loaded /vendor/lib/egl/libEGL_POWERVR_SGX540_120.so
05-27 12:27:24.705: D/libEGL(9361): loaded /vendor/lib/egl/libGLESv1_CM_POWERVR_SGX540_120.so
05-27 12:27:24.713: D/libEGL(9361): loaded /vendor/lib/egl/libGLESv2_POWERVR_SGX540_120.so
05-27 12:27:24.783: D/OpenGLRenderer(9361): Enabling debug mode 0
05-27 12:27:31.838: D/AndroidRuntime(9361): Shutting down VM
05-27 12:27:31.838: W/dalvikvm(9361): threadid=1: thread exiting with uncaught exception (group=0x416fe7c0)
05-27 12:27:31.845: E/AndroidRuntime(9361): FATAL EXCEPTION: main
05-27 12:27:31.845: E/AndroidRuntime(9361): java.lang.IllegalStateException: Could not execute method of the activity
05-27 12:27:31.845: E/AndroidRuntime(9361):     at android.view.View$1.onClick(View.java:3640)
05-27 12:27:31.845: E/AndroidRuntime(9361):     at android.view.View.performClick(View.java:4247)
05-27 12:27:31.845: E/AndroidRuntime(9361):     at android.view.View$PerformClick.run(View.java:17728)
05-27 12:27:31.845: E/AndroidRuntime(9361):     at android.os.Handler.handleCallback(Handler.java:730)
05-27 12:27:31.845: E/AndroidRuntime(9361):     at android.os.Handler.dispatchMessage(Handler.java:92)
05-27 12:27:31.845: E/AndroidRuntime(9361):     at android.os.Looper.loop(Looper.java:137)
05-27 12:27:31.845: E/AndroidRuntime(9361):     at android.app.ActivityThread.main(ActivityThread.java:5289)
05-27 12:27:31.845: E/AndroidRuntime(9361):     at java.lang.reflect.Method.invokeNative(Native Method)
05-27 12:27:31.845: E/AndroidRuntime(9361):     at java.lang.reflect.Method.invoke(Method.java:525)
05-27 12:27:31.845: E/AndroidRuntime(9361):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
05-27 12:27:31.845: E/AndroidRuntime(9361):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
05-27 12:27:31.845: E/AndroidRuntime(9361):     at dalvik.system.NativeStart.main(Native Method)
05-27 12:27:31.845: E/AndroidRuntime(9361): Caused by: java.lang.reflect.InvocationTargetException
05-27 12:27:31.845: E/AndroidRuntime(9361):     at java.lang.reflect.Method.invokeNative(Native Method)
05-27 12:27:31.845: E/AndroidRuntime(9361):     at java.lang.reflect.Method.invoke(Method.java:525)
05-27 12:27:31.845: E/AndroidRuntime(9361):     at android.view.View$1.onClick(View.java:3635)
05-27 12:27:31.845: E/AndroidRuntime(9361):     ... 11 more
05-27 12:27:31.845: E/AndroidRuntime(9361): Caused by: android.os.NetworkOnMainThreadException
05-27 12:27:31.845: E/AndroidRuntime(9361):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
05-27 12:27:31.845: E/AndroidRuntime(9361):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
05-27 12:27:31.845: E/AndroidRuntime(9361):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
05-27 12:27:31.845: E/AndroidRuntime(9361):     at libcore.io.IoBridge.connect(IoBridge.java:112)
05-27 12:27:31.845: E/AndroidRuntime(9361):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
05-27 12:27:31.845: E/AndroidRuntime(9361):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:460)
05-27 12:27:31.845: E/AndroidRuntime(9361):     at java.net.Socket.connect(Socket.java:832)
05-27 12:27:31.845: E/AndroidRuntime(9361):     at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
05-27 12:27:31.845: E/AndroidRuntime(9361):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
05-27 12:27:31.845: E/AndroidRuntime(9361):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
05-27 12:27:31.845: E/AndroidRuntime(9361):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
05-27 12:27:31.845: E/AndroidRuntime(9361):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
05-27 12:27:31.845: E/AndroidRuntime(9361):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-27 12:27:31.845: E/AndroidRuntime(9361):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-27 12:27:31.845: E/AndroidRuntime(9361):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
 05-27 12:27:31.845: E/AndroidRuntime(9361):    at com.example.testphp.MainActivity.send(MainActivity.java:63)

I have given permission to use the internet. Any ideas on why the app is crashing?

</div>
  • 写回答

1条回答 默认 最新

  • dtgvl48608 2014-05-27 16:39
    关注

    Make sure that you are running your Network stuff out of the mainUI. Example: Do it in a Thread or in an AsyncTask.

    Example:

    In your MainUI new MyAsyncTask().execute();

    private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
    @Override
    protected Double doInBackground(String... params) {
        postData(params[0]);
        return null;
    }
    
    protected void onPostExecute(Double result){} 
    
    protected void onProgressUpdate(Integer... progress){
    pb.setProgress(progress[0]);
    }
    }
    
    public void postData(String valueIWantToSend) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://somewebsite.com/receiver.php");
    
        try {
          List nameValuePairs = new ArrayList();
          nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIwantToSend));
          httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
          HttpResponse response = httpclient.execute(httppost);
        } catch (Exception e) {}
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 (标签-STM32|关键词-智能小车)
  • ¥20 关于#stm32#的问题,请各位专家解答!
  • ¥15 (标签-python)
  • ¥15 第一个已完成,求第二个做法
  • ¥20 搭建awx,试了很多版本都有错
  • ¥15 java corba的客户端该如何指定使用本地某个固定IP去连接服务端?
  • ¥15 activiti工作流问题,求解答
  • ¥15 有人写过RPA后台管理系统么?
  • ¥15 Bioage计算生物学年龄
  • ¥20 如何将FPGA Alveo U50恢复原来出厂设置哇?