0

我是安卓新手。

我需要为 Activity 创建某种预加载器。现在我点击按钮说“显示公司”,然后我进入下一个活动,从服务器加载数据并显示在里面。问题是(据我了解)该活动正在与互联网连接,并且在连接完成之前没有任何显示。用户必须等待,然后突然(几秒钟后 - 变化)他会根据新活动获得新的 100% 就绪页面。

对我来说最好的方法是:创建一个显示动画,直到活动完全加载。(这将解决任何地方的问题)

替代方案是:在连接到 Internet url 之前加载新活动。当它加载时,它会说“加载数据”之类的默认值,直到从 url 下载全文,它将替换第一个文本。

这是我用来从 URL 加载文本的代码。

    try {
        // Create a URL for the desired page
        URL url = new URL(serwer_url);

        // Read all the text returned by the server
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String str;
        while ((str = in.readLine()) != null) {
            // str is one line of text; readLine() strips the newline character(s)
            Plain_str = Plain_str + str; 
        }
        Log.i("Plain read str", Plain_str);
        in.close();


    } catch (MalformedURLException e) {
    } catch (IOException e) {}      
    //end of reading file       

    //here is the anchor to the text in activity
    TextView MainText = (TextView)findViewById(R.id.TextMain);      
    MainText.setText(Html.fromHtml(Plain_str.toString()));
4

1 回答 1

2

您可以像这样使用 AsyncTask:

protected class Mytask extends AsyncTask<Void, Void, String>{

        @Override
        protected String doInBackground(Void... params) {
            String Plain_str= null;
            try {
                // Create a URL for the desired page
                URL url = new URL(serwer_url);

                // Read all the text returned by the server
                BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                String str;
                while ((str = in.readLine()) != null) {
                    // str is one line of text; readLine() strips the newline character(s)
                    Plain_str = Plain_str + str; 
                }
                Log.i("Plain read str", Plain_str);
                in.close();


            } catch (MalformedURLException e) {
            } catch (IOException e) {}   

            return Plain_str;
        }
        protected void onPostExecute(String str){
            TextView MainText = (TextView)findViewById(R.id.TextMain);      
            MainText.setText(Html.fromHtml(str.toString()));
        }
    }

然后执行任务

new MyTask().execute();
于 2012-11-06T13:00:04.860 回答