0

我整天都在尝试整理这个类文件,但遇到了更多问题。我相信这个类文件设置完全错误。我认为 AsyncTask 是不正确的,我也相信我的 onCreateView 也是如此。我想要做的是从互联网上下载一个 XML 文件并将信息放入 ListView 使用的区域。我已经让它工作了,但我决定将它更改为片段使用,这就是问题出现的时候,因为显然你不能将相同的东西用于活动作为片段。这是我的类文件,因为我不明白我在 AsyncTask 方面出了什么问题,特别是我可以得到一些帮助。谢谢你的协助!

错误:AsyncTask 上的解析器无法解析符号,并且 xml 字符串对于我想要使用的内容不正确。我现在真的迷路了。

CustomizedListView.class

public class CustomizedListView extends Fragment {
// All static variables
static final String URL = "http://api.androidhive.info/music/music.xml";
// XML node keys
static final String KEY_SONG = "song"; // parent node
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_ARTIST = "artist";
static final String KEY_DURATION = "duration";
static final String KEY_THUMB_URL = "thumb_url";

ListView list;
LazyAdapter adapter;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    final View v = inflater.inflate(R.layout.list_row, container, false);
    list = (ListView) v.findViewById(R.id.game_list);
    return v;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
    new TheTask().execute();
    XMLParser parser = new XMLParser();
    String xml = parser.getXmlFromUrl(URL); // getting XML from URL
    Document doc = parser.getDomElement(xml); // getting DOM element

    NodeList nl = doc.getElementsByTagName(KEY_SONG);
    // looping through all song nodes <song>
    for (int i = 0; i < nl.getLength(); i++) {
        // creating new HashMap
        HashMap<String, String> map = new HashMap<String, String>();
        Element e = (Element) nl.item(i);
        // adding each child node to HashMap key => value
        map.put(KEY_ID, parser.getValue(e, KEY_ID));
        map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
        map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
        map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
        map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));

        // adding HashList to ArrayList
        songsList.add(map);
    }




    // Getting adapter by passing xml data ArrayList
    adapter=new LazyAdapter(getActivity(), songsList);
    list.setAdapter(adapter);


    // Click event for single list row
    list.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {


        }
    });
}
}
class TheTask extends AsyncTask<Void,Void,Void> {
static final String URL = "http://api.androidhive.info/music/music.xml";
static final String xml = xml;


@Override
protected void onPreExecute() {
    // TODO Auto-generated method stub
    super.onPreExecute();
}

@Override
protected void onPostExecute(Void result) {
    // TODO Auto-generated method stub
    super.onPostExecute(result);
}

@Override
protected Void doInBackground(Void... params) {
    // TODO Auto-generated method stub
    String xml = parser.getXmlFromUrl(URL);
    return null;
}

}

代码更改后的 Logcat 错误:

07-20 20:48:18.941  22942-22942/com.example.app E/AndroidRuntime: FATAL EXCEPTION: main
    java.lang.NullPointerException
    at com.example.app.CustomizedListView.onCreate(CustomizedListView.java:52)
    at android.support.v4.app.Fragment.performCreate(Fragment.java:1437)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:877)
    at android.support.v4.app.FragmentManagerImpl.performPendingDeferredStart(FragmentManager.java:807)
    at android.support.v4.app.Fragment.setUserVisibleHint(Fragment.java:801)
    at android.support.v4.app.FragmentPagerAdapter.setPrimaryItem(FragmentPagerAdapter.java:130)
    at android.support.v4.view.ViewPager.populate(ViewPager.java:1062)
    at android.support.v4.view.ViewPager.populate(ViewPager.java:911)
    at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1432)
    at android.view.View.measure(View.java:15525)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at android.view.View.measure(View.java:15525)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:847)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
    at android.view.View.measure(View.java:15525)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2434)
    at android.view.View.measure(View.java:15525)
    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1874)
    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1089)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1265)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
    at android.view.Choreographer.doCallbacks(Choreographer.java:562)
    at android.view.Choreographer.doFrame(Choreographer.java:532)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
    at android.os.Handler.handleCallback(Handler.java:725)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:5227)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
    at dalvik.system.NativeStart.main(Native Method)
4

1 回答 1

0

你做的完全错了..我建议去阅读一下Multi Threaded ProgrammingAsynchronous Tasks这对你有很大帮助..

你的代码有很多问题,我修复了很多东西,但我会提到最重要的和我真正记得的:p

  1. 如果您想使用全局定义的变量,那么您的AsyncTask类应该在您的类中定义Activity您的情况下,它是在外部定义的
  2. 当您执行 aAsyncTask时,它会创建一个新线程,并且新后台线程中的命令独立于UI线程运行。我的观点是,许多人认为UI线程会停止以使Background线程完成工作。这是错误的,也是程序员中的常见问题。
  3. 你真的很讨厌缩进。不是吗?当阅读糟糕的缩进代码时,它会使其他程序员发疯,从而导致您的问题仍未得到解答。

这是固定代码:

public class CustomizedListView extends Fragment {
    // All static variables
    static final String URL = "http://api.androidhive.info/music/music.xml";
    // XML node keys
    static final String KEY_SONG = "song"; // parent node
    static final String KEY_ID = "id";
    static final String KEY_TITLE = "title";
    static final String KEY_ARTIST = "artist";
    static final String KEY_DURATION = "duration";
    static final String KEY_THUMB_URL = "thumb_url";


    ListView list;
    ArrayList<HashMap<String, String>> songsList;
    View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        final View v = inflater.inflate(R.layout.list_row, container, false);
        list = (ListView) v.findViewById(R.id.game_list);
        view = v;
        return v;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TheTask().execute();

        // Click event for single list row
        list.setOnItemClickListener(new OnItemClickListener() {


            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                // TODO Auto-generated method stub

            }
        });
    }

    class TheTask extends AsyncTask<Void, Void, Void> {

        static final String URL = "http://api.androidhive.info/music/music.xml";

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... params) {
            XMLParser parser = new XMLParser();
            String xml = parser.getXmlFromUrl(URL); // getting XML from URL
            songsList = new ArrayList<HashMap<String, String>>();
            Document doc = parser.getDomElement(xml); // getting DOM element

            NodeList nl = doc.getElementsByTagName(KEY_SONG);
            // looping through all song nodes <song>
            for (int i = 0; i < nl.getLength(); i++) {
                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();
                Element e = (Element) nl.item(i);
                // adding each child node to HashMap key => value
                map.put(KEY_ID, parser.getValue(e, KEY_ID));
                map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
                map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
                map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
                map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));

                // adding HashList to ArrayList
                songsList.add(map);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // Getting adapter by passing xml data ArrayList
            LazyAdapter adapter = new LazyAdapter(getActivity(), songsList);
            ((ListView) view.findViewById(R.id.game_list)).setAdapter(adapter);
            super.onPostExecute(result);
        }
    }
}
于 2013-07-20T19:41:15.393 回答