添加其他项目后,ListView不会刷新

时间:2014-07-26 16:21:43

标签: java android android-listview arraylist listview-adapter

我打算向ListView添加额外的项目,然后刷新ListView以显示这些项目。但是,我相信这些项目正在添加(因为当我旋转时,ListView会刷新并显示新项目)但是当前没有刷新。

最初将项目添加到ListView。我使用getData。之后,每次"添加更多"单击项目,从getDataMore检索数据。我尝试过addAll()和notifyDataSetChanged()之类的函数,但我相信我的结构有问题。

FragmentA - 包含带有点击监听器的ListView的片段:

public class FragmentA extends Fragment implements OnItemClickListener {

getData data = getData.getMyData();

public Integer ArticleID;
public CustomList adapter;
public ListView listView;
public View v;
public View V;

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

    V = inflater.inflate(R.layout.fragment_a, container, false);

    listView = (ListView)V.findViewById(R.id.list);

    v = inflater.inflate(R.layout.single_row_loadmore, null);
    listView.addFooterView(v);

      adapter = new CustomList(getActivity(), data.Headline.toArray(new String[data.Headline.size()]), data.Description.toArray(new String[data.Description.size()]), data.BitmapList.toArray(new Bitmap[data.BitmapList.size()]), data.ArticleID.toArray(new Integer[data.ArticleID.size()]));     
      listView.setAdapter(adapter);
      listView.setOnItemClickListener(this);

    return V;

}

@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    if((position + 1) < listView.getCount()){
        // TODO Auto-generated method stub
        Integer IDPasser;
        Intent intent = new Intent(getActivity(), ArticleViewer.class);

        VariableStore.ArticleID = (Integer) data.ArticleID.toArray()[position];
        // Log.e("Passer", IDPasser.toString());
        startActivity(intent);
    }else{      
        Log.e("", "Load more has been clicked");
        new getDataMore().runData();
        adapter = new CustomList(getActivity(), data.Headline.toArray(new String[data.Headline.size()]), data.Description.toArray(new String[data.Description.size()]), data.BitmapList.toArray(new Bitmap[data.BitmapList.size()]), data.ArticleID.toArray(new Integer[data.ArticleID.size()]));
          listView.setAdapter(adapter);
    }
    }

}

getData - 检索首次创建ListView时的数据:

public class getData {

private static getData _instance;

// Defining ArrayList
public static ArrayList<String> Headline = new ArrayList<String>();
public static ArrayList<String> Description = new ArrayList<String>();
public static ArrayList<Bitmap> BitmapList = new ArrayList<Bitmap>();
public static ArrayList<Integer> ArticleID = new ArrayList<Integer>();

// Used to get array list into fragment
public static getData getMyData() {
    if (_instance == null)
        _instance = new getData();
    _instance.runData();
    return _instance;
}

public void runData() {
    StrictMode.enableDefaults(); // STRICT MODE ENABLED
    String result = "";
    InputStream isr = null;
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(
                "http://www.createyourownnews.co.uk/getAllCustomers.php"); // YOUR
                                                                            // PHP
                                                                            // SCRIPT
                                                                            // ADDRESS
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        isr = entity.getContent();
    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }
    // convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                isr, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        isr.close();

        result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error  converting result " + e.toString());
    }

    // parse json data
    try {
        String s = "";
        JSONArray jArray = new JSONArray(result);

        for (int i = 0; i < jArray.length(); i++) {
            JSONObject json = jArray.getJSONObject(i);

            Headline.add(json.getString("NewsStory"));
            Description.add(json.getString("Summary1"));

            ArticleID.add(json.getInt("ID"));

            if (json.getString("Picture1URL").length() == 0) {
                json.getString("Picture1URL")
                        .equals("http://4.bp.blogspot.com/-JOqxgp-ZWe0/U3BtyEQlEiI/AAAAAAAAOfg/Doq6Q2MwIKA/s1600/google-logo-874x288.png");
            }

            Log.e("", json.getString("Picture1URL"));

            Bitmap bitmap = null;
            try {
                bitmap = BitmapFactory.decodeStream((InputStream) new URL(
                        json.getString("Picture1URL")).getContent());
                BitmapList.add(bitmap);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    } catch (Exception e) {
        Log.e("log_tag", "Error Parsing Data " + e.toString());
    }

}
}

getDataMore - 添加到已经创建的ArrayLists是getData:

public class getDataMore {

public void runData() {
    getData data = getData.getMyData();
    StrictMode.enableDefaults(); // STRICT MODE ENABLED
    String result = "";
    InputStream isr = null;
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(
                "http://www.createyourownnews.co.uk/getAllCustomers.php"); // YOUR
                                                                            // PHP
                                                                            // SCRIPT
                                                                            // ADDRESS
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        isr = entity.getContent();
    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
        // ERROR CONNECTING
    }
    // convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                isr, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        isr.close();

        result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error  converting result " + e.toString());
    }

    // parse json data
    try {
        String s = "";
        JSONArray jArray = new JSONArray(result);

        for (int i = 0; i < jArray.length(); i++) {
            JSONObject json = jArray.getJSONObject(i);

            data.Headline.add(json.getString("NewsStory"));
            data.Description.add(json.getString("Summary1"));

            data.ArticleID.add(json.getInt("ID"));

            if(json.getString("Picture1URL").length() == 0){
                json.getString("Picture1URL").equals("http://4.bp.blogspot.com/-JOqxgp-ZWe0/U3BtyEQlEiI/AAAAAAAAOfg/Doq6Q2MwIKA/s1600/google-logo-874x288.png");
            }

            Bitmap bitmap = null;
            try {
                bitmap = BitmapFactory.decodeStream((InputStream) new URL(json.getString("Picture1URL")).getContent());
                data.BitmapList.add(bitmap);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }



            Log.e("log_tag", "Iteration" + i);

        }

    } catch (Exception e) {
        Log.e("log_tag", "Error Parsing Data " + e.toString());
    }

}
}

如果有帮助 - CustomList适配器:

public class CustomList extends ArrayAdapter<String>{

private final Activity context;
private final String[] titleId;
private final String[] descriptionId;
private final Bitmap[] pictureid;

public CustomList(Activity context,
String[] Headline, String[] Description, Bitmap[] BitmapList, Integer[] ArticleID) {
super(context, R.layout.single_row, Headline);
this.context = context;
this.titleId = Headline;
this.descriptionId = Description;
this.pictureid = BitmapList;

}
@Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.single_row, null, true);

TextView txtTitle = (TextView) rowView.findViewById(R.id.tvTitle);
TextView txtDescription = (TextView) rowView.findViewById(R.id.tvDescription);
ImageView imageView = (ImageView) rowView.findViewById(R.id.ivIcon);

txtTitle.setText(titleId[position]);
txtDescription.setText(descriptionId[position]);
imageView.setImageBitmap(pictureid[position]);
return rowView;
}


}

1 个答案:

答案 0 :(得分:3)

将新项目添加到ArrayList

之后
adapter.notifyDataSetChanged();