簡體   English   中英

Android AsyncTask片段加載

[英]Android AsyncTask Fragment Loading

我正在嘗試在Android片段中創建一個JSON填充的listview。 該應用程序在AsyncTask區域崩潰,但是我不確定是什么問題。 我正在嘗試使用活動的原始教程,但將其轉換為片段: http : //www.mybringback.com/tutorial-series/13239/android-mysql-php-json-part- 6-json-parsing-and-android-design / ; 如果需要,將很樂意發布整個片段代碼。 如果您需要更多信息,請告訴我。

片段整體:

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

的AsyncTask:

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

Android錯誤:

08-04 22:14:53.530:E / AndroidRuntime(22819):致命異常:主08-04 22:14:53.530:E / AndroidRuntime(22819):進程:com.rynovation.kline,PID:22819 08-04 22:14:53.530:E / AndroidRuntime(22819):java.lang.NullPointerException 08-04 22:14:53.530:E / AndroidRuntime(22819):在android.widget.SimpleAdapter。(SimpleAdapter.java:85)08- 04 22:14:53.530:E / AndroidRuntime(22819):在com.rynovation.kline.mainViewController.updateList(mainViewController.java:159)08-04 22:14:53.530:E / AndroidRuntime(22819):在com。 rynovation.kline.mainViewController.access $ 0(mainViewController.java:152)08-04 22:14:53.530:E / AndroidRuntime(22819):at com.rynovation.kline.mainViewController $ LoadComments.onPostExecute(mainViewController.java:209) 08-04 22:14:53.530:E / AndroidRuntime(22819):at com.rynovation.kline.mainViewController $ LoadComments.onPostExecute(mainViewController.java:1)08-04 22:14:53.530:E / AndroidRuntime(22819) :位於android.os.AsyncTask.finish(AsyncTask.java:632)08-04 22:14:53.530:E / AndroidRunt ime(22819):在android.os.AsyncTask.access $ 600(AsyncTask.java:177)08-04 22:14:53.530:E / AndroidRuntime(22819):在android.os.AsyncTask $ InternalHandler.handleMessage(AsyncTask。 java:645)08-04 22:14:53.530:E / AndroidRuntime(22819):在android.os.Handler.dispatchMessage(Handler.java:102)08-04 22:14:53.530:E / AndroidRuntime(22819) :位於android.os.Looper.loop(Looper.java:146)08-04 22:14:53.530:E / AndroidRuntime(22819):位於android.app.ActivityThread.main(ActivityThread.java:5487)08-04 22:14:53.530:E / AndroidRuntime(22819):at java.lang.reflect.Method.invokeNative(Native Method)08-04 22:14:53.530:E / AndroidRuntime(22819):at java.lang.reflect Method.invoke(Method.java:515)08-04 22:14:53.530:E / AndroidRuntime(22819):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1283)08-04 22:14:53.530:E / AndroidRuntime(22819):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)08-04 22:14:53.530:E / AndroidRuntime(22819):在dalvik .system.NativeStart.main(NAT ive方法)

您要傳遞的上下文為null,因為在代碼中沒有this.context集合。 請改用Fragment.getActivity()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM