Search code examples
javaandroidlistviewlistadapter

data will not populate listview


I'm having issues populating my listview. I thought I had modifed my XML and adapters accordingly but apparently not. When the activity is loaded the dialog pops up stating it's loading then the app force closes. If i remove the 3 lines of coding stating listview.setText(name) then it just loads all the items with the default text in my XML file. My code looks like this:

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>

Solution

  • // Change display methods

          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();
    }
    

    // add folloowing class in activity

      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;
        }
    
    }