数据不会填充listview

时间:2013-05-13 03:48:27

标签: java android listview listadapter

我在填写listview时遇到问题。我以为我相应地修改了我的XML和适配器,但显然没有。加载活动后,会弹出对话框,说明正在加载,然后应用程序强制关闭。如果我删除说明listview.setText(名称)的3行编码​​,那么它只是加载我的XML文件中的默认文本的所有项目。我的代码如下所示:

public class DisplayServiceActivity extends ListActivity {
    private ListView listOfServices;

    //JSONArrays?
    JSONArray directory;


    //JSON Node names
    private static String TAG_ID = "id";
    private static String TAG_NAME= "name";
    private static String TAG_DIRECTORY = "Categories";
    private final static String url= "API LINK HERE";
    JSONObject json;
jsonParser jParser = new jsonParser();
ArrayList<HashMap<String, String>> directoryList;

@SuppressLint("NewApi")
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.service);

    directoryList = new ArrayList<HashMap<String, String>>();
    Request request = new Request();
    request.execute();

    listOfServices = getListView(); //get builtin listView




    // Make sure we're running on Honeycomb or higher to use ActionBar APIs
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        // Show the Up button in the action bar.
        getActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle("Home Service Categories");

    }
}// end of onCreate Method
@SuppressWarnings("unused")
public class Request extends AsyncTask<String, Void, JSONObject> {

    private static final int REGISTRATION_TIMEOUT = 3 * 1000;
    private static final int WAIT_TIMEOUT = 30 * 1000;
    private ProgressDialog dialog = 
            new ProgressDialog(DisplayServiceActivity.this);


    protected void onPreExecute() {
        dialog = new ProgressDialog(DisplayServiceActivity.this);
        dialog.setMessage("Getting your info real quick... Please wait...");
        dialog.show();
    }

    protected JSONObject doInBackground(String... params) {

        json = jParser.getJSONfromURL(url);

        return json;

    }

    protected void onPostExecute(JSONObject s) {          
        super.onPostExecute(s);
        String name = null;
        String id = null;
        dialog.dismiss();

        try {
            directory = s.getJSONArray("Categories");
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        for(int i = 0; i< directory.length(); i++){;
        try {
            id = directory.getJSONObject(i).getString(TAG_ID);
            name = directory.getJSONObject(i).getString(TAG_NAME);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        displayCatList(id, name);

        }

    }

}

public void displayCatList(String id, String name){                 
    //create new HashMap
    HashMap<String,String> map = new HashMap<String, String>();

    //add each child node to HashMap key
    //map.put(TAG_ID, id);
    map.put(TAG_NAME, name);

    //adding HashList to ArrarList
    directoryList.add(map);



    // set Adapter for ListView here
    ListAdapter adapter = new SimpleAdapter(this,
            directoryList, 
            R.layout.list_item, 
            new String[] { name }, 
            new int[] { android.R.id.text1});



    LayoutInflater inflator = (LayoutInflater)  getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View  v = inflator.inflate(R.layout.list_item, null);
    TextView listName = (TextView) v.findViewById(R.id.listName);
    listName.setText(name);

    setListAdapter(adapter);

}



@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        NavUtils.navigateUpFromSameTask(this);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

List_item.xml

<?xml version="1.0" encoding="utf-8"?>
<!--  Single List Item Design -->
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listName"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="rubble rubble rubble"
        android:textColor="#FFFFFF"
        android:padding="10dip"
        android:textSize="20dip"
        android:textStyle="bold" >
</TextView>

的services.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/gradient"
    android:orientation="vertical" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </ListView>

    <TextView
        android:id="@+id/listName"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="10dip"
        android:text="rubble rubble rubble"
        android:textColor="#FFFFFF"
        android:textSize="20dip"
        android:textStyle="bold" >
    </TextView>

</LinearLayout>

4 个答案:

答案 0 :(得分:1)

//更改显示方法

      public void displayCatList(String id, String name){                 
      //create new HashMap
    HashMap<String,String> map = new HashMap<String, String>();

    //add each child node to HashMap key
    //map.put(TAG_ID, id);
    map.put(TAG_NAME, name);

    //adding HashList to ArrarList
    directoryList.add(map);

    MySimpleAdapter adapter = new MySimpleAdapter(this, R.layout.list_item, android.R.id.text1, directoryList);
    setListAdapter(adapter);

    adapter.notifyDataSetChanged();
}

//在活动中添加folloowing类

  public class MySimpleAdapter extends ArrayAdapter<HashMap<String, String>> {

    List<HashMap<String, String>> listItems;

    public MySimpleAdapter(Context context, int resource,
            int textViewResourceId, List<HashMap<String, String>> objects) {
        super(context, resource, textViewResourceId, objects);
        listItems = objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        if(convertView == null) {
                  LayoutInflater inflator = (LayoutInflater)  getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflator.inflate(R.layout.list_item, null);
        }

          TextView listName = (TextView) convertView.findViewById(R.id.listName);

        listName.setText(listItems.get(position).get(TAG_NAME));
        return convertView;
    }

}

答案 1 :(得分:0)

您正在将视图设置为R.layout.service。但是在displayCatList中,你为listitem.xml中的一个视图调用了findViewById。这不起作用 - 它不在你看来。如果该文本视图应该在列表中,则需要在调用适配器的getView时进行设置。或者让simpleAdaptor为您完成。如果您不希望它成为行的一部分,则不要将其添加到listitem.xml

答案 2 :(得分:0)

您的listName为空,因为TextView R.id.listName不在主布局中。要获得TextView的值,请执行以下操作: -

LayoutInflator li = getLayoutInflator();
View listItems = li.inflate(R.layout.list_item, null);
// set Adapter for ListView here
        ListAdapter adapter = new SimpleAdapter(this,
                directoryList, 
                listItems , 
                new String[] { id,name }, 
                new int[] { android.R.id.text1,android.R.id.text2 });


        TextView listName = (TextView) listItems .findViewById(R.id.listName);
        Log.e("XML Variable", name);
        listName.setText(name);

这里我改变的是我在一个名为listItems的视图中夸大了R.layout.list_item,并用它来查找TextView listName。

希望这有帮助。

答案 3 :(得分:0)

在你的代码中,你首先调用asynck任务,它正在处理包括setAdapter for listview在内的所有内容,然后再调用带有directoryList的setAdapter,当你在异步任务之后初始化时,该目录是空白的。最好的解决方案是初始化你的directoryList关于asynctask调用。

 directoryList = new ArrayList<HashMap<String, String>>(); 
 Request request = new Request();
    request.execute();

然后你的整个代码试试这个。我认为它会解决你的问题...... 我希望它有效。