Question

I'm trying to make a app, which shows you the latest stock quotes, by downloading and parsing the specific .csv file. However it doesn't run.. here my MainActivity.java:

package com.jdesign.finanzberater;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class MainActivity extends Activity {

EditText setSymbol;
TextView symbolOut;
TextView priceOut;
TextView changePercentageOut;
Button getQuote;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setSymbol = (EditText) findViewById(R.id.setSymbol);
    symbolOut = (TextView) findViewById(R.id.stockSymbolOutput);
    priceOut = (TextView) findViewById(R.id.stockPriceOutput);
    changePercentageOut = (TextView) findViewById(R.id.stockChangePercentageOutput);
    getQuote = (Button) findViewById(R.id.get_quote_button);

    getQuote.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

              URL url;

              try {
                url = new URL("http://download.finance.yahoo.com/d/quotes.csv?s=" + setSymbol.getText() + "&f=sl1p2");

              InputStream stream = url.openStream();

              BufferedInputStream bis = new BufferedInputStream(stream);
              ByteArrayBuffer baf = new ByteArrayBuffer(50);

              int current = 0;
              while ((current = bis.read()) != -1) {
                  baf.append((byte) current);
              }


              String stockTxt = new String(baf.toByteArray());

              String[] tokens = stockTxt.split(",");

              String stockSymbol = tokens[0];
              String stockPrice = tokens[1];
              String stockChangePercentage = tokens[2];


              String fstockSymbol = stockSymbol.substring(1, stockSymbol.length() -1);
              String fstockChangePercentage = stockChangePercentage.substring(1, stockChangePercentage.length() -3);

              symbolOut.setText(fstockSymbol);
              priceOut.setText(stockPrice);
              changePercentageOut.setText(fstockChangePercentage);


              } catch (MalformedURLException e) {


                e.printStackTrace();
            } catch (IOException e) {

                e.printStackTrace();
            } 

        }
    });



}



}

..my activity_main.xml:

<LinearLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<EditText
    android:id="@+id/setSymbol"
    android:layout_width="0dip"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:ems="10"
    android:hint="@string/setSymbol" >

    <requestFocus />
</EditText>

<Button
    android:id="@+id/get_quote_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/get_quote" />

<TextView
    android:id="@+id/stockSymbolOutput"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/stockPriceOutput"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/stockChangePercentageOutput"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />



</LinearLayout>

and my manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jdesign.finanzberater"
    android:versionCode="1"
    android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.jdesign.finanzberater.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

and my LogCat of course:

08-08 12:26:15.745: D/libEGL(24748): loaded /system/lib/egl/libGLES_android.so
08-08 12:26:15.755: D/libEGL(24748): loaded /system/lib/egl/libEGL_adreno200.so
08-08 12:26:15.755: D/libEGL(24748): loaded /system/lib/egl/libGLESv1_CM_adreno200.so
08-08 12:26:15.755: D/libEGL(24748): loaded /system/lib/egl/libGLESv2_adreno200.so
08-08 12:26:15.775: D/memalloc(24748): /dev/pmem: Mapped buffer base:0x52015000   size:26386432 offset:24297472 fd:62
08-08 12:26:15.785: D/OpenGLRenderer(24748): Enabling debug mode 0
08-08 12:26:15.855: D/memalloc(24748): /dev/pmem: Mapped buffer base:0x53d20000 size:13746176 offset:11657216 fd:65

08-08 12:26:16.816: D/memalloc(24748): /dev/pmem: Mapped buffer base:0x54bc3000 size:4177920 offset:2088960 fd:68
08-08 12:26:17.116: W/TextView(24748): GetLabel fail! Do framework orig behavior
08-08 12:26:31.100: D/AndroidRuntime(24748): Shutting down VM
08-08 12:26:31.100: W/dalvikvm(24748): threadid=1: thread exiting with uncaught exception (group=0x40aac228)
08-08 12:26:31.120: E/AndroidRuntime(24748): FATAL EXCEPTION: main
08-08 12:26:31.120: E/AndroidRuntime(24748): android.os.NetworkOnMainThreadException
08-08 12:26:31.120: E/AndroidRuntime(24748):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1178)
08-08 12:26:31.120: E/AndroidRuntime(24748):at java.net.InetAddress.lookupHostByName(InetAddress.java:394)
08-08 12:26:31.120: E/AndroidRuntime(24748):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:245)
08-08 12:26:31.120: E/AndroidRuntime(24748):    at java.net.InetAddress.getAllByName(InetAddress.java:220)
08-08 12:26:31.120: E/AndroidRuntime(24748):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:71)
08-08 12:26:31.120: E/AndroidRuntime(24748):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
08-08 12:26:31.120: E/AndroidRuntime(24748):    at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:351)
08-08 12:26:31.120: E/AndroidRuntime(24748):    at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)
08-08 12:26:31.120: E/AndroidRuntime(24748):    at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
08-08 12:26:31.120: E/AndroidRuntime(24748):    at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
08-08 12:26:31.120: E/AndroidRuntime(24748):    at libcore.net.http.HttpEngine.connect(HttpEngine.java:303)
08-08 12:26:31.120: E/AndroidRuntime(24748):    at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
08-08 12:26:31.120: E/AndroidRuntime(24748):    at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
08-08 12:26:31.120: E/AndroidRuntime(24748):    at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
08-08 12:26:31.120: E/AndroidRuntime(24748):    at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
08-08 12:26:31.120: E/AndroidRuntime(24748):    at java.net.URL.openStream(URL.java:462)
08-08 12:26:31.120: E/AndroidRuntime(24748):    at com.jdesign.finanzberater.MainActivity$1.onClick(MainActivity.java:48)
08-08 12:26:31.120: E/AndroidRuntime(24748):    at android.view.View.performClick(View.java:3549)
08-08 12:26:31.120: E/AndroidRuntime(24748):    at android.view.View$PerformClick.run(View.java:14393)
08-08 12:26:31.120: E/AndroidRuntime(24748):    at android.os.Handler.handleCallback(Handler.java:605)
08-08 12:26:31.120: E/AndroidRuntime(24748):    at android.os.Handler.dispatchMessage(Handler.java:92)
08-08 12:26:31.120: E/AndroidRuntime(24748):    at android.os.Looper.loop(Looper.java:154)
08-08 12:26:31.120: E/AndroidRuntime(24748):    at android.app.ActivityThread.main(ActivityThread.java:4945)
08-08 12:26:31.120: E/AndroidRuntime(24748):    at java.lang.reflect.Method.invokeNative(Native Method)
08-08 12:26:31.120: E/AndroidRuntime(24748):    at java.lang.reflect.Method.invoke(Method.java:511)
08-08 12:26:31.120: E/AndroidRuntime(24748):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
08-08 12:26:31.120: E/AndroidRuntime(24748):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
08-08 12:26:31.120: E/AndroidRuntime(24748):    at dalvik.system.NativeStart.main(Native Method)
08-08 12:26:33.442: D/Process(24748): killProcess, pid=24748
08-08 12:26:33.532: D/Process(24748): dalvik.system.VMStack.getThreadStackTrace(Native Method)
08-08 12:26:33.552: D/Process(24748): java.lang.Thread.getStackTrace(Thread.java:599)
08-08 12:26:33.562: D/Process(24748): android.os.Process.killProcess(Process.java:790)
08-08 12:26:33.562: D/Process(24748): com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:104)
08-08 12:26:33.572: D/Process(24748): java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693)
08-08 12:26:33.602: D/Process(24748): java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690)
08-08 12:26:33.642: D/Process(24748): dalvik.system.NativeStart.main(Native Method)
08-08 12:26:33.653: I/Process(24748): Sending signal. PID: 24748 SIG: 9

It would be very nice if someone would correct my code.
Kind regards,
Julien

Was it helpful?

Solution

The following code should work:

Inside the MainActivity, change the listener and add the method setResult:

getQuote.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View arg0) {
        try {
            List<String> results = new Task().execute(
                    setSymbol.getText().toString()).get();
            setResult(results.get(0), results.get(1), results.get(2));
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
});

private void setResult(String fstockSymbol, String stockPrice, String fstockChangePercentage) {
    symbolOut.setText(fstockSymbol);
    priceOut.setText(stockPrice);
    changePercentageOut.setText(fstockChangePercentage);
}

In addition you have to create an AsyncTask:

class Task extends AsyncTask<String, Void, List<String>> {

    protected List<String> doInBackground(String... symbols) {
        try {
            URL url;

            try {
                url = new URL(
                        "http://download.finance.yahoo.com/d/quotes.csv?s="
                                + symbols[0] + "&f=sl1p2");

                InputStream stream = url.openStream();

                BufferedInputStream bis = new BufferedInputStream(stream);
                ByteArrayBuffer baf = new ByteArrayBuffer(50);

                int current = 0;
                while ((current = bis.read()) != -1) {
                    baf.append((byte) current);
                }

                String stockTxt = new String(baf.toByteArray());

                String[] tokens = stockTxt.split(",");

                String stockSymbol = tokens[0];
                String stockPrice = tokens[1];
                String stockChangePercentage = tokens[2];

                String fstockSymbol = stockSymbol.substring(1,
                        stockSymbol.length() - 1);
                String fstockChangePercentage = stockChangePercentage
                        .substring(1, stockChangePercentage.length() - 3);

                List<String> results = new ArrayList<String>();
                results.add(fstockSymbol);
                results.add(stockPrice);
                results.add(fstockChangePercentage);

                return results;

            } catch (MalformedURLException e) {

                e.printStackTrace();
            } catch (IOException e) {

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

You have to add some error handling.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top