Following Android HTTP Example / Tutorial - Issue

2019-03-07 03:41发布

问题:

I'm attempting to follow a tutorial regarding posting HTTP data however its force closing on the main thread due to network activity on the IO thread so I've attempted to implement AsyncTask (as suggested by several other helpful SO users - however I've butchered the code and the whole enchilada force closes on me.)

: (

http://webtutsdepot.com/2011/11/15/android-tutorial-how-to-post-data-from-an-android-app-to-a-website/

Thanks in advance!

NoobNinja

JAVA:

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) 
               {

               }


               @Override
               protected void saveContactTask.execute()
               {

               }


            ; 

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

               return null; 

            }
    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);
    protected void saveContactTask.execute();

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

LOGCAT:

    03-27 16:30:00.775: D/dalvikvm(14566): GC_FOR_ALLOC freed 88K, 3% free 7355K/7568K, paused 36ms, total 36ms
03-27 16:30:00.785: I/dalvikvm-heap(14566): Grow heap (frag case) to 10.818MB for 3686416-byte allocation
03-27 16:30:00.825: D/dalvikvm(14566): GC_FOR_ALLOC freed 1K, 2% free 10953K/11172K, paused 35ms, total 35ms
03-27 16:30:00.845: D/dalvikvm(14566): GC_CONCURRENT freed <1K, 2% free 10953K/11172K, paused 3ms+3ms, total 29ms
03-27 16:30:01.095: D/dalvikvm(14566): GC_FOR_ALLOC freed <1K, 2% free 10953K/11172K, paused 16ms, total 16ms
03-27 16:30:01.105: I/dalvikvm-heap(14566): Grow heap (frag case) to 17.043MB for 6529744-byte allocation
03-27 16:30:01.125: D/dalvikvm(14566): GC_FOR_ALLOC freed 0K, 2% free 17330K/17552K, paused 16ms, total 16ms
03-27 16:30:01.145: D/dalvikvm(14566): GC_CONCURRENT freed 0K, 2% free 17330K/17552K, paused 3ms+3ms, total 23ms
03-27 16:30:01.275: D/libEGL(14566): loaded /system/lib/egl/libEGL_tegra.so
03-27 16:30:01.285: D/libEGL(14566): loaded /system/lib/egl/libGLESv1_CM_tegra.so
03-27 16:30:01.295: D/libEGL(14566): loaded /system/lib/egl/libGLESv2_tegra.so
03-27 16:30:01.325: D/OpenGLRenderer(14566): Enabling debug mode 0
03-27 16:30:03.325: D/AndroidRuntime(14566): Shutting down VM
03-27 16:30:03.325: W/dalvikvm(14566): threadid=1: thread exiting with uncaught exception (group=0x41cd2930)
03-27 16:30:03.325: E/AndroidRuntime(14566): FATAL EXCEPTION: main
03-27 16:30:03.325: E/AndroidRuntime(14566): java.lang.Error: Unresolved compilation problems: 
03-27 16:30:03.325: E/AndroidRuntime(14566):    Syntax error on token ".", ; expected
03-27 16:30:03.325: E/AndroidRuntime(14566):    Syntax error, insert ";" to complete FieldDeclaration
03-27 16:30:03.325: E/AndroidRuntime(14566):    Syntax error, insert "}" to complete ClassBody
03-27 16:30:03.325: E/AndroidRuntime(14566):    at com.nfc.linkingmanager.DeviceConfig.<init>(DeviceConfig.java:48)
03-27 16:30:03.325: E/AndroidRuntime(14566):    at java.lang.Class.newInstanceImpl(Native Method)
03-27 16:30:03.325: E/AndroidRuntime(14566):    at java.lang.Class.newInstance(Class.java:1319)
03-27 16:30:03.325: E/AndroidRuntime(14566):    at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
03-27 16:30:03.325: E/AndroidRuntime(14566):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
03-27 16:30:03.325: E/AndroidRuntime(14566):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-27 16:30:03.325: E/AndroidRuntime(14566):    at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-27 16:30:03.325: E/AndroidRuntime(14566):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-27 16:30:03.325: E/AndroidRuntime(14566):    at android.os.Handler.dispatchMessage(Handler.java:99)
03-27 16:30:03.325: E/AndroidRuntime(14566):    at android.os.Looper.loop(Looper.java:137)
03-27 16:30:03.325: E/AndroidRuntime(14566):    at android.app.ActivityThread.main(ActivityThread.java:5041)
03-27 16:30:03.325: E/AndroidRuntime(14566):    at java.lang.reflect.Method.invokeNative(Native Method)
03-27 16:30:03.325: E/AndroidRuntime(14566):    at java.lang.reflect.Method.invoke(Method.java:511)
03-27 16:30:03.325: E/AndroidRuntime(14566):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-27 16:30:03.325: E/AndroidRuntime(14566):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-27 16:30:03.325: E/AndroidRuntime(14566):    at dalvik.system.NativeStart.main(Native Method)

回答1:

NetworkOnMainThreadException

You are getting exception because you are doing network operation on main thread which is not allow android version >= 3.0.

Use AsyncTask to do network operation.

Do your network operation in doInBackground() method.

Read android docs for AsyncTask.