0
我在此Android應用程序中遇到問題。當我按下button_x時,它總是崩潰。該程序列在下面。我使用BufferedReader從互聯網上閱讀內容。從URL中讀取內容導致Android應用程序崩潰
public class MainActivity extends Activity {
Button button_x;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_x = (Button)findViewById(R.id.button_x);
button_x.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
URL yahoo = null;
try {
yahoo = new URL("http://www.google.com.tw/");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader in = null;
try {
in = new BufferedReader(
new InputStreamReader(
yahoo.openStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String inputLine;
try {
while ((inputLine = in.readLine()) != null)
button_x.setBackgroundColor(Color.RED);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
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.main, menu);
return true;
}
}
我以爲是Internet權限引起的,所以我想補充的清單文件中的Internet權限。
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<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.example.euro.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 please! – Nerd
請搜索你的異常(我懷疑是NetworkOnMainThreadException) - 你會發現幾百個問題和答案。 – ianhanniballake