随着Android的HTTP示例/教程 - 颁布实施异步任务的网络活动 [英] Following Android HTTP Example / Tutorial - Issue Implementing Async Task for Network Activity

查看:87
本文介绍了随着Android的HTTP示例/教程 - 颁布实施异步任务的网络活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图遵循教程发布有关HTTP数据但是它的力量关闭主线程由于IO线程上的网络活动,所以我已经尝试实现的AsyncTask(所建议的一些其他有用的,因此用户 - 然而,我已经屠杀了code和事情的方方面面的力量对我关闭。)

<一个href="http://webtutsdepot.com/2011/11/15/android-tutorial-how-to-post-data-from-an-android-app-to-a-website/" rel="nofollow">http://webtutsdepot.com/2011/11/15/android-tutorial-how-to-post-data-from-an-android-app-to-a-website/

在此先感谢!

NoobNinja

JAVA:

 进口java.io.IOException异常;
进口org.apache.http.client.ClientProtocolException;


进口的java.util.ArrayList;
进口android.os.AsyncTask;
进口的java.util.List;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.impl.client.DefaultHttpClient;


进口org.apache.http.NameValuePair;
进口org.apache.http.client.entity.UrlEn codedFormEntity;
进口org.apache.http.message.BasicNameValuePair;

//输入你需要的一切
进口android.app.Activity;
进口android.os.Bundle;
进口android.view.View;
进口android.widget.Button;
进口android.widget.EditText;
进口android.widget.Toast;


公共类DeviceConfig软件扩展了活动{

    AsyncTask的&LT;对象,对象,对象&gt; saveContactTask =
            新的AsyncTask&LT;对象,对象,对象&gt;()
            {
               @覆盖
               保护对象doInBackground(对象... PARAMS)
               {

                  返回null;
               }

               @覆盖
               保护无效onPostExecute(对象结果)
               {

               }


               @覆盖
               保护无效saveContactTask.execute()
               {

               }


            ;

            @覆盖
            保护对象doInBackground(对象... PARAMS)
            {

               返回null;

            }
    按钮sendButton;

    的EditText msgTextField;

    / **第一次创建活动时调用。 * /
    @覆盖
    公共无效的onCreate(包savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        //将布局
        的setContentView(R.layout.deviceconfig);

        //使消息文本字段对象
        msgTextField =(EditText上)findViewById(R.id.msgTextField);
        //使发送按钮对象
        sendButton =(按钮)findViewById(R.id.sendButton);

    }



    //这是当您单击该按钮被调用的函数
    公共无效发送(查看V);
    保护无效saveContactTask.execute();

        //从消息文本框中输入消息
        弦乐味精= msgTextField.getText()的toString()。 {

        //确保字段不为空
        如果(msg.length()大于0)
        {
            HttpClient的HttpClient的=新DefaultHttpClient();
            HttpPost httppost =新HttpPost(http://gamedemo.hostzi.com/test.php);
         尝试 {
           名单&LT;的NameValuePair&GT; namevaluepairs中=新的ArrayList&LT;的NameValuePair&GT;(2);
           nameValuePairs.add(新BasicNameValuePair(ID,12345));
           nameValuePairs.add(新BasicNameValuePair(信息,MSG));
           httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));
           httpclient.execute(httppost);
           msgTextField.setText(); //清晰的文本框
         }赶上(ClientProtocolException E){
             // TODO自动生成的catch块
         }赶上(IOException异常E){
             // TODO自动生成的catch块
         }

        }
        其他
        {
            //如果显示消息文本字段为空
            Toast.makeText(getBaseContext(),所有的领域都需要,Toast.LENGTH_SHORT).show();
        }

    }

}
 

XML:

 &LT; XML版本=1.0编码=UTF-8&GT?;
&LT; LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:方向=垂直
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =FILL_PARENT
    &GT;
    &LT;的TextView
        机器人:文本=消息
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =WRAP_CONTENT
        /&GT;

    &LT;的EditText
        机器人:ID =@ + ID / msgTextField
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =WRAP_CONTENT
        /&GT;
    &LT;按钮
        机器人:文=发送
        机器人:ID =@ + ID / sendButton
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =WRAP_CONTENT
        机器人:的onClick =送
        /&GT;

&LT; / LinearLayout中&GT;
 

PHP:

 &LT; PHP
//从POST请求的消息变量
//这是从Android应用程序传来的数据
$消息= $ _ POST [信息];
//指定文件,我们将保存可变信息的内容
$文件名=androidmessages.html;
//写入(附加)的数据,以文件
file_put_contents($文件名,$消息。&LT; BR /&gt;中,FILE_APPEND);
//加载文件的内容,以一个可变
$ androidmessages =的file_get_contents($文件名);
//显示变量的内容(其具有该文件的内容)
回声$ androidmessages;
?&GT;
 

logcat的:

  03-27 16:30:00.775:D / dalvikvm(14566):GC_FOR_ALLOC释放88K,3%的自由7355K / 7568K,暂停36ms,共36ms
03-27 16:30:00.785:I / dalvikvm堆(14566):成长堆(破片的情况下),以10.818MB为3686416字节分配
03-27 16:30:00.825:D / dalvikvm(14566):GC_FOR_ALLOC释放1K,免费10953K / 11172K,暂停为35ms,共为35ms 2%
03-27 16:30:00.845:D / dalvikvm(14566):GC_CONCURRENT释放&LT; 1K,免费10953K / 11172K 2%,暂停3毫秒+ 3ms的,总29ms
03-27 16:30:01.095:D / dalvikvm(14566):GC_FOR_ALLOC释放&LT; 1K,免费10953K / 11172K 2%,暂停16ms的,共有16毫秒
03-27 16:30:01.105:I / dalvikvm堆(14566):成长堆(破片的情况下),以17.043MB为6529744字节分配
03-27 16:30:01.125:D / dalvikvm(14566):GC_FOR_ALLOC释放0K,免费17330K / 17552K,暂停16毫秒,16毫秒总额2%
03-27 16:30:01.145:D / dalvikvm(14566):GC_CONCURRENT释放0K,2%自由17330K / 17552K,暂停3毫秒+ 3ms的,总23MS
03-27 16:30:01.275:D / libEGL(14566):加载/system/lib/egl/libEGL_tegra.so
03-27 16:30:01.285:D / libEGL(14566):加载/system/lib/egl/libGLESv1_CM_tegra.so
03-27 16:30:01.295:D / libEGL(14566):加载/system/lib/egl/libGLESv2_tegra.so
03-27 16:30:01.325:D / OpenGLRenderer(14566):启用调试模式0
03-27 16:30:03.325:D / AndroidRuntime(14566):关闭虚拟机
03-27 16:30:03.325:W / dalvikvm(14566):主题ID = 1:螺纹退出与未捕获的异常(组= 0x41cd2930)
03-27 16:30:03.325:E / AndroidRuntime(14566):致命异常:主要
03-27 16:30:03.325:E / AndroidRuntime(14566):java.lang.Error:未解决的编译问题:
03-27 16:30:03.325:E / AndroidRuntime(14566):语法令牌的错误;预期
03-27 16:30:03.325:E / AndroidRuntime(14566):语法错误,插入;完成FieldDeclaration
03-27 16:30:03.325:E / AndroidRuntime(14566):语法错误,将}来完成ClassBody
。03-27 16:30:03.325:E / AndroidRuntime(14566):在com.nfc.linkingmanager.DeviceConfig&LT; INIT&GT;(DeviceConfig.java:48)
03-27 16:30:03.325:E / AndroidRuntime(14566):在java.lang.Class.newInstanceImpl(本机方法)
03-27 16:30:03.325:E / AndroidRuntime(14566):在java.lang.Class.newInstance(Class.java:1319)
03-27 16:30:03.325:E / AndroidRuntime(14566):在android.app.Instrumentation.newActivity(Instrumentation.java:1054)
03-27 16:30:03.325:E / AndroidRuntime(14566):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
03-27 16:30:03.325:E / AndroidRuntime(14566):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-27 16:30:03.325:E / AndroidRuntime(14566):在android.app.ActivityThread.access $ 600(ActivityThread.java:141)
03-27 16:30:03.325:E / AndroidRuntime(14566):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1234)
03-27 16:30:03.325:E / AndroidRuntime(14566):在android.os.Handler.dispatchMessage(Handler.java:99)
03-27 16:30:03.325:E / AndroidRuntime(14566):在android.os.Looper.loop(Looper.java:137)
03-27 16:30:03.325:E / AndroidRuntime(14566):在android.app.ActivityThread.main(ActivityThread.java:5041)
03-27 16:30:03.325:E / AndroidRuntime(14566):在java.lang.reflect.Method.invokeNative(本机方法)
03-27 16:30:03.325:E / AndroidRuntime(14566):在java.lang.reflect.Method.invoke(Method.java:511)
03-27 16:30:03.325:E / AndroidRuntime(14566):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:793)
03-27 16:30:03.325:E / AndroidRuntime(14566):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-27 16:30:03.325:E / AndroidRuntime(14566):在dalvik.system.NativeStart.main(本机方法)
 

解决方案
  

NetworkOnMainThreadException

您也越来越异常,因为你是做在主线程网络操作是不允许的Andr​​oid版本> = 3.0。

使用的AsyncTask做网络操作。

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

Android的阅读文档的 AsyncTask的

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)

解决方案

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.

这篇关于随着Android的HTTP示例/教程 - 颁布实施异步任务的网络活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆