【问题标题】:Load screen while under async http request在异步 http 请求下加载屏幕
【发布时间】:2014-09-02 22:41:03
【问题描述】:

在启动时,会执行一个异步类,它会抓取网站以获取信息。在将收集的信息填充到列表视图之前,屏幕在此期间保持空白。在此期间有没有办法添加加载屏幕?

我查看了这个 (Add the loading screen in starting of the android application),但我认为这不是我需要的,因为我不知道请求需要多长时间。

感谢您的宝贵时间。

在看到一些答案后,我修改了我的代码,但都没有显示出来。这是我用于活动主要的 xml 文件。列表视图中的默认 textview 元素还有一个 textview 布局 xml 文件。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<ProgressBar
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/progressBar"
    style="?android:attr/progressBarStyleLarge"
    android:layout_centerInParent="true"/>


<ListView
    android:layout_width="match_parent"
    android:layout_height="507dp"
    android:id="@+id/listView"
    android:smoothScrollbar="true" />



</RelativeLayout>

这是主要活动的代码:

    package adam.example.com.stockexample;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;


public class MainActivity extends Activity {
    private int index=-1;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final ListView ListStock= (ListView)findViewById(R.id.listView);
        final ArrayList<String>symbols= new ArrayList<String>();
        final ProgressBar pb= (ProgressBar)findViewById(R.id.progressBar);
        List<StockElement> stats= new ArrayList<StockElement>();
        List<String> StringList= new ArrayList<String>();

        pb.setVisibility(View.VISIBLE);

        try {
            InputStream inputStream = openFileInput("stocks.txt");

            if ( inputStream != null ) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String receiveString = "";
                StringBuilder stringBuilder = new StringBuilder();

                while ( (receiveString = bufferedReader.readLine()) != null ) {
                    stringBuilder.append(receiveString);
                }

                inputStream.close();
                String []ret = stringBuilder.toString().split(",");

                for(int x=0;x<ret.length;x++){
                    symbols.add(ret[x]);
                }

            }
        }
        catch (FileNotFoundException e) {
            Log.e("login activity", "File not found: " + e.toString());
        } catch (IOException e) {
            Log.e("login activity", "Can not read file: " + e.toString());
        }


        for(int x=0;x<symbols.size();x++){
            stats.add(addStock(symbols.get(x)));
        }
        for(int x=0;x<stats.size();x++){
            StringList.add(stats.get(x).toString());
        }


        final ArrayAdapter<String> stockAdapter=
             new ArrayAdapter<String>(
                    getApplicationContext(),
                    R.layout.list_item_textview,
                    R.id.list_item_textview,
                    StringList);
        pb.setVisibility(View.GONE);
        ListStock.setAdapter(stockAdapter);

        final AlertDialog.Builder builder= new AlertDialog.Builder(this);
        builder.setMessage("Are you sure you would like to delete this?")
                .setTitle("Warning")
                .setPositiveButton("No", null)
                .setNegativeButton("Delete", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        stockAdapter.remove(stockAdapter.getItem(index));
                        symbols.remove(index);

                        WriteBack(symbols);

                        stockAdapter.notifyDataSetChanged();
                    }
                });


        OnItemClickListener itemClickListener = new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
                // Getting the Container Layout of the ListView

                TextView ItemText = (TextView) container;
                String selectedItemText=(String)ItemText.getText();
                String symbol =selectedItemText.substring(selectedItemText.indexOf(":")+1,selectedItemText.lastIndexOf(")"));

                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com/finance?q="+symbol));
                startActivity(browserIntent);
            }
        };

        AdapterView.OnItemLongClickListener itemLongClickListener= new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?>parent, View container, final int position, long id){
                TextView ItemText= (TextView) container;
                String selectedItemText= (String) ItemText.getText();
                index=position;

                builder.show();
                return true;

            }
        };

        ListStock.setOnItemClickListener(itemClickListener);
        ListStock.setOnItemLongClickListener(itemLongClickListener);
    }

    public void WriteBack(ArrayList <String> list){
        try {
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("stocks.txt", Context.MODE_PRIVATE));
            for(int x=0;x<list.size()-1;x++){
                outputStreamWriter.append(list.get(x)+",");
            }
            outputStreamWriter.append(list.get(list.size()-1));

            outputStreamWriter.close();
        }
        catch (IOException e) {
            Log.e("Exception", "File write failed: " + e.toString());
        }
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public StockElement addStock(String sym){
        try {
            String s = new HTTPRequest().execute("http://www.google.com/finance?q="+sym).get();

            String symbol= s.substring(s.indexOf("<title>")+7,s.indexOf("</title>"));
            String name= symbol.substring(0,symbol.indexOf(":"));
            symbol=symbol.substring(symbol.indexOf(":")+2,symbol.indexOf(" quotes"));

            String price= s.substring(s.indexOf("<meta itemprop=\"price\"")+25,s.indexOf("<meta itemprop=\"price\"")+50);

            price= price.substring(price.indexOf("\"")+1,price.lastIndexOf("\""));

            String priceChange= s.substring(s.indexOf("<meta itemprop=\"priceChange\"")+36,s.indexOf("<meta itemprop=\"priceChange\"")+60);

            priceChange=priceChange.substring(priceChange.indexOf("\"")+1,priceChange.lastIndexOf("\""));

            String percent= s.substring(s.indexOf("<meta itemprop=\"priceChangePercent\"")+36,s.indexOf("<meta itemprop=\"priceChangePercent\"")+60);

            percent=percent.substring(percent.indexOf("\"")+1,percent.lastIndexOf("\""));

            return new StockElement(name,symbol,price,priceChange,percent);

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }catch (NullPointerException e){
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

【问题讨论】:

    标签: java android httpwebrequest


    【解决方案1】:

    您可以在 Activity 的布局中添加 ProgresBar(circle)。为了将加载圆圈设置在屏幕中间,您可以使用类似这样的布局。

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:divider="@null" 
        android:listSelector="@android:color/transparent"
        android:layout_alignParentTop="true"/> 
    
    <ProgressBar
        android:id="@+id/progress"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:layout_centerInParent="true"/> //to make it appear in the middle of screen
    

    现在在你的Activity

    ProgressBar pb;
    pb = (ProgressBar) findViewById(R.id.progress);
    

    现在当任务正在进行时,即联系您的网站时,您可以设置pb.setVisibility(View.VISIBLE);

    只要你的任务完成就设置 pb.setVisibility(View.GONE);

    希望对你有帮助。

    【讨论】:

    • 编辑了我的答案以显示我尝试过的内容。尽管在 android studio 的 xml 设计器图像中看起来不错,但它仍然不可见。
    • 在您的布局中,在ListView 内也添加这一行android:layout_alignParentTop="true"。如果它现在显示,请告诉我。
    • 请发布您的MainActivity 的完整代码。我怀疑您没有在正确的地方使用pb.setVisibility
    • 添加了整个主要活动
    • 现在你只是让它不可见。最初你让它可见,但很快你就让它不可见而不执行你的网络操作。我建议你使用AsynTask来执行您的网络操作,例如联系网站并从那里收集信息。使用AsynTask.AsynTask 实现您的代码让您知道网络操作何时完成,以便您可以完成只有在成功后才需要完成的工作完成网络操作。
    【解决方案2】:

    向您的 XML 添加一个包含一些“正在加载”消息的视图。然后使用ListView.setEmptyView(View view) 方法让ListView 控制该视图。它将一直显示,直到 ListView 填充了项目。

    【讨论】:

    • 试过这个,我认为它会很好用,并添加很多自定义,但我仍然遇到与进度条相同的可见性问题。谢谢
    • 可能是您在 XML 中的 ListView 之前有 ProgressBar。换个顺序试试,ListView可能会覆盖ProgressBar。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多