Search code examples
javaandroidandroid-fragmentsandroid-listfragment

I am getting an error"getStackSitesFromFile(android.content.Context) in BreakingXmlpullparser cannot be applied to Activity_B"


I am getting this error in this line of code in my class(Activity_B):

 BreakingXmlPullParser.getStackSitesFromFile(**Activity_B.this**));

 breakingSites = BreakingXmlPullParser.getStackSitesFromFile(
              (**Activity_B.this**));
breakingSites = BreakingXmlPullParser.getStackSitesFromFile (Activity_B.this));

Here is the BreakingXmlPullParser Class

    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;
    }

}

And here is 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);
    }

}

Please assist me.The aim of this appliaction is to display the listview inside fragment.I had to convert an entire activity into a fragment,and so far i am new to fragments. Please help me solve the context issue.I dont understand why the activity_B fragment cannot recognize the context ctx in BreakingXmpPullParser.Please dont vote me down.I am new and just trying to learn here...

error screenshot

Error screenshot2


Solution

  • The reason is your Activity_B extends Fragment and not Activity, just pass getActivity() to your function instead of Activity_B.this

    like this

    BreakingXmlPullParser.getStackSitesFromFile(getActivity()));

    just replace wherever you need context you pass in getActivity() and not Acitivty_B.this remember Activity_B is not an activity anymore but a fragment !