Android AsyncTask和setAdapter帮助

时间:2011-06-24 23:09:33

标签: android android-activity android-asynctask adapter

我正在尝试获取解析xml的AsyncTask并创建对象的arraylist以将对象的arraylist传递给setAdapter,以便向用户显示一个库。

然而,我得到了这个:

06-24 15:24:07.972: ERROR/AndroidRuntime(4402): FATAL EXCEPTION: main
06-24 15:24:07.972: ERROR/AndroidRuntime(4402): java.lang.IllegalStateException: System services not available to Activities before onCreate()
06-24 15:24:07.972: ERROR/AndroidRuntime(4402):     at android.app.Activity.getSystemService(Activity.java:3886)
06-24 15:24:07.972: ERROR/AndroidRuntime(4402):     at android.gallery.ImageAdapter.<init>(ImageAdapter.java:41)
06-24 15:24:07.972: ERROR/AndroidRuntime(4402):     at android.gallery.GalleryActivity$ParseXML.onPostExecute(GalleryActivity.java:150)
06-24 15:24:07.972: ERROR/AndroidRuntime(4402):     at android.gallery.GalleryActivity$ParseXML.onPostExecute(GalleryActivity.java:1)
06-24 15:24:07.972: ERROR/AndroidRuntime(4402):     at android.os.AsyncTask.finish(AsyncTask.java:590)
06-24 15:24:07.972: ERROR/AndroidRuntime(4402):     at android.os.AsyncTask.access$600(AsyncTask.java:149)
06-24 15:24:07.972: ERROR/AndroidRuntime(4402):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:603)
06-24 15:24:07.972: ERROR/AndroidRuntime(4402):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-24 15:24:07.972: ERROR/AndroidRuntime(4402):     at android.os.Looper.loop(Looper.java:132)
06-24 15:24:07.972: ERROR/AndroidRuntime(4402):     at android.app.ActivityThread.main(ActivityThread.java:4025)
06-24 15:24:07.972: ERROR/AndroidRuntime(4402):     at java.lang.reflect.Method.invokeNative(Native Method)
06-24 15:24:07.972: ERROR/AndroidRuntime(4402):     at java.lang.reflect.Method.invoke(Method.java:491)
06-24 15:24:07.972: ERROR/AndroidRuntime(4402):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
06-24 15:24:07.972: ERROR/AndroidRuntime(4402):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
06-24 15:24:07.972: ERROR/AndroidRuntime(4402):     at dalvik.system.NativeStart.main(Native Method)

我在GalleryActivity中遗漏了解析部分 ImageAdapter中的第41行:inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

GalleryActivity中的第150行:galleryView.setAdapter(new ImageAdapter(new GalleryActivity(), listOfDish));

GalleryActivity.java

public class GalleryActivity extends Activity 
{
    private  Gallery galleryView;
    private ArrayList<Dish >listOfDish;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ParseXML p = new ParseXML();
        p.execute();

        galleryView = (Gallery)findViewById(R.id.galleryid);

        galleryView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView parent, View v, int position, long id) {
                Toast.makeText(GalleryActivity.this, "" + position, Toast.LENGTH_SHORT).show();
            }
        });   
    }

    private class ParseXML extends AsyncTask<String, Void, ArrayList<Dish>>
    {
        protected ArrayList<Dish> doInBackground(String... arg0) 
        {
                listOfDish = new ArrayList<Dish>();

                    ...parse xml (this works)

                listOfDish.add(dish);
            }

            return listOfDish;  
        }

        @Override
        protected void onPostExecute(ArrayList<Dish> result)
        {
            galleryView.setAdapter(new ImageAdapter(new GalleryActivity(), listOfDish));
        }
    }

    public static String getElement(Element a, String name)
    {
        NodeList elementList = a.getElementsByTagName(name);
        Element b = (Element)elementList.item(0);

        if (b != null)
        {
            NodeList list = b.getChildNodes();
            System.out.println(name + ": " + ((Node)list.item(0)).getNodeValue().trim() );
            return ((Node)list.item(0)).getNodeValue().trim();
        }

        return null;
    }

    public static String getXML(int num){    
        String line = null;

        try 
        {   
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet("http://reddit.com/.xml");

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            line = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            line = "<results status=\"error\"><msg>Can't connect to server1</msg></results>";
        } catch (MalformedURLException e) {
            line = "<results status=\"error\"><msg>Can't connect to server2</msg></results>";
        } catch (IOException e) {
            line = "<results status=\"error\"><msg>Can't connect to server3</msg></results>";
        }

        return line;

    }

    public final static Document XMLfromString(String xml){

        Document doc = null;

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {

            DocumentBuilder db = dbf.newDocumentBuilder();

            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            doc = db.parse(is); 

        } catch (ParserConfigurationException e) {
            System.out.println("XML parse error: " + e.getMessage());
            return null;
        } catch (SAXException e) {
            System.out.println("Wrong XML file structure: " + e.getMessage());
            return null;
        } catch (IOException e) {
            System.out.println("I/O exeption: " + e.getMessage());
            return null;
        }

        return doc;

    }
}

ImageAdapter

public class ImageAdapter extends BaseAdapter {

    private Activity activity;
    private static LayoutInflater inflater = null;
    private ArrayList<Dish> listOfDish;
    private int[] data;
    private String[] name;

    public ImageAdapter(Activity a, ArrayList<Dish> listOfDish) {
        activity = a;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.listOfDish = listOfDish;
        data = new int[listOfDish.size()];
        name = new String[listOfDish.size()];

        for (int i = 0; i < data.length; i++)
        {
            data[i] = R.drawable.sample_0;
            name[i] = "test";
        }
    }

    public int getCount() {
        return data.length;
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public static class ViewHolder{
        public TextView text, dssnum;
        public ImageView image;
    }

    public View getView(int position, View convertView, ViewGroup parent) 
    {
        View vi = convertView;
        ViewHolder holder;

        if (convertView == null)
        {
            vi = inflater.inflate(R.layout.caption, null);
            holder = new ViewHolder();
            holder.text = (TextView) vi.findViewById(R.id.textView1);
            holder.dssnum = (TextView) vi.findViewById(R.id.dss_num);
            holder.image = (ImageView) vi.findViewById(R.id.image);
            vi.setTag(holder);
        }
        else
            holder = (ViewHolder) vi.getTag();

        holder.text.setText(name[position]);
        holder.dssnum.setText("DSS " + listOfDish.get(position).getSubsystems().get(0).getDSSNum());

        final int stub_id = data[position];
        holder.image.setImageResource(stub_id);

        return vi;
    }
}

2 个答案:

答案 0 :(得分:4)

请勿使用activity.getSystemService(...)来传递GalleryActivity的上下文...

onPostExecute(...)执行此操作...

@Override
protected void onPostExecute(ArrayList<Dish> result)
{
    galleryView.setAdapter(new ImageAdapter(GalleryActivity.this, listOfDish));
}

...并将ImageAdapter更改为...

public ImageAdapter(Context context, ArrayList<Dish> listOfDish) {
    inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

答案 1 :(得分:0)

可能是竞争条件,AsyncTask在onCreate()之前完成。尝试使用android.os.Handler安排ParseXML.execute()。例如,而不是......

ParseXML p = new ParseXML();
p.execute();

...尝试...

new Handler().post(new Runnable() {
    public void run() {
        ParseXML p = new ParseXML();
        p.execute();
    }
});

Dunno肯定是否有用,但它值得一试。