2015-01-18 3 views
-2

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

내 코드입니다 0

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

어떤 도움을 주시면 감사하겠습니다, 내가했습니다를 꽤 오래 동안 이걸 붙잡 혔어.

+1

확실한 중복 (http://stackoverflow.com/ : 응용 프로그램의 응답이 링크를 확인에 대한 http://developer.android.com/reference/android/os/AsyncTask.html

이 더 많은 것을 알고 질문/6343166/android-os-networkonmainthreadexception). 질문자가 관련 예외를 찾지 않고이 예외를 검색하는 동안 StackOverflow를 발견 한 것은 놀라운 일입니다. – 323go

+0

작업을 수행하기 위해 AsyncTask를 시도하거나 새 스레드를 생성하십시오. 왜 대답은 downvoted 모르겠어요. – ZakiMak

답변

-1

안드로이드의 UI/메인 스레드에서 다운로드 중입니다 (네트워크 작동 중). 이는 UI가 중단되게하므로 허용되지 않습니다. 따라서 Android는 사용자가이 작업을 수행하도록 허용하지 않습니다.

당신은 여기 그것에 대해 세부 사항을 발견 할 것이다 : 여기에 응용 프로그램의 응답에 대한 NetworkOnMainThreadException

당신이 알아야 할 것입니다 : 앱이 잠재적으로 긴 작업을 수행하는 어떤 상황에서

, 당신이해야 UI 스레드에서 작업을 수행하지 말고 대신 작업자 스레드를 만들고 거기에서 대부분의 작업을 수행하십시오.

다운로드 또는 네트워크 연결과 같이 오래 실행되는 작업이있는 경우 새 스레드에서 수행해야합니다. 이를 수행하는 적절한 방법은 AsyncTask에 코드를 구현하는 것입니다.

확인 여기 문서 : [android.os.NetworkOnMainThreadException]의 Keeping Your App Responsive

관련 문제