0

On startup, an async class is executed which scrapes a website for information. The screen is left blank during this time, before the gathered information is populated to a listview. Is there any way to add a loading screen during this time?

I looked at this (Add the loading screen in starting of the android application) but I don't think it's what I need because I don't know how long the request will take.

Thanks for your time.

After seeing some of the answers, I revised my code, but neither became visible. here is my xml file for activity main. there is also a textview layout xml file for the default textview element in a listview.

<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>

And here is the main activity's code:

    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);
    }
}
Community
  • 1
  • 1

2 Answers2

2

Add a view to your XML that has some "Loading" message. Then use the ListView.setEmptyView(View view) method to have the ListView control that view. It will be shown until the ListView is populated with items.

Coeffect
  • 8,772
  • 2
  • 27
  • 42
  • Tried this, I think it would work well, and add a lot of customization, but I am stilling having the same visibility issue as the progressbar. Thank you – Adam the Mediocre Sep 03 '14 at 00:11
  • It might be that you have the ProgressBar before the ListView in the XML. Try switching the order, the ListView might be covering the ProgressBar. – Coeffect Sep 04 '14 at 18:29
2

You can add a ProgresBar(circle) in your activity's layout.And in order to set the loading circle right on the middle of the screen you can have your layout something like this.

<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

Now in your Activity

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

Now when the task is in progress i.e when contacting your website, you can set pb.setVisibility(View.VISIBLE);

And as soon as your task is complete just set pb.setVisibility(View.GONE);

Hope it helps.

Sash_KP
  • 5,551
  • 2
  • 25
  • 34
  • Edited my answer to show what I have tried. It stays invisible although looks fine in android studio's xml designer image. – Adam the Mediocre Sep 03 '14 at 00:12
  • In your layout,inside `ListView` add this line too `android:layout_alignParentTop="true"`.And let me know if it's showing now. – Sash_KP Sep 03 '14 at 00:16
  • Please post your `MainActivity`'s full code.I doubt that you are not using `pb.setVisibility` at the right place. – Sash_KP Sep 03 '14 at 00:55
  • added whole main activity – Adam the Mediocre Sep 03 '14 at 01:28
  • Right now you're just making it invisible only.Initially you are making it visible but soon after you're making it invisible without performing your networking operations.I suggest you to use `AsynTask` to perform your networking operations like contacting to a website and gather information from there.Implement your code using `AsynTask`.`AsynTask` lets you know when the networking operations are completed so that you can do your stuffs which are required to be done only after successful completion of networking operations. – Sash_KP Sep 03 '14 at 01:43
  • Thanks, although I dont think that is the issue. I used an AsynTask for the http request, String s = new HTTPRequest().execute("http://www.google.com/finance?q="+sym).get(); But Then I found that I can get the loading icon to show up, just not before the listview does. So, I believe that the asynctask isnt the problem, its actually taking that long to load the graphics to the screen for some reason. Would that make sense? – Adam the Mediocre Sep 03 '14 at 01:46
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/60488/discussion-between-sash-kp-and-adam-the-mediocre). – Sash_KP Sep 03 '14 at 01:56