如何使用ArrayList将JSON数据填充到ListView中

时间:2015-06-30 08:53:37

标签: java android json listview arraylist

我已使用ArrayList成功将JSON数据解析为ListView,但无法根据City名称填充List。

就像我允许用户选择City然后我尝试使用新的ArrayList将结果填充到ListView中,但是没有将任何数据导入ListView。

public class TitleListActivity extends Activity {

  ....

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_title);

    ......
    new JSONAsyncTask().execute("http://murl.com/json/citywise.json");  

    try {
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            value = extras.getString("new_variable_name");
            Toast.makeText(TitleListActivity.this, value, Toast.LENGTH_LONG).show(); 

            // not getting data city wise
            cityWiseSearch();
        }
        else
        {
            // getting all data
            adapter = new TitleListAdapter(TitleListActivity.this, R.layout.row, allArrayList);             
            listview.setAdapter(adapter); 
        }
    } catch (Exception e) {
        // TODO: handle exception
    }


    ....
}

class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {

    ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override
    protected Boolean doInBackground(String... urls) {
        try {

            ....

                JSONArray jarray = jsono.getJSONArray("cities");

                for (int i = 0; i < jarray.length(); i++) {
                    JSONObject object = jarray.getJSONObject(i);

                    destination = new TitleList();                      
                    destination.setTitle(object.getString("address"));                      
                    allArrayList.add(destination);

                ......

        return false;
    }

    protected void onPostExecute(Boolean result) {
        dialog.cancel();
        ....
    }
}

public void cityWiseSearch() {              

    for (int i = 0; i <allArrayList.size(); i++) {
        destination = (TitleList) allArrayList.get(i);

        String strStatuss = allArrayList.get(i).getCity();

        if (strStatuss.equalsIgnoreCase(value)){                
            cityArrayList.add(destination);         
        }                      
    }              

    adapter = new TitleListAdapter(TitleListActivity.this, R.layout.row, cityArrayList);        
    listview.setAdapter(adapter);

   }
 }

2 个答案:

答案 0 :(得分:2)

放置setAdapter code inside onPostExecute,您必须提取city名称,因为您要提取title以比较 cityWiseSearch()方法中的城市名称

destination.setCity(object.getString("city")); 

答案 1 :(得分:0)

我认为您的ListView是空的,因为您更新ArrayList但是您必须在调用之前将allArrayList发送到适配器

adapter.notifyDataSetChanged();