当任何形式的循环中的Andr​​oid code介绍main.xml中不加载 [英] Main.xml not loading when a loop of any sort introduced in Android code

查看:158
本文介绍了当任何形式的循环中的Andr​​oid code介绍main.xml中不加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参考以下code,它抓住了从PHP脚本的一些信息,并将其显示在我的手机上:

Please refer to the following code, which grabs some information from a PHP script, and displays it on my phone:

package room.temperature;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class RoomTemperatureActivity extends Activity {

    String result = null;
    StringBuilder sb=null;

    TextView TemperatureText, DateText;
    ArrayList<NameValuePair> nameValuePairs;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        TemperatureText = (TextView) findViewById(R.id.temperature); 
        DateText = (TextView) findViewById(R.id.date); 
        nameValuePairs = new ArrayList<NameValuePair>();
    }

    @Override
    public void onResume() {
        super.onResume();
        //setValues();

        for (int i = 0; i < 10; i++) {
            setValues();
        }
    }

    public void setValues() {

        InputStream is = null;

        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://mywebsite.com/tempscript.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        }

        catch(Exception e)  {
            Log.e("log_tag", "Error in http connection" + e.toString());
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            sb = new StringBuilder();
            sb.append(reader.readLine());
            is.close();
            result=sb.toString();
        }

        catch(Exception e)  {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        System.out.println(result);

        String[] values = result.split("&");

        TemperatureText.setText(values[0]);
        DateText.setText(values[1]);

    }
}

这code,当我注释掉for循环,并调用 setValues​​方法()曾经的伟大工程。然而,当我介绍了循环,的main.xml (或屏幕上的任何内容)不加载,直到循环完成。我认为它有一些东西需要与该活动的生命周期,但无论在哪里我试图把我的code,简单说就是不工作的权利。从本质上讲,我希望这些值不断更新每次我打电话 setValues​​方法时间()。 10迭代循环只是用于测试的概念。

This code works great when I comment out the for-loop, and just call setValues() once. However, as soon as I introduce the loop, main.xml (or anything on the screen) does not load until the loop is complete. I thought it had something to do with the activity life cycle, but no matter where I have tried putting my code, it simply is not working right. Essentially, I want the values to keep updating every time I call setValues(). A 10 iteration loop is just for testing the concept.

推荐答案

您需要了解UI线程是如何工作的理解,为什么你看不到任何东西,直到循环完成。 UI线程包含消息循环,邮件(你可以把它们想象成code小块)推入和串行执行(1一次)。当UI线程上运行您的code,它会做所有你问它,但屏幕上的值将是贴,或者发送到消息循环的下一个可用的时间确实被放置在屏幕上。你不应该做的UI线程,这也是为什么Android系统已经拿出了应对长期运行操作的多种方式对长期运行的操作。最常见的情况是使用AsyncTask的。

You need to understand how the UI thread works to understand why you don't see anything until the loop completes. The UI thread contains a message loop where messages (you can think of them as small blocks of code) are pushed onto and executed serially (1 at a time). When the UI thread runs your code, it will do all that you ask of it but the values on screen will be "posted", or sent into the message loop to actually be placed on the screen at the next available time. You are not supposed to do long running operations on the UI thread, which is why the Android system has come up with multiple ways of dealing with long running operations. The most common scenario is to use an AsyncTask.

HTTP调用不应该在UI线程上执行,事实上这将失败上运行的蜂窝状或更高版本的设备(除非你介绍你的code一些黑客)。

Http calls should never be executed on the UI thread, in fact this will fail on devices running honeycomb or later (unless you introduce some hacks in your code).

您应该把你的HTTP调用在的AsyncTask doInBackground 方法。然后设置 onPostExecute 方法,你可以对UI方法的调用(.setText方法)。
你会希望把所有的数据转换成某种数据结构,如在doInBackground方法一个ArrayList

You should put your http calls in an AsyncTask in the doInBackground method. Then set the onPostExecute method you can make your calls to the UI methods (.setText methods). You'll want to put all the data into some kind of data structure such as an ArrayList in the doInBackground method.

这篇关于当任何形式的循环中的Andr​​oid code介绍main.xml中不加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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