Android - 从网络获取非常大的JSON数组 - 导致粉碎

时间:2014-04-01 15:55:14

标签: android arrays json android-asynctask

我正在开发Android应用程序,它从Web服务器(通过AsyncTask)获取非常大的JSON数组,有时它很破碎,有时它不是 - 我认为它是因为我正在收获一个巨大的json数组(大约1500个JSON对象),当我得到250个JSON对象时,它的工作效果很好。

应用程序获取JSON数组并使用Custome adatper将其添加到LIstView。

在创建时:

try {
async_get_songs = new Read_today_songs();
async_get_songs.execute();
asynk_timeout(async_get_songs, 15000);
} catch (Exception e) {
    new Read_today_songs().execute();
}

的AsyncTask:

public class Read_today_songs extends AsyncTask<String, Integer, String> {
        boolean running = true;

        @Override
        protected void onCancelled() {
            super.onCancelled();
            finish();
        }


        @Override
        protected String doInBackground(String... params) {
            try {
                jsonArray = getJSONs_array();
                if (jsonArray.length() > 0) {
                    today_song_item = new ArrayList<Map<String, String>>();
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        // singerName = jsonObject.getString("singerName");
                        Map<String, String> map = new HashMap<String, String>();

                        String singerName_coverted = jsonObject.getString("singerName").replaceAll("(\\r|\\n|' ')", "");
                        String songName_coverted = jsonObject.getString("songName").replaceAll("(\\r|\\n|' ')", "");
                        String date_coverted = jsonObject.getString("date").replaceAll("(\\r|\\n|' ')", "");

                        map.put("singerName", singerName_coverted);
                        map.put("songName", songName_coverted);
                        map.put("date", date_coverted);
                        today_song_item.add(map);
                    }
                    return "true";
                } else
                    return "false";
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            pbPlaylist.setVisibility(View.GONE);
            etSearchPlaylist.setEnabled(true);
            // check if got the today_song_itemArrayList<Map<String, String>>()
            // with values
            if (result.contains("true")) {
                ArrayList<Song> mListItems = new ArrayList<Song>();
                for (Map<String, String> mapItem : today_song_item) {
                    Song song_item = new Song(mapItem.get("singerName"), mapItem.get("songName"), mapItem.get("date"));
                    mListItems.add(song_item);
                }

                mAdapter = new CustomAdapter(thePlayList.this, R.layout.playlist_item_layout, mListItems);
                lvSongsList.setAdapter(mAdapter);
            } else
                fb_msg = "שגיאה התרחשה!";
        }
    }

public JSONArray getJSONs_array() throws ClientProtocolException, IOException, JSONException {
        StringBuilder url = new StringBuilder(current_url);
        HttpGet get = new HttpGet(url.toString());
        HttpResponse r = client.execute(get);
        int status = r.getStatusLine().getStatusCode();
        if (status == 200) {
            HttpEntity e = r.getEntity();
            String data = EntityUtils.toString(e);
            JSONArray JSONarray = new JSONArray(data);
            return JSONarray;
        } else
            return null;
    }

CustomeAdatper:

public class CustomAdapter extends ArrayAdapter<Song> {

    public CustomAdapter(Context context, int resource, ArrayList<Song> mlist) {
        super(context, resource);
        dbTools = new DBTools(context);
        this.mlist = mlist;
        this.context = context;
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getPosition(Song item) {
        return super.getPosition(item);
    }

    @Override
    public Song getItem(int position) {
        return mlist.get(position);
    }

    @Override
    public int getCount() {
        return mlist.size();
    }

    @Override
    public long getItemId(int position) {
        return super.getItemId(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        convertView = inflater.inflate(R.layout.playlist_item_layout, null);// Replace your                         // layout....
        tvArtist = (TextView) convertView.findViewById(R.id.tvArtist);
        tvSongName = (TextView) convertView.findViewById(R.id.tvSongName);
        tvDate = (TextView) convertView.findViewById(R.id.tvDate);
        ivFav = (ImageView)convertView.findViewById(R.id.ivFav);

        tvArtist_from_list = mlist.get(position).getSingerName();
        tvSongName_from_list = mlist.get(position).getSongName();
        tvDate_from_list = mlist.get(position).getDate();

        tvArtist_from_list = tvArtist_from_list.replaceAll("(\\r|\\n|' ')", "");
        tvSongName_from_list = tvSongName_from_list.replaceAll("(\\r|\\n|' ')", "");
        tvDate_from_list = tvDate_from_list.replaceAll("(\\r|\\n|' ')", "");

        tvArtist.setText(tvArtist_from_list);
        tvSongName.setText(tvSongName_from_list);
        tvDate.setText(tvDate_from_list);

        try {
            Cursor c = dbTools.getAllRowsByQuery("SELECT * FROM favs WHERE singerName='"+tvArtist_from_list+"' AND songName='"+tvSongName_from_list+"'");
            if (c.moveToFirst()) {
                ivFav.setImageResource(R.drawable.plank4);
                ivFav.setTag("full");
            }else{
                ivFav.setImageResource(R.drawable.plank4_empty);
                ivFav.setTag("");
            }
        } catch (Exception e) {
            alert(e.toString());

        }
        return convertView;
    }
    // Filter Class
    public void filter(CharSequence cs) {
        String cs_string = String.valueOf(cs);
        cs_string = cs_string.toLowerCase(Locale.getDefault());
        if (original_mlist==null) {
            original_mlist = new ArrayList<Song>();
            original_mlist.addAll(mlist);
        }
        this.mlist.clear();
        if (cs_string.length() == 0) {
            mlist.addAll(original_mlist);

        } else {
            for (Song song_item : original_mlist) {
                if (son

g_item.getFullSongName().toLowerCase(Locale.getDefault()).contains(cs_string) ||
                            song_item.getSingerName().toLowerCase(Locale.getDefault()).contains(cs_string) ||
                            song_item

.getDate().toLowerCase(Locale.getDefault()).contains(cs_string)) {
                        this.mlist.add(song_item);
                    }
                }
            }
                notifyDataSetChanged();
            }
            public void alert(String get_fb_msg) {
                Toast.makeText(context, get_fb_msg, Toast.LENGTH_SHORT).show();
            }

    }

控制台错误:

04-01 18:49:50.082: E/AndroidRuntime(31326): FATAL EXCEPTION: main
04-01 18:49:50.082: E/AndroidRuntime(31326): java.lang.NullPointerException
04-01 18:49:50.082: E/AndroidRuntime(31326):    at com.manishma.thePlayList$Read_today_songs.onPostExecute(thePlayList.java:383)
04-01 18:49:50.082: E/AndroidRuntime(31326):    at com.manishma.thePlayList$Read_today_songs.onPostExecute(thePlayList.java:1)
04-01 18:49:50.082: E/AndroidRuntime(31326):    at android.os.AsyncTask.finish(AsyncTask.java:631)
04-01 18:49:50.082: E/AndroidRuntime(31326):    at android.os.AsyncTask.access$600(AsyncTask.java:177)
04-01 18:49:50.082: E/AndroidRuntime(31326):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
04-01 18:49:50.082: E/AndroidRuntime(31326):    at android.os.Handler.dispatchMessage(Handler.java:99)
04-01 18:49:50.082: E/AndroidRuntime(31326):    at android.os.Looper.loop(Looper.java:137)
04-01 18:49:50.082: E/AndroidRuntime(31326):    at android.app.ActivityThread.main(ActivityThread.java:5171)
04-01 18:49:50.082: E/AndroidRuntime(31326):    at java.lang.reflect.Method.invokeNative(Native Method)
04-01 18:49:50.082: E/AndroidRuntime(31326):    at java.lang.reflect.Method.invoke(Method.java:511)
04-01 18:49:50.082: E/AndroidRuntime(31326):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
04-01 18:49:50.082: E/AndroidRuntime(31326):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:564)
04-01 18:49:50.082: E/AndroidRuntime(31326):    at dalvik.system.NativeStart.main(Native Method)

我该如何解决?

1 个答案:

答案 0 :(得分:0)

使用IntentService而不是AsyncTask,服务与活动或片段的生命周期无关,它们具有独立的生命周期,例如,如果您在活动中创建了asynctask并且用户轮换了他们的设备,AsyncTask将被重新创建,它将重新开始,相反,如果您使用IntentService,一旦网络请求启动,无论用户是否更改方向或切换应用程序,请求都将完成;你要做的就是找出如何通知你的Activites / Fragments有新数据,你可以使用广播,或使用外部库,如Otto

由于json是如此之大,所以最好将它存储在本地,只有当你知道某些事情发生了变化或者已经过了很多时间才能获取它