I am setting up a ListView adapter like this:
public class SeeAllQuestionsActivity extends Activity
{
//ArrayAdapter<Question> adapter;
SimpleAdapter mSchedule = null;
ListView list = new ListView (this);
TextView loading_questions = null;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.all_question_page);
TextView loading_questions = (TextView) findViewById(R.id.loading_questions);
list = (ListView) findViewById(R.id.list);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
mSchedule = new SimpleAdapter(this, mylist, R.layout.questions_list,
new String[] {"train", "from", "to"},
new int[] {R.id.TRAIN_CELL, R.id.FROM_CELL, R.id.TO_CELL});
list.setAdapter(mSchedule);
list.setTextFilterEnabled(true);
list.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
...
and then making a remote Asynch call to get the list from my database, and trying to do this in the onPostExecute method:
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
try
{
JSONArray obj = new JSONArray(result);
if ( obj != null )
{
for ( int i = 0; i < obj.length(); i++ )
{
JSONObject o = obj.getJSONObject(i);
map.put("train", "Business Name");
map.put("from", ">");
map.put("to", ">");
mylist.add(map);
map = new HashMap<String, String>();
map.put("train", "103(x)");
map.put("from", "6:35 AM");
map.put("to", "7:45 AM");
mylist.add(map);
}
}
}
catch ( Exception e )
{
}
list.setAdapter(mSchedule);
but I get a Null Pointer exception on this line:
ListView list = new ListView (this);
But I think generally I am way off in how this needs to be done in the postExecute method. Any help with how to do this correctly is much appreciated.
In your OnCreate you define a new SimpleAdapter and attach it to your ListView. This is correct. The datasource (
mylistin your case) is empty at this point so you will fill it with in anAsyncTask.In your onPostExecute you are creating a new
ArrayList. Depending on the result you receive, you fill it. After you did this, you are setting the adapter again. Which will do nothing because the adapter has no data.. What you want to do, is give your new filled list to your Adapter so it can fill theListViewwith your data.Solution 1
This is one way you can do it and fits you current implementation.
Solution 2
I would opt for this solution
UPDATE
Check out this tutorial. I use the same layouts and same source to fill my list but I have altered it so it is similar to your case. Good luck 🙂
MainActivity