我正在用android studio編寫rssfeed我正在使用模擬器。我的代碼編譯並啓動,但除了頂部的標題MyRssFeed之外,它不顯示任何內容。有什麼我失蹤?Android Studio RssFeed
類:
package jrodriguez.myrssfeed;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by Jennifer Rodriguez on 3/8/2016.
*/
public class MainActivity extends AppCompatActivity {
private TextView src;
protected void OnCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
setContentView(R.layout.activity_main);
src = (TextView) findViewById(R.id.text);
}
public void fetch(View v) {
Downloader d = new Downloader();
d.execute("https://en.wikipedia.org/wiki/Main_Page");
try {
src.setText(d.get());
} catch (Exception e) {
Log.e("Error to thread", e.toString());
}
}
class Downloader extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String result = null;
try {
URL url = new URL(urls[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
result = result + line;
}
conn.disconnect();
reader.close();
} catch (Exception e) {
Log.e("error to fetching", e.toString());
}
return result;
}
}
XML文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res
/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/text"
android:enabled="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/Fetch"
android:id="@+id/Fetch"
android:enabled="true"
android:clickable="true" />
</LinearLayout>
清單
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="jrodriguez.myrssfeed">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-permissions android:name="android.permission.INTERNET" />
</application>
</manifest>
實現Button的clickListener。然後只有你的fetch()會工作。 –
在按鈕標籤android:onClick =「fetch」中添加此行。實際上你獲取(View v)函數沒有執行。嘗試這可能它顯示你想要的 –
我的按鈕不顯示,當它啓動 – Jennifer