I have a main activity with many fragments, one of which contains a list view, with adaptor homeworkListAdapter
, this adapter does display any items initial in homeworkItems
. My activity opens up another activity (HomeworkAddActivity
, which gets a string from the user and puts it in an array homeworkItems
, this all works as I have checked each step independently. However when I try to update the list view with this new item (using .notifyDataSetChanged
) it doesn't update, I have been trying to fix this for 3-4 hours, please help.
Code
MainActivity
public static ArrayAdapter<String> homeworkListAdapter;
public static ArrayList<String> homeworkItems;
....
protected void onCreate(Bundle savedInstanceState) {
....
homeworkItems = new ArrayList<String>();
homeworkListAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, homeworkItems);
....
public static class HomeworkListViewFragment extends Fragment {
....
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_homework_listview, container, false);
homeworkListView = (ListView) rootView
.findViewById(R.id.homework_listview);
homeworkListView.setAdapter(homeworkListAdapter);
return rootView;
}
HomeworkAddActivity
public class HomeworkAddActivity extends ActionBarActivity {
....
public void buttonAddHomework(View v) {
NavUtils.navigateUpFromSameTask(this);
EditText editText = (EditText) findViewById(R.id.text_new_homework_name);
String homeworkItem = (String) editText.getText().toString();
if (!(TextUtils.isEmpty(homeworkItem))) {
//MainActivity.homeworkList.addItem(homeworkItem);
MainActivity.homeworkItems.add(homeworkItem);
MainActivity.homeworkListAdapter.notifyDataSetChanged();
}
}
}
Could you make a check like this:
if (!TextUtils.isEmpty(homeworkItem)) {
Toast.makeText(getBaseContext(),"ADDING AN ITEM!!!",Toast.LENGH_SHORT).show()
homeworkItems.add(homeworkItem);
homeworkListAdapter.notifyDataSetChanged();
}
just to be sure it passes the check. if it does (and you'll see the toast) then try
if (!TextUtils.isEmpty(homeworkItem)) {
homeworkItems.add(homeworkItem);
homeworkListAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, homeworkItems);
homeworkListView.setAdapter(homeworkListAdapter);
}
UPDATE
and the very last thing I assume your ListView has property android:height set to "wrap_content" - try to change it to "match_parent" :) It updates but you cant see it - try to scroll :)) And if this is it you should to fall back to notifyDatasetChanged()