有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在活动片段内调用方法?

我在片段内部调用方法时遇到问题

方法被调用:public static List<mobAppModel> getmobAppModel(Context ctx)

方法所在的我的活动:

package com.example.eronetmarket;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import com.example.eronetmarket.mobAppModel;


import 安卓.content.Context;


public class XMLsourcePullParser {
    static final String KEY_APP_INFO = "appInfo";
    static final String KEY_ID = "id";
    static final String KEY_CATEGORY = "category";
    static final String KEY_ICON_URL = "iconUrl";
    static final String KEY_APP_HEADLINE = "appHeadline";
    static final String KEY_APP_DESC = "appDesc";
    static final String KEY_RATING_POINTS = "ratingPoints";
    static final String KEY_PLATFORM = "platform";
    static final String KEY_STORE_URL = "storeUrl";
    static final String KEY_STORE_PRICE = "storePrice";
    static final String KEY_DEVELOPER = "developer";

    public static List<mobAppModel> getmobAppModel(Context ctx) {

        // List of StackSites that we will return
        List<mobAppModel> appModels;
        appModels = new ArrayList<mobAppModel>();

        // temp holder for current StackSite while parsing
        mobAppModel curmobAppModel = null;
        // temp holder for current text value while parsing
        String curText = "";

        try {
            // Get our factory and PullParser
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser xpp = factory.newPullParser();

            // Open up InputStream and Reader of our file.
            FileInputStream fis = ctx.openFileInput("XMLsource.xml");
            BufferedReader reader = new BufferedReader(new InputStreamReader(fis));

            // point the parser to our file.
            xpp.setInput(reader);

            // get initial eventType
            int eventType = xpp.getEventType();

            // Loop through pull events until we reach END_DOCUMENT
            while (eventType != XmlPullParser.END_DOCUMENT) {
                // Get the current tag
                String tagname = xpp.getName();

                // React to different event types appropriately
                switch (eventType) {
                case XmlPullParser.START_TAG:
                    if (tagname.equalsIgnoreCase(KEY_APP_INFO)) {
                        // If we are starting a new <site> block we need
                        //a new StackSite object to represent it
                        curmobAppModel = new mobAppModel();
                    }
                    break;

                case XmlPullParser.TEXT:
                    //grab the current text so we can use it in END_TAG event
                    curText = xpp.getText();
                    break;

                case XmlPullParser.END_TAG:
                    if (tagname.equalsIgnoreCase(KEY_APP_INFO)) {
                        // if </appInfo> then we are done with current app
                        // add it to the list.
                        appModels.add(curmobAppModel);
                    } else if (tagname.equalsIgnoreCase(KEY_ID)) {

                        curmobAppModel.setid(curText);
                    } else if (tagname.equalsIgnoreCase(KEY_CATEGORY)) {

                        curmobAppModel.setcategory(curText);
                    } else if (tagname.equalsIgnoreCase(KEY_ICON_URL)) {

                        curmobAppModel.seticonUrl(curText);
                    } else if (tagname.equalsIgnoreCase(KEY_APP_HEADLINE)) {

                        curmobAppModel.setappHeadline(curText);

                    }
                    else if (tagname.equalsIgnoreCase(KEY_APP_DESC)) {

                        curmobAppModel.setappDesc(curText);

                    }
                    else if (tagname.equalsIgnoreCase(KEY_RATING_POINTS)) {

                        curmobAppModel.setratingPoints(curText);

                    }
                    else if (tagname.equalsIgnoreCase(KEY_PLATFORM)) {

                        curmobAppModel.setplatform(curText);

                    }
                    else if (tagname.equalsIgnoreCase(KEY_STORE_URL)) {

                        curmobAppModel.setstoreURL(curText);
                    }
                    else if (tagname.equalsIgnoreCase(KEY_STORE_PRICE)) {

                        curmobAppModel.setstorePrice(curText);
                    }
                    else if (tagname.equalsIgnoreCase(KEY_DEVELOPER)) {

                        curmobAppModel.setdeveloper(curText);
                    }
                    break;

                default:
                    break;
                }
                //move on to next iteration
                eventType = xpp.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // return the populated list.
        return appModels;
    }
}`

这是我的片段:

package com.example.eronetmarket;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import 安卓.app.Activity;
import 安卓.content.Context;
import 安卓.content.Intent;
import 安卓.net.ConnectivityManager;
import 安卓.net.NetworkInfo;
import 安卓.net.Uri;
import 安卓.os.AsyncTask;
import 安卓.os.Bundle;
import 安卓.support.v4.app.Fragment;
import 安卓.support.v4.app.FragmentActivity;
import 安卓.support.v4.app.FragmentManager;
import 安卓.support.v4.app.FragmentPagerAdapter;
import 安卓.util.Log;
import 安卓.view.LayoutInflater;
import 安卓.view.View;
import 安卓.view.ViewGroup;
import 安卓.widget.AdapterView;
import 安卓.widget.AdapterView.OnItemClickListener;
import 安卓.widget.LinearLayout;
import 安卓.widget.ListView;

public class Preporuceno extends Fragment   {



    private AppAdapter mAdapter;
    private ListView siteList;

    private LinearLayout ll;
    private FragmentActivity fa;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    fa = super.getActivity();
    ll = (LinearLayout) inflater.inflate(R.layout.activity_preporuceno, container, false);

        siteList = (ListView) getActivity().findViewById(R.id.listView1);

        siteList.setOnItemClickListener(new OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> parent, View v, int pos,long id) {
                String url = mAdapter.getItem(pos).getstoreURL();
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(url));
                startActivity(i);

            }
        });



        if(isNetworkAvailable()){
            Log.i("mobAppModel", "starting download Task");
            AppDownloadTask download = new AppDownloadTask();
            download.execute();
        }else{
            mAdapter = new AppAdapter(getActivity().getApplicationContext(), -1, XMLsourcePullParser.getmobAppModel(Preporuceno.this));
            siteList.setAdapter(mAdapter);
        }

        return ll;}
    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager 
              = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    } 
    private class AppDownloadTask extends AsyncTask<Void, Void, Void>{
        @Override
        protected Void doInBackground(Void... arg0) {
            //Download the file
            try {
                Downloader.DownloadFromUrl("http://minores.info/joomla30/stacksites.xml", getActivity().openFileOutput("XMLsource.xml", Context.MODE_PRIVATE));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            return null;
        }
        @Override
        protected void onPostExecute(Void result){
            //setup our Adapter and set it to the ListView.
            mAdapter = new AppAdapter(Preporuceno.this, -1, XMLsourcePullParser.getmobAppModel(Preporuceno.this));
            siteList.setAdapter(mAdapter);
            Log.i("mobAppModel", "adapter size = "+ mAdapter.getCount());
        }
    }

    }

我在

XMLsourcePullParser.getmobAppModel(Preporuceno.this)

The method getmobAppModel(Context) in the type XMLsourcePullParser is not applicable for the arguments (Preporuceno)

我完全糊涂了:\ 作为一项活动,效果很好,但作为碎片,这就是问题所在


共 (2) 个答案

  1. # 1 楼答案

    使用以下内容从片段中获取上下文:

    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        myContext=activity;
    }
    

    然后像这样使用你的方法:

    XMLsourcePullParser.getmobAppModel(myContext)
    
  2. # 2 楼答案

    Fragment不扩展上下文,因为他的上下文是活动所在的,所以应该调用getmobAppModel(getActivity())