0

我正在尝试通过下载和解析特定的 .csv 文件来制作一个向您显示最新股票报价的应用程序。但是它没有运行..这里是我的 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();
            } 

        }
    });



}



}

..我的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>

和我的清单:

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

当然还有我的 LogCat:

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

如果有人能更正我的代码,那就太好了。
亲切的问候,
朱利安

4

1 回答 1

1

以下代码应该可以工作:

在 MainActivity 中,更改侦听器并添加方法 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);
}

此外,您必须创建一个 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;
        }
    }
}

您必须添加一些错误处理。

于 2013-08-08T11:41:45.253 回答