나는 yahoo에서 주식 데이터를 다운로드하는 응용 프로그램을 만들고 있습니다! 표시합니다.안드로이드 다운로드 .csv 파일이 오류를 제공합니다
MainActivity.java :
package frank.com.myapplication;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.apache.http.util.ByteArrayBuffer;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends ActionBarActivity {
TextView symbolOut;
TextView priceOut;
TextView changePrecentageOut;
Button getQuote;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
symbolOut = (TextView) findViewById(R.id.stockSymbolOutput);
priceOut = (TextView) findViewById(R.id.stockPriceOutput);
changePrecentageOut = (TextView) findViewById(R.id.stockChangePercentageOutput);
getQuote = (Button) findViewById(R.id.get_quote_button);
getQuote.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
URL url;
try {
url = new URL("http://download.finance.yahoo.com/d/quotes.csv?s=goog&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);
changePrecentageOut.setText(fstockChangePercentage);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
의 AndroidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".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>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
이
내 코드입니다 0activity_main.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">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Get Quote"
android:id="@+id/get_quote_button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/stockSymbolOutput"
android:layout_below="@+id/get_quote_button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/stockPriceOutput"
android:layout_below="@+id/stockSymbolOutput"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/stockChangePercentageOutput"
android:layout_below="@+id/stockPriceOutput"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
내가 그것을 다음과 같은 오류가 있습니다 내 응용 프로그램에서 버튼을 클릭 해보십시오
01-18 15:20:23.959 1532-1532/frank.com.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: frank.com.myapplication, PID: 1532
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:323)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:190)
at java.net.URL.openStream(URL.java:470)
at frank.com.myapplication.MainActivity$1.onClick(MainActivity.java:48)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
어떤 도움을 주시면 감사하겠습니다, 내가했습니다를 꽤 오래 동안 이걸 붙잡 혔어.
확실한 중복 (http://stackoverflow.com/ : 응용 프로그램의 응답이 링크를 확인에 대한 http://developer.android.com/reference/android/os/AsyncTask.html
이 더 많은 것을 알고 질문/6343166/android-os-networkonmainthreadexception). 질문자가 관련 예외를 찾지 않고이 예외를 검색하는 동안 StackOverflow를 발견 한 것은 놀라운 일입니다. – 323go
작업을 수행하기 위해 AsyncTask를 시도하거나 새 스레드를 생성하십시오. 왜 대답은 downvoted 모르겠어요. – ZakiMak