-1

我对此很陌生-我添加了一些源代码来实现 AsyncTask,但由于在 IO 线程上运行而不是实现 AsyncTask,它仍然强制关闭。我知道我做错了什么,但我不确定它可能是什么。

爪哇:

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


import java.util.ArrayList;
import android.os.AsyncTask;
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 DeviceConfig  extends Activity {

    AsyncTask<Object, Object, Object> saveContactTask = 
            new AsyncTask<Object, Object, Object>() 
            {
               @Override
               protected Object doInBackground(Object... params) 
               {

                  return null;
               }

               @Override
               protected void onPostExecute(Object result) 
               {
                  finish();
               }
            }; 



    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.deviceconfig);        

        // 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://gamedemo.hostzi.com/test.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();
        }

    }

}

XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView
        android:text="Message"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        /> 

    <EditText
        android:id="@+id/msgTextField"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />
    <Button
        android:text="Send"
        android:id="@+id/sendButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="send"
        /> 

</LinearLayout>

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

日志猫:

    03-27 16:07:05.795: D/dalvikvm(11620): Late-enabling CheckJNI
03-27 16:07:05.935: D/dalvikvm(11620): GC_FOR_ALLOC freed 88K, 3% free 7355K/7568K, paused 18ms, total 19ms
03-27 16:07:05.945: I/dalvikvm-heap(11620): Grow heap (frag case) to 10.818MB for 3686416-byte allocation
03-27 16:07:05.975: D/dalvikvm(11620): GC_FOR_ALLOC freed 1K, 2% free 10953K/11172K, paused 25ms, total 25ms
03-27 16:07:05.995: D/dalvikvm(11620): GC_CONCURRENT freed <1K, 2% free 10953K/11172K, paused 3ms+2ms, total 18ms
03-27 16:07:06.285: D/dalvikvm(11620): GC_FOR_ALLOC freed <1K, 2% free 10953K/11172K, paused 15ms, total 16ms
03-27 16:07:06.305: I/dalvikvm-heap(11620): Grow heap (frag case) to 17.043MB for 6529744-byte allocation
03-27 16:07:06.315: D/dalvikvm(11620): GC_FOR_ALLOC freed 0K, 2% free 17330K/17552K, paused 16ms, total 16ms
03-27 16:07:06.335: D/dalvikvm(11620): GC_CONCURRENT freed <1K, 2% free 17330K/17552K, paused 3ms+2ms, total 21ms
03-27 16:07:06.435: D/libEGL(11620): loaded /system/lib/egl/libEGL_tegra.so
03-27 16:07:06.455: D/libEGL(11620): loaded /system/lib/egl/libGLESv1_CM_tegra.so
03-27 16:07:06.465: D/libEGL(11620): loaded /system/lib/egl/libGLESv2_tegra.so
03-27 16:07:06.485: D/OpenGLRenderer(11620): Enabling debug mode 0
03-27 16:07:19.615: W/IInputConnectionWrapper(11620): showStatusIcon on inactive InputConnection
03-27 16:07:45.695: D/AndroidRuntime(11620): Shutting down VM
03-27 16:07:45.695: W/dalvikvm(11620): threadid=1: thread exiting with uncaught exception (group=0x41cd2930)
03-27 16:07:45.695: E/AndroidRuntime(11620): FATAL EXCEPTION: main
03-27 16:07:45.695: E/AndroidRuntime(11620): java.lang.IllegalStateException: Could not execute method of the activity
03-27 16:07:45.695: E/AndroidRuntime(11620):    at android.view.View$1.onClick(View.java:3599)
03-27 16:07:45.695: E/AndroidRuntime(11620):    at android.view.View.performClick(View.java:4204)
03-27 16:07:45.695: E/AndroidRuntime(11620):    at android.view.View$PerformClick.run(View.java:17355)
03-27 16:07:45.695: E/AndroidRuntime(11620):    at android.os.Handler.handleCallback(Handler.java:725)
03-27 16:07:45.695: E/AndroidRuntime(11620):    at android.os.Handler.dispatchMessage(Handler.java:92)
03-27 16:07:45.695: E/AndroidRuntime(11620):    at android.os.Looper.loop(Looper.java:137)
03-27 16:07:45.695: E/AndroidRuntime(11620):    at android.app.ActivityThread.main(ActivityThread.java:5041)
03-27 16:07:45.695: E/AndroidRuntime(11620):    at java.lang.reflect.Method.invokeNative(Native Method)
03-27 16:07:45.695: E/AndroidRuntime(11620):    at java.lang.reflect.Method.invoke(Method.java:511)
03-27 16:07:45.695: E/AndroidRuntime(11620):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-27 16:07:45.695: E/AndroidRuntime(11620):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-27 16:07:45.695: E/AndroidRuntime(11620):    at dalvik.system.NativeStart.main(Native Method)
03-27 16:07:45.695: E/AndroidRuntime(11620): Caused by: java.lang.reflect.InvocationTargetException
03-27 16:07:45.695: E/AndroidRuntime(11620):    at java.lang.reflect.Method.invokeNative(Native Method)
03-27 16:07:45.695: E/AndroidRuntime(11620):    at java.lang.reflect.Method.invoke(Method.java:511)
03-27 16:07:45.695: E/AndroidRuntime(11620):    at android.view.View$1.onClick(View.java:3594)
03-27 16:07:45.695: E/AndroidRuntime(11620):    ... 11 more
03-27 16:07:45.695: E/AndroidRuntime(11620): Caused by: android.os.NetworkOnMainThreadException
03-27 16:07:45.695: E/AndroidRuntime(11620):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
03-27 16:07:45.695: E/AndroidRuntime(11620):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
03-27 16:07:45.695: E/AndroidRuntime(11620):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
03-27 16:07:45.695: E/AndroidRuntime(11620):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
03-27 16:07:45.695: E/AndroidRuntime(11620):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
03-27 16:07:45.695: E/AndroidRuntime(11620):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
03-27 16:07:45.695: E/AndroidRuntime(11620):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
03-27 16:07:45.695: E/AndroidRuntime(11620):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
03-27 16:07:45.695: E/AndroidRuntime(11620):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
03-27 16:07:45.695: E/AndroidRuntime(11620):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
03-27 16:07:45.695: E/AndroidRuntime(11620):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
03-27 16:07:45.695: E/AndroidRuntime(11620):    at com.nfc.linkingmanager.DeviceConfig.send(DeviceConfig.java:84)
03-27 16:07:45.695: E/AndroidRuntime(11620):    ... 14 more
4

2 回答 2

3

您需要将 HttpClient 的内容移到 AsyncTask 中,因为您无法在主线程上进行网络调用。

您也没有调用 saveContactTask.execute()。在 onPostExecute() 我不认为你想调用 finish() 因为那会杀死你的活动。

于 2013-03-27T20:03:23.153 回答
0

您永远不会调用 saveContactTask.execute()。这是我肯定看到的一件事。发送需要在 doInBackground() 中调用。saveContactTask.execute() 需要在您单击按钮时调用。

于 2013-03-27T20:01:31.137 回答