有人可以告诉我为什么我在Cannot resolve symbol
和on create
方法on start
时遇到mRssFeed
错误?顺便说一句,这只是我的RSS Feed片段类。谢谢。
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FeedFragmentPortrait extends android.support.v4.app.Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.feed_fragment_portrait, container, false);
View rootView = inflater.inflate(R.layout.feed_fragment_portrait, container, false);
mRssFeed = (TextView) rootView.findViewById(R.id.rss_feed);
return rootView;
}
@Override
public void onStart() {
super.onStart();
InputStream in = null;
try {
URL url = new URL("http://www.google.com/feed/main.xml");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
in = conn.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int count; (count = in.read(buffer)) != -1; ) {
out.write(buffer, 0, count);
}
byte[] response = out.toByteArray();
String rssFeed = new String(response, "UTF-8");
mRssFeed.setText(rssFeed);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
答案 0 :(得分:0)
从oncreateView中删除此行
return inflater.inflate(R.layout.feed_fragment_portrait, container, false);
您在初始化mRssFeed之前返回
这就是为什么系统无法知道mRssFeed是什么
修改
此外,您应该在后台任务中执行所有api调用
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
new DownloadInfo().execute("http://example.com/xxx.php");
}
和Asynctask就是这样的
class DownloadInfo extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... url) {
// constants
InputStream in = null;
try {
HttpURLConnection conn = ((HttpURLConnection) new URL(url[0]).openConnection();
in = conn.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int count; (count = in.read(buffer)) != -1; ) {
out.write(buffer, 0, count);
}
byte[] response = out.toByteArray();
return new String(response, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
if (result != null) {
mRssFeed.setText(rssFeed);
}
}