Java Android异步任务片段加载

Java Android异步任务片段加载,java,android,json,android-fragments,android-asynctask,Java,Android,Json,Android Fragments,Android Asynctask,我试图在Android片段中创建一个JSON填充的listview。应用程序在AsyncTask区域崩溃,但我不确定问题出在哪里。我试图按照使用活动的原始教程进行操作,但我将其转换为一个片段:;如果需要的话,我很乐意发布整个片段代码。如果你需要更多信息,请告诉我 片段作为一个整体: public class mainViewController extends ListFragment { Context context; // Progress Dialog

我试图在Android片段中创建一个JSON填充的listview。应用程序在AsyncTask区域崩溃,但我不确定问题出在哪里。我试图按照使用活动的原始教程进行操作,但我将其转换为一个片段:;如果需要的话,我很乐意发布整个片段代码。如果你需要更多信息,请告诉我

片段作为一个整体:

public class mainViewController extends ListFragment
{

    Context context;

    // Progress Dialog
        private ProgressDialog pDialog;

        // testing on Emulator:
        private static final String READ_COMMENTS_URL = "https://MY_URL";


        // JSON IDS:
        @SuppressWarnings("unused")
        private static final String TAG_SUCCESS = "success";
        private static final String TAG_TITLE = "title";
        private static final String TAG_POSTS = "posts";
        @SuppressWarnings("unused")
        private static final String TAG_POST_ID = "post_id";
        private static final String TAG_USERNAME = "username";
        private static final String TAG_MESSAGE = "message";
        // it's important to note that the message is both in the parent branch of
        // our JSON tree that displays a "Post Available" or a "No Post Available"
        // message,
        // and there is also a message for each individual post, listed under the
        // "posts"
        // category, that displays what the user typed as their message.

        // An array of all of our comments
        private JSONArray mComments = null;
        // manages all of our comments in a list.
        private ArrayList<HashMap<String, String>> mCommentList;

    public mainViewController()
    {
    }

    String[] mainFeed = {};

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

//       // TODO Auto-generated method stub
//          ArrayAdapter<String> adapter = new ArrayAdapter<String>(
//                  inflater.getContext(), android.R.layout.simple_list_item_1,
//                  mainFeed);
//
//          setListAdapter(adapter);


         return super.onCreateView(inflater, container, savedInstanceState);
     }

        @Override
        public void onResume() {
            // TODO Auto-generated method stub
            super.onResume();
            // loading the comments via AsyncTask
            new LoadComments().execute();
        }

        public void addComment(View v) {
//          Intent i = new Intent(ReadComments.this, AddComment.class);
//          startActivity(i);
        }

        /**
         * Retrieves recent post data from the server.
         */
        public void updateJSONdata() {

            // Instantiate the arraylist to contain all the JSON data.
            // we are going to use a bunch of key-value pairs, referring
            // to the json element name, and the content, for example,
            // message it the tag, and "I'm awesome" as the content..

            mCommentList = new ArrayList<HashMap<String, String>>();

            // Bro, it's time to power up the J parser
            JSONParser jParser = new JSONParser();
            // Feed the beast our comments url, and it spits us
            // back a JSON object. Boo-yeah Jerome.
            JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);

            // when parsing JSON stuff, we should probably
            // try to catch any exceptions:
            try {

                // I know I said we would check if "Posts were Avail." (success==1)
                // before we tried to read the individual posts, but I lied...
                // mComments will tell us how many "posts" or comments are
                // available
                mComments = json.getJSONArray(TAG_POSTS);

                // looping through all posts according to the json object returned
                for (int i = 0; i < mComments.length(); i++) {
                    JSONObject c = mComments.getJSONObject(i);

                    // gets the content of each tag
                    String title = c.getString(TAG_TITLE);
                    String content = c.getString(TAG_MESSAGE);
                    String username = c.getString(TAG_USERNAME);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    map.put(TAG_TITLE, title);
                    map.put(TAG_MESSAGE, content);
                    map.put(TAG_USERNAME, username);

                    // adding HashList to ArrayList
                    mCommentList.add(map);

                    // annndddd, our JSON data is up to date same with our array
                    // list
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        /**
         * Inserts the parsed data into the listview.
         */
        private void updateList() {
            // For a ListActivity we need to set the List Adapter, and in order to do
            //that, we need to create a ListAdapter.  This SimpleAdapter,
            //will utilize our updated Hashmapped ArrayList, 
            //use our single_post xml template for each item in our list,
            //and place the appropriate info from the list to the
            //correct GUI id.  Order is important here.
            ListAdapter adapter = new SimpleAdapter(this.context, mCommentList,
                    R.layout.single_post, new String[] { TAG_TITLE, TAG_MESSAGE,
                            TAG_USERNAME }, new int[] { R.id.title, R.id.message,
                            R.id.username });

            // I shouldn't have to comment on this one:
            setListAdapter(adapter);

            // Optional: when the user clicks a list item we 
            //could do something.  However, we will choose
            //to do nothing...
            ListView lv = getListView();    
            lv.setOnItemClickListener(new OnItemClickListener() {

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

                    // This method is triggered if an item is click within our
                    // list. For our example we won't be using this, but
                    // it is useful to know in real life applications.

                }
            });
        }


        public class LoadComments extends AsyncTask<Void, Void, Boolean> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
//              pDialog = new ProgressDialog(mainViewController.this);
//              pDialog.setMessage("Loading Posts...");
//              pDialog.setIndeterminate(false);
//              pDialog.setCancelable(true);
//              pDialog.show();
            }

            @Override
            protected Boolean doInBackground(Void... arg0) {
                updateJSONdata();
                return null;

            }

            @Override
            protected void onPostExecute(Boolean result) {
                super.onPostExecute(result);
                //pDialog.dismiss();
                updateList();
            }
        }

     @Override
        public void onListItemClick(ListView l, View v, int position, long id) 
        {
            // TODO Auto-generated method stub
            super.onListItemClick(l, v, position, id);
        }
}
public类mainViewController扩展ListFragment
{
语境;
//进度对话框
私人对话;
//在模拟器上测试:
私有静态最终字符串读取\u注释\u URL=”https://MY_URL";
//JSON ID:
@抑制警告(“未使用”)
私有静态最终字符串标记_SUCCESS=“SUCCESS”;
私有静态最终字符串标记_TITLE=“TITLE”;
私有静态最终字符串标记_POSTS=“POSTS”;
@抑制警告(“未使用”)
私有静态最终字符串标记\u POST\u ID=“POST\u ID”;
私有静态最终字符串标记\u USERNAME=“USERNAME”;
私有静态最终字符串标记_MESSAGE=“MESSAGE”;
//需要注意的是,消息都位于的父分支中
//我们的JSON树显示“Post Available”或“No Post Available”
//信息,
//每个帖子都有一条信息,列在
//“职位”
//类别,显示用户键入的消息。
//我们所有评论的数组
私有JSONArray mComments=null;
//管理列表中的所有评论。
私有数组列表mCommentList;
公共主视图控制器()
{
}
字符串[]mainFeed={};
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
////TODO自动生成的方法存根
//ArrayAdapter适配器=新的ArrayAdapter(
//充气器.getContext(),android.R.layout.simple\u list\u item\u 1,
//主食);
//
//setListAdapter(适配器);
返回super.onCreateView(充气机、容器、savedInstanceState);
}
@凌驾
恢复时公开作废(){
//TODO自动生成的方法存根
super.onResume();
//通过AsyncTask加载注释
新建LoadComments().execute();
}
公共void addComment(视图五){
//意图i=新意图(ReadComments.this、AddComment.class);
//星触觉(i);
}
/**
*从服务器检索最近发布的数据。
*/
public void updateJSONdata(){
//实例化arraylist以包含所有JSON数据。
//我们将使用一组键值对,引用
//例如,json元素名和内容,
//在标签上留言,并在内容上写上“我太棒了”。。
mCommentList=newarraylist();
//兄弟,是时候给J解析器通电了
JSONParser jParser=新的JSONParser();
//向野兽提供我们的评论url,它就会吐我们
//返回一个JSON对象。嘘,耶,杰罗姆。
JSONObject json=jParser.getJSONFromUrl(读取注释URL);
//在解析JSON内容时,我们可能应该
//尝试捕获任何异常:
试一试{
//我知道我说过我们会检查“帖子是否有用。”(success==1)
//在我们试图阅读个别帖子之前,但我撒谎了。。。
//McComments会告诉我们有多少“帖子”或评论
//可用
mComments=json.getJSONArray(TAG_POSTS);
//根据返回的json对象遍历所有帖子
对于(int i=0;ipublic class LoadComments extends AsyncTask<Void, Void, Boolean> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
//              pDialog = new ProgressDialog(mainViewController.this);
//              pDialog.setMessage("Loading Posts...");
//              pDialog.setIndeterminate(false);
//              pDialog.setCancelable(true);
//              pDialog.show();
            }

            @Override
            protected Boolean doInBackground(Void... arg0) {
                updateJSONdata();
                return null;

            }

            @Override
            protected void onPostExecute(Boolean result) {
                super.onPostExecute(result);
                //pDialog.dismiss();
                updateList();
            }
        }

     @Override
        public void onListItemClick(ListView l, View v, int position, long id) 
        {
            // TODO Auto-generated method stub
            super.onListItemClick(l, v, position, id);
        }
}