对Listview的AsyncTask + JSON解析有时只显示数据

时间:2016-09-08 15:02:24

标签: android android-layout listview android-fragments

有时它显示数据,有时它什么也没显示。

public class HomeFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.home_fragment, container, false);
        arraylist1 = new ArrayList<>();
        listOfNews = (ListView) view.findViewById(R.id.listView);

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                new ReadJSON().execute("url");
            }
        });

        return view;
    }

    public class ReadJSON extends AsyncTask<String, Integer, String> {


        @Override
        protected String doInBackground(String... url) {
            String st = readURL(url[0]);
            Log.d("st", st);
            return st;
        }

        @Override
        protected void onPostExecute(String content) {
            try {
                JSONObject jsonObject = new JSONObject(content);
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                for (int i = 0; i < jsonArray.length(); i++) {
                    Log.d(i+":jsonArray object", jsonArray.toString() + " size= " + jsonArray.length());
                    JSONObject productObject = jsonArray.getJSONObject(i);
                    JSONObject img = productObject.getJSONObject("image");
                    JSONObject da = img.getJSONObject("data");

                    arraylist1.add(new HotNews(
                            da.getString("filename"),
                            productObject.getString("title"),
                            productObject.getString("article_by"),
                            productObject.getString("date_publish"),
                            productObject.getString("short_description")
                    ));
                }

                Log.d("jsonArray news list1", arraylist1.size() + "");
            } catch (JSONException e) {
                e.printStackTrace();
            }

            adapter = new ListViewAdapter(view.getContext(), R.layout.list_view_adapter, arraylist1);
            listOfNews.setAdapter(adapter);
            adapter.notifyDataSetChanged();

        }

    }

    private static String readURL(String theUrl) {
        StringBuilder content = new StringBuilder();

        try {
            //create url object
            URL url = new URL(theUrl);
            //create url connection
            URLConnection urlConnection = url.openConnection();
            //wrap the urlconnection in a bufferedreader
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                content.append(line + "\n");
            }
            bufferedReader.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return content.toString();

    }

}
public class ListViewAdapter extends ArrayAdapter<HotNews> {

    public ListViewAdapter(Context context, int resource, ArrayList<HotNews> arrayList) {
        super(context, resource,arrayList);
        mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.arrayList = arrayList;
        this.context = context;
    }

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

    @Override
    public int getViewTypeCount() {
        return 2;
    }
    @Override
    public long getItemId(int position) {
        return position;
    }


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

        if (v == null) {
            v = mInflater.inflate(R.layout.list_view_adapter, parent, false);
        }
            image = (ImageView) v.findViewById(R.id.imagetitle);
            title = (TextView) v.findViewById(R.id.txtTitle);
            doer = (TextView) v.findViewById(R.id.doer);
            date = (TextView) v.findViewById(R.id.txtdate);
            text = (TextView) v.findViewById(R.id.text);

            final HotNews news = getItem(position);

            Picasso.with(getContext()).load("url" + news.getImage()).noFade().into(image);
            title.setText(news.getTitle());
            doer.setText(news.getDoer());
            date.setText(news.getDate());
            text.setText(news.getContent());
            return v;
        }

}

2 个答案:

答案 0 :(得分:0)

试试这段代码:

public class HomeFragment  extends Fragment {

private View view;
private ArrayList<HotNews> arraylist1;
private ListView listOfNews;

private int SUCCESS = 1;
private int FAILS = 0;
private int NO_DATA = 2;
private int ERROR = -1;
private ListViewAdapter adapter;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.home_fragment, container, false);
    arraylist1 = new ArrayList<>();
    listOfNews = (ListView) view.findViewById(R.id.listView);
    adapter = new ListViewAdapter();
    listOfNews.setAdapter(adapter);

    new ReadJSON().execute("url");


    return view;
}

public class ReadJSON extends AsyncTask<String, Integer, Integer> {


    @Override
    protected Integer doInBackground(String... url) {
        String response = readURL(url[0]);
        Log.d("response ", response);


        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            arraylist1.clear();

            if(jsonArray.length()>0) {

                for (int i = 0; i < jsonArray.length(); i++) {
                    Log.d(i + ":jsonArray object", jsonArray.toString() + " size= " + jsonArray.length());
                    JSONObject productObject = jsonArray.getJSONObject(i);
                    JSONObject img = productObject.getJSONObject("image");
                    JSONObject da = img.getJSONObject("data");

                    arraylist1.add(new HotNews(
                            da.getString("filename"),
                            productObject.getString("title"),
                            productObject.getString("article_by"),
                            productObject.getString("date_publish"),
                            productObject.getString("short_description")
                    ));
                }
            }else{
                return NO_DATA;
            }
            Log.d("jsonArray news list1", arraylist1.size() + "");
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }
        return SUCCESS;
    }

    @Override
    protected void onPostExecute(Integer integer) {
        super.onPostExecute(integer);
        Log.d("parseResponse", integer + "");
        if(integer==SUCCESS){
            adapter.notifyDataSetChanged();
        }else if(integer==ERROR){
            Toast.makeText(getActivity(),"Server or Exception Error!", Toast.LENGTH_SHORT).show();
        }else if(integer==NO_DATA){
            Toast.makeText(getActivity(),"No Data!", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(getActivity(),"Some thing went wrong!", Toast.LENGTH_SHORT).show();
        }
    }
}


class ListViewAdapter extends BaseAdapter{


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

    @Override
    public Object getItem(int position) {
        return arraylist1.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        ListViewHolder holder;
        if (v == null) {
            v = LayoutInflater.from(getActivity()).inflate(R.layout.list_view_adapter, parent, false);
            holder = new ListViewHolder(v);
            v.setTag(holder);
        }else{
            holder = (ListViewHolder)v.getTag();
        }


        final HotNews news = arraylist1.get(position);


        holder.title.setText(news.getTitle());
        holder.doer.setText(news.getDoer());
        holder.date.setText(news.getDate());
        holder.text.setText(news.getContent());

        Picasso.with(getContext()).load("url" + news.getImage()).noFade().into(holder.image);
        return v;
    }

    class ListViewHolder {
        private ImageView image;
        private TextView title,doer,date,text;
        public ListViewHolder(View v){
            image = (ImageView) v.findViewById(R.id.imagetitle);
            title = (TextView) v.findViewById(R.id.txtTitle);
            doer = (TextView) v.findViewById(R.id.doer);
            date = (TextView) v.findViewById(R.id.txtdate);
            text = (TextView) v.findViewById(R.id.text);
        }
    }

}


private static String readURL(String theUrl) {
    StringBuilder content = new StringBuilder();

    try {
        //create url object
        URL url = new URL(theUrl);
        //create url connection
        URLConnection urlConnection = url.openConnection();
        //wrap the urlconnection in a bufferedreader
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            content.append(line + "\n");
        }
        bufferedReader.close();

    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return content.toString();

}

}

答案 1 :(得分:0)

您看到此错误,这会导致整个循环崩溃。您可能正在请求10个对象,但在没有该image属性的第一个对象上,它正在退出。

  

W / System.err:org.json.JSONException:没有图像值

因此,建议(除了使用Retrofit管理您的JSON API之外)将使用optType()方法而不是JSON对象的getType()方法。

例如,

JSONObject img = productObject.optJSONObject("image");

img属性不存在时,这会将null设置为"image"

稍后请注意,如果您在此行中尝试使用img时遇到NullPointerException

JSONObject da = img.getJSONObject("data");