【问题标题】:Following Android HTTP Example / Tutorial - Issue Implementing Async Task for Network Activity关注 Android HTTP 示例/教程 - 为网络活动实现异步任务的问题
【发布时间】:2013-03-28 04:32:56
【问题描述】:

我正在尝试遵循有关发布 HTTP 数据的教程,但是由于 IO 线程上的网络活动,它在主线程上强制关闭,因此我尝试实现 AsyncTask(正如其他几个有用的 SO 用户所建议的那样 - 但是我已经杀掉了代码,整个辣酱玉米饼馅的力量都在我身上。)

: (

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

提前致谢!

菜鸟忍者

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)

【问题讨论】:

  • 您是否使用LogCat 生成任何日志?
  • 您正在尝试在 UI 线程上执行网络操作,如果您使用的是 android 3.x 或更高版本,则会出现异常。
  • @NoobNinja 根据答案更新你的问题不好..
  • @NoobNinja 你犯了大错。学习 SO 的规则。不是这样如果你找到你的解决方案然后用不同的问题编辑完整的问题。
  • @Pragnani 我们现在应该采取行动。我们不应该吗?

标签: java android http post


【解决方案1】:

NetworkOnMainThreadException

您遇到异常是因为您在主线程上进行网络操作,而该主线程不允许 android 版本 >= 3.0。

使用AsyncTask做网络操作。

用doInBackground()方法做你的网络操作。

阅读 AsyncTask 的 android 文档。

【讨论】:

  • 我在上面实现了它......但它仍然崩溃(我需要帮助清理一下项目 - 但使用 eclipse 建议看起来完全不正确 - 它要求我把 ; 在一些看起来很奇怪的地方
  • 你放了不需要的大括号和分号。在eclipse中签入代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-05
相关资源
最近更新 更多