无法从Asynctask填充数据?

时间:2014-10-18 07:31:40

标签: java android android-asynctask

在我的应用程序中,我正在解析Json文件中的数据。它工作正常。现在我将代码从我的主线程更改为Asynctask。我是Asynctask的新手,所以我无法找到我犯错误的地方。但是在logcat中它显示错误来自DoInBackground。 在此先感谢!

旧代码

private void parseJsonFeed(JSONObject response) {
    try {
        JSONArray feedArray = response.getJSONArray("feed");

        for (int i = 0; i < feedArray.length(); i++) {
            JSONObject feedObj = (JSONObject) feedArray.get(i);

            FeedItem item = new FeedItem();
            item.setId(feedObj.getInt("id"));
            item.setName(feedObj.getString("name"));

            // Image might be null sometimes
            String image = feedObj.isNull("image") ? null : feedObj
                    .getString("image");
            item.setImageUrl(image);
            item.setStatus(feedObj.getString("status"));
            item.setProfilePic(feedObj.getString("profilePic"));
            item.setTimeStamp(feedObj.getString("timeStamp"));

            // url might be null sometimes
            String feedUrl = feedObj.isNull("url") ? null : feedObj
                    .getString("url");
            item.setUrl(feedUrl);

            feedItems.add(item);
        }

        // notify data changes to list adapater
        listAdapter.notifyDataSetChanged();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

Asynctask代码

public class News extends AsyncTask<JSONObject, Void, FeedListAdapter> {

        JSONObject response;

        protected FeedListAdapter doInBackground(JSONObject... params) {
            try {
                JSONArray feedArray = response.getJSONArray("feed");

                for (int i = 0; i < feedArray.length(); i++) {
                    JSONObject feedObj = (JSONObject) feedArray.get(i);

                    FeedItem item = new FeedItem();
                    item.setId(feedObj.getInt("id"));
                    item.setName(feedObj.getString("name"));

                    // Image might be null sometimes
                    String image = feedObj.isNull("image") ? null : feedObj
                            .getString("image");
                    item.setImageUrl(image);
                    item.setStatus(feedObj.getString("status"));
                    item.setProfilePic(feedObj.getString("profilePic"));
                    item.setTimeStamp(feedObj.getString("timeStamp"));

                    // url might be null sometimes
                    String feedUrl = feedObj.isNull("url") ? null : feedObj
                            .getString("url");
                    item.setUrl(feedUrl);

                    feedItems.add(item);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        protected void onPostExecute(FeedListAdapter result) {
            super.onPostExecute(result);
            listAdapter.notifyDataSetChanged();
        }

    }

我的班级

public class FeedListActivity extends BaseActivity {
    private static final String TAG = "FeedListActivity";

    private ListView NewsView;
    private FeedListAdapter listAdapter;
    private List<FeedItem> feedItems;
    News mynews;
    private String URL_FEED = "http://www.amsonsindia.net/ins/news.json";

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feed_list);
        setTitle(R.string.feed_list_demo);

        mynews=new News();
        mynews.execute();

        NewsView = (ListView) findViewById(R.id.feed_list);
        feedItems = new ArrayList<FeedItem>();
        listAdapter = new FeedListAdapter(this, feedItems);
        NewsView.setAdapter(listAdapter);

        // making fresh volley request and getting json
        GsonRequest<FeedResult> gsonRequest = new GsonRequest<FeedResult>(URL_FEED, FeedResult.class,
                new Response.Listener<FeedResult>() {
                    @Override
                    public void onResponse(FeedResult response) {
                        feedItems = response.getFeedItems();
                        listAdapter.setData(feedItems);
                        listAdapter.notifyDataSetChanged();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d(TAG, "Error: " + error.getMessage());
                    }
                });

        // Adding request to volley request queue
        AppController.getInstance().addRequest(gsonRequest, TAG);
        getimg();
    }

logcat的

   Process: io.bxbxbai.feedlistviewdemo, PID: 2245
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
     Caused by: java.lang.NullPointerException
            at io.bxbxbai.androiddemos.activity.FeedListActivity$News.doInBackground(FeedListActivity.java:123)
            at io.bxbxbai.androiddemos.activity.FeedListActivity$News.doInBackground(FeedListActivity.java:117)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)

2 个答案:

答案 0 :(得分:0)

在doInBackground方法中,您无法更新UI

改变像这样的doinbackground代码 -

         for (int i = 0; i < feedArray.length(); i++) 
         {
         JSONObject feedObj = (JSONObject) feedArray.get(i);      

         publishProgress(feedObj.getInt("id"), feedObj.getString("status");
         //so on..
         }     

并在aynctask add

   protected void onProgressUpdate(final String... message) {
        try {

                FeedItem item = new FeedItem();
                item.setId(message[0]);
                item.setName(message[1);
                and so on


                feedItems.add(item);



        } catch (Exception e) {
            if (pd != null) {
                pd.dismiss();
            }
        }
    }

答案 1 :(得分:0)

    public class FeedListActivity extends BaseActivity {
        private static final String TAG = "FeedListActivity";

        private ListView NewsView;
        private FeedListAdapter listAdapter;
        private List<FeedItem> feedItems;
        News mynews;
        private String URL_FEED = "http://www.amsonsindia.net/ins/news.json";

        @SuppressLint("NewApi")
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_feed_list);
            setTitle(R.string.feed_list_demo);
            feedItems = new ArrayList<FeedItem>();
            listAdapter = new FeedListAdapter(this, feedItems);
// i just change feeditem position here
            mynews=new News();
            mynews.execute();

            NewsView = (ListView) findViewById(R.id.feed_list);

            NewsView.setAdapter(listAdapter);

            // making fresh volley request and getting json
            GsonRequest<FeedResult> gsonRequest = new GsonRequest<FeedResult>(URL_FEED, FeedResult.class,
                    new Response.Listener<FeedResult>() {
                        @Override
                        public void onResponse(FeedResult response) {
                            feedItems = response.getFeedItems();
                            listAdapter.setData(feedItems);
                            listAdapter.notifyDataSetChanged();
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Log.d(TAG, "Error: " + error.getMessage());
                        }
                    });

            // Adding request to volley request queue
            AppController.getInstance().addRequest(gsonRequest, TAG);
            getimg();
        }


    ----------
    Replace your my class with above and put debug in doinbackgroud
    and postexecute