我在我的类(Activity_B)中的这行代码中收到此错误:
BreakingXmlPullParser.getStackSitesFromFile(**Activity_B.this**));
breakingSites = BreakingXmlPullParser.getStackSitesFromFile(
(**Activity_B.this**));
breakingSites = BreakingXmlPullParser.getStackSitesFromFile (Activity_B.this));
这是BreakingXmlPullParser类
public class BreakingXmlPullParser {
static final String KEY_CONTENT = "Content";
static final String KEY_MAINHEADLINE = "MainHeadline";
static final String KEY_SUMMARYHEADLINE = "SummaryHeadline";
static final String KEY_EDITION = "Edition";
static final String KEY_IMAGE_URL = "Image";
static final String KEY_LOGO_URL = "Logo";
static final String KEY_STORY = "Story";
static final String KEY_AUTHOR = "Author";
static final String KEY_PUBLISHDATE = "PublishDate";
public static List<BreakingSite> getStackSitesFromFile(Context ctx) {
// List of StackSites that we will return
List<BreakingSite> breakingSites;
breakingSites = new ArrayList<>();
// temp holder for current BreakingSite while parsing
BreakingSite curBreakingSite = null;
// temp holder for current text value while parsing
String curText = "";
try {
// Get our factory and PullParser
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
// Open up InputStream and Reader of our file.
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.toString() + "/Android/data/"
+ "com.example.agispoc");
StringReader reader = new StringReader(getStringFromFile(dir+"/breakingnews.xml"));
Log.e("Responce", reader.toString());
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(getStringFromFile(dir+"/breakingnews.xml")); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_CONTENT);
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
Element e = (Element) nl.item(i);
curBreakingSite = new BreakingSite();
curBreakingSite.setMainheadline(parser.getValue(e, KEY_MAINHEADLINE));
curBreakingSite.setSummaryheadline(parser.getValue(e, KEY_SUMMARYHEADLINE));
curBreakingSite.setEdition(parser.getValue(e, KEY_EDITION));
curBreakingSite.setImgUrl(parser.getValue(e, KEY_IMAGE_URL));
curBreakingSite.setLogoUrl(parser.getValue(e, KEY_LOGO_URL));
curBreakingSite.setStory(parser.getValue(e, KEY_STORY));
curBreakingSite.setAuthor(parser.getValue(e, KEY_AUTHOR));
curBreakingSite.setPublishdate(parser.getValue(e, KEY_PUBLISHDATE));
breakingSites.add(curBreakingSite);
Log.e("Response", breakingSites.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
// return the populated list.
return breakingSites;
}
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}
public static String getStringFromFile (String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();
return ret;
}
}
这是Activity_B
public class Activity_B extends android.support.v4.app.Fragment {
private InterstitialAd interstitial;
private BreakingSiteAdapter mAdapter;
private ListView sitesList;
private Toolbar mToolbar;
private SwipeRefreshLayout mSwipeRefreshLayout = null;
static final String KEY_CONTENT = "Content";
static final String KEY_MAINHEADLINE = "MainHeadline";
static final String KEY_SUMMARYHEADLINE = "SummaryHeadline";
static final String KEY_EDITION = "Edition";
static final String KEY_IMAGE_URL = "ImgUrl";
static final String KEY_LOGO_URL = "Logo";
static final String KEY_STORY = "Story";
static final String KEY_AUTHOR = "Author";
static final String KEY_PUBLISHDATE = "PublishDate";
List<BreakingSite> breakingSites;
ProgressDialog mProgressDialog;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
private LinearLayout x;
private FragmentActivity fa;
//private Context cm;
private static Context ctx;
//private Context mContext;
@Override
public void onAttach(final Activity Activity_B) {
super.onAttach(Activity_B);
ctx = Activity_B;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
fa = super.getActivity();
// x = (LinearLayout) inflater.inflate(R.layout.b, container, false);
View x = inflater.inflate(R.layout.b,null);
Context context = getActivity();
mSwipeRefreshLayout = (SwipeRefreshLayout)x.findViewById(R.id.swipeRefreshLayout);
mSwipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
new SitesDownloadTask().execute();
}
});
Log.i("StackSites", "OnCreate()");
mProgressDialog = new ProgressDialog(getActivity());
sitesList = (ListView)x.findViewById(R.id.list);
sitesList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int pos,
long id) {
Intent in = new Intent(getContext(),
Bpage1.class);
in.putExtra(KEY_MAINHEADLINE, breakingSites.get(pos).getMainheadline());
in.putExtra(KEY_STORY, breakingSites.get(pos).getStory());
in.putExtra(KEY_LOGO_URL, breakingSites.get(pos).getLogoUrl());
in.putExtra(KEY_IMAGE_URL, breakingSites.get(pos).getImgUrl());
in.putExtra(KEY_AUTHOR, breakingSites.get(pos).getAuthor());
in.putExtra(KEY_PUBLISHDATE, breakingSites.get(pos).getPublishdate());
//in.putExtra(KEY_IMAGE_URL, breakingSites.get(pos).getImgUrl());
startActivity(in);
}
});
if (isNetworkAvailable()) {
Log.i("StackSites", "starting download Task");
SitesDownloadTask download = new SitesDownloadTask();
download.execute();
} else {
mAdapter = new BreakingSiteAdapter(Activity_B.this, -1,
BreakingXmlPullParser.getStackSitesFromFile(Activity_B.this));
sitesList.setAdapter(mAdapter);
}
return x;
}
public void displayInterstitial() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
private boolean isNetworkAvailable() {
ConnectivityManager conManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conManager.getActiveNetworkInfo();
return ( netInfo != null && netInfo.isConnected() );
}
private class SitesDownloadTask extends AsyncTask<Void, Void, Void> {
String xml;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mProgressDialog.setTitle(getString(R.string.app_name));
mProgressDialog.setMessage("Loading...Please wait a moment...");
mProgressDialog.setCancelable(true);
mProgressDialog.setIcon(R.drawable.ic_launcher);
mProgressDialog.show();
mSwipeRefreshLayout.setRefreshing(false);
}
@Override
protected Void doInBackground(Void... arg0) {
BreakingDownloader
.DownloadFromUrl("http://nte.nmh.com.na/MyInfo/Master/Category/breakingnews.xml");
return null;
}
@Override
protected void onPostExecute(Void result) {
// setup our Adapter and set it to the ListView.
mProgressDialog.dismiss();
breakingSites = BreakingXmlPullParser.getStackSitesFromFile(
(Activity_B.this));
breakingSites = BreakingXmlPullParser.getStackSitesFromFile (Activity_B.this));
sitesList.setAdapter(mAdapter);
Log.i("StackSites", "adapter size = " + mAdapter.getCount());
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
// finish();
getActivity().finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
请帮助我。这个应用程序的目的是在fragment中显示listview。我必须将整个活动转换为片段,到目前为止我是片段的新手。 请帮我解决上下文问题。我不明白为什么activity_B片段无法识别BreakingXmpPullParser中的上下文ctx。请不要投票给我。我是新手,只是想在这里学习......
答案 0 :(得分:0)
原因是你的Activity_B扩展了Fragment而不是Activity,只是将getActivity()传递给你的函数而不是Activity_B.this
像这样 BreakingXmlPullParser.getStackSitesFromFile(getActivity()));
只需替换你需要在getActivity()中传递的上下文,而不是Acitivty_B.this,记住Activity_B不再是一个活动,而是一个片段!