java - Activity 之间的预加载器 - android java

标签 java android

我是 Android 新手。

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

对我来说最好的办法是:创建一个加载动画,直到 Activity 完全加载为止。 (这可以解决所有问题)

替代方案是:在连接互联网网址之前加载新 Activity 。加载时,它会默认显示“正在加载数据”,直到从 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()));

最佳答案

您可以像这样使用 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();

关于java - Activity 之间的预加载器 - android java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13251168/

相关文章:

android - 我能知道 X dp 宽度的 TextView 可以容纳多少个字符吗?

Java:通用方法和数字

java - MergeSort - 实现

java - 使用自定义对象映射器在 Vertx 4.0 中注册 Jackson Codec 的地方在哪里

java - 这个值 "20150716203621.000Z"的时间格式的技术术语是什么?

android - Gradle 任务更改构建配置中的 bool 值

java - PushBot 接收推送通知会导致应用程序在未运行时崩溃

Android facebook sdk 内部实用程序 java.lang.AssertionError

android - listview android中的离散滚动

java - 输入新条目时需要更新部分页面