onCreateView ListView is Empty. Items Missing - android

Resolved. See singularhum's answer below.
I have a sliding menu option that points to a fragment. This fragment inflates a layout using onCreateView. I update the values of the list in onActivityCreated . Here is my source.
My Listview
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
this.dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.getDefault());
this.portfolio = new Portfolio();
this.portfolio.addCompanyNoUpdate("YHOO");
// Specify the fragment layout file for this fragment class
View view = inflater.inflate(R.layout.fragment_stock, container, false);
progressText = (TextView) view.findViewById(R.id.progressTextView);
// Assign our CursorAdapter
adapter = new QuoteAdapter(getActivity(), portfolio.getQuotes());
ListView list = (ListView) view.findViewById(R.id.list);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
return view;
}
Then I have the onActivityCreated just doing an update.
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.update();
}
My Update Class
private void update() {
// If a network connection is available, update the stock information
if (Utils.isNetworkAvailable(getActivity())) {
// Start a custom task that downloads the data on another thread so the UI does not lock up
new UpdateQuotesTask().execute(portfolio);
}
else {
// Otherwise display an error message to the user
this.progressText.setText(this.getResources().getString(R.string.no_internet_connection));
}
}
My Adapter
public class QuoteAdapter extends BaseAdapter {
private Context context;
private List<Quote> quotes;
public QuoteAdapter(Context c, List<Quote> quotes) {
this.context = c;
this.quotes = quotes;
}
public void addQuote(Quote q) {
this.quotes.add(q);
}
#Override
public int getCount() {
return this.quotes.size();
}
#Override
public Object getItem(int position) {
return this.quotes.get(position);
}
public long getItemId(int position) {
// We can just return a default value for this adapter
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MiniQuoteView miniQuoteView = new MiniQuoteView(this.context, this.quotes.get(position));
miniQuoteView.setLayoutParams(new ListView.LayoutParams(ListView.LayoutParams.FILL_PARENT, ListView.LayoutParams.WRAP_CONTENT));
return miniQuoteView;
}
public void removeItem(int position) {
this.quotes.remove(position);
}
}
And Finally My XML as the standard listview
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/progressTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/none" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:verticalSpacing="2dp"
android:layout_below="#+id/progressTextView" />
</RelativeLayout>
For some reason my Listview turns out to be empty.
See the image.
As you can see the debugger also has some values for the adapter.
Here are the related MiniQuoteView Class and XML
http://pastebin.com/rRpRA30L
http://pastebin.com/YajCCqdJ

I believe your issue is in the fillData method in your MiniQuoteView class.
Your first if statement is:
if (this.quote == null)
but you do not have an else or else if statement for when the quote object is not null.
Then if you look at your second if statement (which reads the quote data and sets to views) inside your first one, it is:
if (this.quote.name != null)
which will never be true because the quote is null within that if. That is why you are not seeing anything in your list view because nothing is being set to be displayed.
So it should be something like this:
if (this.quote == null) {
// displaying your not available message
} else if (this.quote.name != null){
// your code to display the data
}

Related

ListView not updating properly in Android

I am trying to update the content of my listview by adding stuff to it. Although the listview does update its contents the size still stays the same for some reason. So for example, if the original listview contains A, B, Y, Z and I add C and D to it, the updated list view will be: A, B, C, D. What am I doing wrong?
Here is some relavent code:
//in main activity...
//additionalSongs is an arraylist
addAdditionalSongs(additionalSongs);//add the additional songs to the main list
songTabFragment = new SongTabFragment();//update the list on the screen
...
private void addAdditionalSongs(ArrayList<Song> additionalSongs){
for(int i = 0; i < additionalSongs.size(); i++) {
songList.add(additionalSongs.get(i));
}
}
SongTabFragment class
public class SongTabFragment extends Fragment {
private ListView songView;
private Context context;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.song_tab_layout, container, false);
songView = (ListView) rootView.findViewById(R.id.song_list); //get a reference to the ListView created in song_tab_layout
SongAdapter theAdapter = new SongAdapter(context, MainActivity.getSongArray());
songView.setAdapter(theAdapter); //pass the ListView object the appropriate adapter
return rootView;
}
}
SongAdapter class
public class SongAdapter extends BaseAdapter {
private ArrayList<Song> songArray;
private LayoutInflater songInf;
public SongAdapter(Context c, ArrayList<Song> grabbedSongArray){
songArray = grabbedSongArray;
songInf = LayoutInflater.from(c);
}
#Override
public int getCount() {
return songArray.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout listLayout = (LinearLayout)songInf.inflate(R.layout.song, parent, false);
//layout for each individual song in the list. Uses song.xml
TextView songView = (TextView)listLayout.findViewById(R.id.song_title);
TextView artistView = (TextView)listLayout.findViewById(R.id.song_artist);
Song currentSong = songArray.get(position);
songView.setText(currentSong.getTitle()); //pass data to textView objects in each list item
artistView.setText(currentSong.getArtist());
listLayout.setTag(position); //use the song's position in list as a tag
return listLayout;
}
}
It might be that the SongTabFragment is not being updated. Instead of accessing your song array via the MainActivity
MainActivity.getSongArray()
Why not add a method in your fragment to update the arraylist in the SongAdapter and then notify the list view that the data set has changed so that it will recreate the view based on the new array list.
Example
In fragment class
// Fragment code
public void updateAdapterArray(ArrayList<Songs> adapter) {
((SongAdapter) mListView.getAdapter()).setSongs(adapter);
}
In adapter class
//Adapter code
public void setSongs(ArrayList<Songs> adapter) {
this.songList = adapter;
notifyDataSetChanged();
}
In mainactivity
// your mainactivity code
SongTabFragment songFragment = (SongTabFragment) mFragmentManager.findFragmentById(R.id.fragContainer);
songFragment.updateAdapterArray(newSongList);
Check your getCount() method,
#Override
public int getCount() {
return list.getSize(); //it should return size of list. Not 4
}
Are you updating the item count in your list view? If the listview still only thinks there are 4 items in the list it will only display 4 items. You have to update the value the getCount() returns.

Why is my ListActivity stuck on the /empty element?

I'm trying to use a ListActivity on my Android App but it isn't working the way it should.
Here is my Activity :
public class MainActivity extends ListActivity {
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_terminals_list); //The special layout
TerminalsArrayAdapter adapter = new TerminalsArrayAdapter(this); // A custom adapter
setListAdapter(adapter);
RequestTask task = new RequestTask(adapter); // An Async task
task.execute("/terminals/all");
}
}
Here is my layout :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<TextView
android:id="#android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Loading..." />
</LinearLayout>
Here is my custom adapter :
public class TerminalsArrayAdapter extends ArrayAdapter<String[]> {
private Activity mContext;
private ArrayList<String[]> mObjects = new ArrayList<String[]>();
public TerminalsArrayAdapter(Activity context) {
super(context, R.layout.terminals_listview_item);
this.mContext = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View elementView;
if(convertView==null){
LayoutInflater inflater = mContext.getLayoutInflater();
elementView = inflater.inflate(R.layout.terminals_listview_item, parent);
...
// Some things with my view
} else {
elementView = convertView;
}
...
// Some things with my view
return elementView;
}
public void updateTerminals(ArrayList<String[]> newObject){
mObjects.clear();
mObjects.addAll(newObject);
notifyDataSetChanged();
Log.d("TerminalsArrayAdapter", "Dataset Changed !");
}
}
And here is my Async task :
public class RequestTask extends AsyncTask<String, Void, ArrayList<String[]>>{
private final TerminalsArrayAdapter mAdapter;
public RequestTask(TerminalsArrayAdapter adapter) {
mAdapter = adapter;
}
#Override
protected ArrayList<String[]> doInBackground(String... params) {
...
// retrieve some data from my server
return response;
}
#Override
protected void onPostExecute(ArrayList<String[]> response) {
Log.d("response_server","GOT IT !");
mAdapter.updateTerminals(response);
}
}
As I understood, the ListView will be shown only if the adapter is not empty. If it is empty, it will be the TextView which will be displayed.
This is the way my app should work :
The app creates an empty adapter. This will display the "Loading..." TextView
The app creates a new Async task which will retrieve some needed data from my server
When the Async task finishes, it will call the .updateTerminals() method
This method will update the entries of the custom adapter and call notifyDataSetChanged()
The app should now display the ListView with the freshly retrieved data
The steps 1 to 4 are working fine. The problem occurs on step 5 : Even if the data has been updated, my app doesn't refresh the screen to show me the ListView and stays on the "Loading..." TextView.
I tried to figure out what was wrong with my code, but I wasn't able to. I'd love to hear your suggestions/solutions ! Thanks !
PS: Tell me if you need any thing to understand my issue better.
Your ListView height should be match_parent.
Try to play around with setVisibility(View.GONE) and setVisibility(View.VISIBLE) to:
show TextView & hide ListView
show ListView & hide TextView
public class MainActivity extends ListActivity {
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_terminals_list); //The special layout
// create your list with specific method to be able call her many time
// prefer to create then refresh with new data
CreateList(Passanydata);
RequestTask task = new RequestTask(adapter); // An Async task
task.execute("/terminals/all");
}
}
public void CreateList(ArrayList<String[]> response){
TerminalsArrayAdapter adapter = new TerminalsArrayAdapter(this,response); // A custom adapter
setListAdapter(adapter);
}
#Override
protected void onPostExecute(ArrayList<String[]> response) {
Log.d("response_server","GOT IT !");
// after you got your new data , pass it to your list
CreateList(response);
}
public class TerminalsArrayAdapter extends ArrayAdapter<String[]> {
private Activity mContext;
private ArrayList<String[]> mObjects = new ArrayList<String[]>();
public TerminalsArrayAdapter(Activity context,ArrayList<String[]> objects) {
super(context, R.layout.terminals_listview_item);
this.mContext = context;
// when you have your data it will be able to use it here
this.mObjects = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View elementView;
if(convertView==null){
LayoutInflater inflater = mContext.getLayoutInflater();
elementView = inflater.inflate(R.layout.terminals_listview_item, parent);
...
// Some things with my view
} else {
elementView = convertView;
}
...
// Some things with my view
return elementView;
}
}

Items in ListFragment would not show in Listview using Custom Array Adapter

I am implmenting a Fragment activity that implements ActionBar.TabListener, so I have 3 tabs that each have ListFragments which have a list populated with data obtained through the server. I have been facing this issue for a while now, and I couldn't find an answer no matter how many questions I looked into regarding this particular issue or how many tutorials I looked at in regarding implementing ListFragments with custom array adapters.
The issue I'm having is that I couldn't get the data on the Listview to display on the app. I have managed to obtain the data through the server that I needed to populate the Custom Array Adapter before setting the adapter to the ListView. I even debugged the code and it says that the data is populated in the Adapter as well as in the Listview after making the call to set the array adapter to that Listview. Yet, I couldn't get the data in the Listview to show up in the app. I have been looking into this issue for a while now and I looked into this issue through tutorials and questions posted in forums for any suggestions(Even this one) and I have yet to find anything that has helped me resolve my issue. If anyone could point out on what I did wrong and offer suggestions to fix this issue, I'd gladly appreciate any input.
Code for the ListFragment Activity
public class MyJobsActivity extends ListFragment{
private ArrayList<Job> myJobs;
private static ListView listView;
private static ArrayList<Job> jobList;
ActionBar titleBar;
MyJobsActivity disAllList;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myJobs = (ArrayList<Job>) getArguments().getSerializable(Constants.MYJOBS);
jobList = new ArrayList<Job>();
Job datJob;
for(int i = 0; i < myJobs.size(); i++){
datJob = new Job();
datJob.setJobId(myJobs.get(i).getJobId());
datJob.setJobTitle(myJobs.get(i).getJobTitle());
datJob.setCompany(myJobs.get(i).getCompany());
datJob.setLocation(myJobs.get(i).getLocation());
jobList.add(datJob);
}
MyJobsAdapter datAdapter = new MyJobsAdapter(getActivity(), R.layout.job_row, jobList);
listView.setAdapter(datAdapter);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
try{
Intent datIntent = new Intent(getActivity(),JobActivity.class);
Job job = jobList.get(position);
datIntent.putExtra(Constants.JOBID, job.getJobId());
datIntent.putExtra(Constants.JOBTITLE, job.getJobTitle());
startActivity(datIntent);
}
catch(RuntimeException e){
e.printStackTrace();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.activity_my_jobs, container, false);
listView = (ListView) rootView.findViewById(android.R.id.list);
return rootView;
}
}
XML file for ListFragment Activity
<?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:gravity="center_horizontal"
android:orientation="vertical"
android:background="#FFFFFF">
<ListView
android:id="#android:id/list"
android:drawSelectorOnTop="false"
android:tag="my_jobs"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_width="match_parent" />
</LinearLayout>
Code for the custom array adapter
public class MyJobsAdapter extends ArrayAdapter<Job> {
private Activity activity;
private ArrayList<Job> data;
private HashMap<Integer, Boolean> selection;
private static LayoutInflater inflater=null;
private TextView jobPosition, company, location;
private CheckBox jobChecked;
private View actionView;
private int height, prevSize;
private ActionMode datMode;
public MyJobsAdapter(Activity a, int layoutResourceId, ArrayList<Job> jobs) {
super (a, layoutResourceId, jobs);
this.selection = new HashMap<Integer, Boolean>();
this.activity = a;
this.data = jobs;
}
private class ViewHolder {
TextView jobTitle;
TextView companyName;
TextView location;
}
/*public void setData(ArrayList<Job> d){
data = d;
if(data != null){
for (Job job : d){
add(job);
}
}
this.notifyDataSetChanged();
} */
public void setNewSelection(int position, boolean value){
prevSize = selection.size();
selection.put(position, value);
this.notifyDataSetChanged();
}
public boolean isPositionChecked(int position, boolean value){
boolean result = selection.get(position);
return result == true ? result : false;
}
public void removedSelection(int position){
prevSize = selection.size();
selection.remove(position);
this.notifyDataSetChanged();
}
public void clearSelection(){
prevSize = 0;
selection = new HashMap<Integer, Boolean>();
this.notifyDataSetChanged();
}
#Override
public int getCount() {
return data.size();
}
#Override
public long getItemId(int position) {
return position;
}
public void setMode(ActionMode mode){
datMode = mode;
}
public int getSelectedNumberOfItems(){
return selection.size();
}
public HashMap<Integer, Boolean> getSelectedList(){
return selection;
}
public ArrayList<Job> getData(){
return data;
}
public int getHeight(){
return height;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder jobHolder = null;
Job rowItem = getItem(position);
if(convertView==null){
convertView = inflater.inflate(R.layout.job_row, parent, false);
convertView.setBackgroundResource(R.drawable.list_selector);
jobHolder = new ViewHolder();
jobHolder.jobTitle = (TextView) convertView.findViewById(R.id.Position);
jobHolder.companyName = (TextView) convertView.findViewById(R.id.Company);
jobHolder.location = (TextView) convertView.findViewById(R.id.Location);
convertView.setTag(jobHolder);
} else{
jobHolder = (ViewHolder) convertView.getTag();
}
/* jobPosition = (TextView)vi.findViewById(R.id.Position);
company = (TextView)vi.findViewById(R.id.Company);
location = (TextView)vi.findViewById(R.id.Location);
jobChecked = (CheckBox)vi.findViewById(R.id.JobSelected);
jobChecked.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
StringBuilder lSelectedString = new StringBuilder(selection.size()).append(Constants.SELECTED);
if(isChecked){
setNewSelection(position,true);
datMode.setTitle(lSelectedString.toString());
}
else{
removedSelection(position);
datMode.setTitle(lSelectedString.toString());
if(selection.size() < 1)
datMode.finish();
}
}
});
if(selection.size() == 0){
jobChecked.setVisibility(View.GONE);
}
else{
jobChecked.setVisibility(View.VISIBLE);
jobChecked.setChecked(selection.get(position) == null ? false : true);
}
vi.setBackgroundResource(selection.get(position) == null ? color.white_color : color.holo_blue_bright);
*/
jobHolder.jobTitle.setText(rowItem.getJobTitle());
jobHolder.companyName.setText(rowItem.getCompany());
jobHolder.location.setText(rowItem.getLocation());
return convertView;
}
}
Code for each row in the ListView
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/light_gray"
android:paddingTop="8dip"
android:paddingBottom="8dip"
android:descendantFocusability="blocksDescendants">
<RelativeLayout
android:id="#+id/JobRow"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<CheckBox
android:id="#+id/JobSelected"
android:layout_centerVertical ="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/Position"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/dark_gray_position"
android:layout_toRightOf="#+id/JobSelected"
android:typeface="sans"
android:fontFamily="Roboto Regular"
android:textSize="22sp"
android:paddingLeft="4dip"/>
<TextView
android:id="#+id/Company"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#color/blue_company"
android:textSize="18sp"
android:fontFamily="Roboto Regular"
android:paddingLeft="4dip"
android:layout_below="#+id/Position"
android:layout_toRightOf="#+id/JobSelected"/>
<TextView
android:id="#+id/Location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Company"
android:layout_toRightOf="#+id/JobSelected"
android:paddingBottom="8dip"
android:paddingLeft="4dip"
android:textColor="#color/steel_gray_location"
android:fontFamily="Roboto Regular"
android:textSize="14sp"/>
</RelativeLayout>
</RelativeLayout>
Well there are a few issues you might have with the fragment lifecycle due to the statics in your MyJobsActivity, but as for showing the data itself:
In your MyJobsActivity.onActivityCreated (or wherever you end up associating your custom adapter with the underlying ListFragment), you need to use setListAdapter instead of setAdapter.
From the ListFragment docs (see Binding to Data):
You must use ListFragment.setListAdapter() to associate the list with an adapter. Do not directly call ListView.setAdapter() or else important initialization will be skipped.
To be a bit more clear, one of the many benefits of using/extending a ListFragment is that it will internally handle the binding between your custom adapter and the underlying ListView, but the adapter must be added to the ListFragment itself (i.e., setListAdapter), not on the ListView.
A few other observations:
In fact, unless you need a custom layout, I would recommend completely removing your implementation of onCreateView. This will allow the ListFragment to use its default layout, initialization, and handling for its internal ListView and you'll get (default) handling of an empty list, a loading progress bar, etc. as well.
Given the code you've posted, I would recommend against using a private ListView member in your MyJobsActivity - its parent ListFragment already maintains a copy of the underlying ListView for you, and if you're properly setting the adapter via setListAdapter, you don't need the explicit object (and if you do, use ListFragment's getListView()).
Regardless, if my own trials and challenges are any indication, the static ListView and ArrayList members will most certainly cause you grief when the fragment is destroyed and recreated (on orientation change, on restore of your app from the Recents list if the process has been torn down in the interim, etc.).

Xamarin android: How to get GridView Data Source in android like asp.net

I have a WebService which return user details like User Name, its Date of Birth and Address. I am calling this web service to my android application developed Xamarin c#. But don't know how to show data (bind data) in Grid View. can some one provide sample code or explain how to show data in Grid View.
What you need to do, is to create an adapter for the GridView and axml layout (the view of the components in the GridView). For example, suppose that you want to make a GridView of Tiles with blue background and with a text at the left bottom corner with white color:
tile.axml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tile_layout"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="#0000FF">
<TextView
android:id="#+id/tile_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:paddingLeft="6dp"
android:paddingBottom="2dp"
android:textColor="#ffffff" />
</RelativeLayout>
TileAdapter.cs
public class TileAdapter : BaseAdapter<BaseTileItem>
{
protected Activity _context = null;
protected List<BaseTileItem> _tileList = new List<BaseTileItem>();
public TileAdapter(Activity context, List<BaseTileItem> tileList)
: base()
{
this._context = context;
this._tileList = tileList;
}
public override BaseTileItem this[int position]
{
get { return this._tileList[position]; }
}
public override long GetItemId(int position)
{
return position;
}
public override int Count
{
get { return this._tileList.Count; }
}
/// Inflates the Tile layout and sets the values
public override Android.Views.View GetView(int position, Android.Views.View convertView, Android.Views.ViewGroup parent)
{
// Get our object for this position
var item = this._tileList[position];
//Try to reuse convertView if it's not null, otherwise inflate it from our item layout
var view = (convertView ??
this._context.LayoutInflater.Inflate(
Resource.Layout.tile,
parent,
false)) as RelativeLayout;
// Find references to each subview in the list item's view
TextView itemText = view.FindViewById<TextView>(Resource.Id.tile_text);
//Assign this item's values to the various subviews
itemText.Text = this._tileList[position].Text;
//Finally return the view
return view;
}
}
}
TileBaseItem.cs
//This is what you retrieve from the webservice
public class BaseTileItem
{
private string _text;
public BaseTileItem(string text)
{
this._text = text;
}
public string Text {
get {return this._text; }
set { this._text = value; }
}
And then in your activity :
private List<BaseTileItem> _usersList;
private TileAdapter _usersAdapter;
private GridView _usersGridView;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
this.SetContentView(Resource.Layout.startactivity);
//inflate all views
InflateViews();
this._usersList = //populate the list with BaseTileItem items
this._usersAdapter = new TileAdapter(this, this._usersList);
//creating the GridView
this._usersGridView = new GridView(this);
this._usersGridView.SetNumColumns(2);
this._usersGridView.SetGravity(GravityFlags.Center);
this._usersGridView.SetPadding(0, 20, 0, 20);
this._usersGridView.SetVerticalSpacing(20);
this._usersGridView.Adapter = this._usersAdapter;
}

Android listview item doesn't appear

I should write in the title instead of 'doesn't work' something like 'I
don't know how to do it' but the first version feels better :).
What I am trying to do is the following:
Download the xml from the web, parse it and create ArrayList of some
objects (done and working)
Display the objects using custom Adapter (doesn't work)
The second one works if I add the items to my ArrayList before I add it to
the view using
m_orderAdapter = new OrderAdapter(this,m_orders); //code for orderadapter
below
setListAdapter(m_orderAdapter);
I have found on the web something like this: (in my onCreate method)
handler = new Handler();
viewOrders = new Runnable(){
#Override
public void run() {
getOrders();
}
};
new Thread(){
#Override
public void run(){
handler.post(viewOrders);
}
}.start();
then, the following code for the methods:
private void getOrders(){
try{
OrderManager om = new OrderManager();
m_orders = om.getOrdersFromWeb();
Log.i("ARRAY", ""+ m_orders.size());
} catch (Exception e) {
Log.e("BACKGROUND_PROC", e.getMessage());
}
runOnUiThread(returnRes);
}
OrderManager downloads and parse the xml into Order objects and returns
array list of those. Then I set this list to my member array list m_orders.
Once downloading and parsing is done I run returnRes method on the ui thread
using runOnUiThread method
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if(m_orders != null && m_orders.size() > 0){
Log.i("ORDER",m_orders.get(0).getOrder_id());
setListAdapter(m_orderAdapter);
m_orderAdapter.notifyDataSetChanged();
}
m_orderAdapter.notifyDataSetChanged();
}
};
and I call notifyDataSetChanged() on my adapter.
The view I do all this stuff extends ListView and the code for the adapter
itself is listed below:
public class OrderAdapter extends BaseAdapter{
private Context ctx;
private List<Order> orders;
public OrderAdapter(Context ctx, List<Order> orderLst){
this.ctx = ctx;
this.orders = orderLst;
}
#Override
public int getCount() {
return orders.size();
}
#Override
public Object getItem(int pos) {
return orders.get(pos);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Order o = orders.get(position);
return new OrderListAdapterView(this.ctx,o);
}
}
When I debug I have the data inside my m_orders list but when I call
notifyDataSetChanged nothing happens, I've read that I have to execute that
on the UI thread which I think I do. So whats the problem ?
any help highly appreciated, or maybe just a link to the nice tutorial on
the web explaining this issue on how to update the list view at runtime ?
Hey Arutha - why don't you see my answer for this post - I think it is what you need.
Or just let me repost it here
You can extend ArrayAdapter. Here's code example for you. In this example - SearchItem is some custom POJO. Basically you need to override getView() method to build your row by inflating row layout and then populating values based on List of items and current position
class SearchItemsAdapter extends ArrayAdapter<SearchItem> {
Activity context;
List<SearchItem> items;
SearchHeader header;
#SuppressWarnings("unchecked")
public SearchItemsAdapter(final Activity context,
final Map<SearchHeader, List<SearchItem>> result) {
super(context, R.layout.item, (List) ((Object[]) result.values()
.toArray())[0]);
this.context = context;
this.header = result.keySet().iterator().next();
this.items = result.get(this.header);
}
#Override
public View getView(final int position, final View convertView,
final ViewGroup parent) {
final View view = this.context.getLayoutInflater().inflate(
R.layout.item, null);
final SearchItem item = this.items.get(position);
((TextView) view.findViewById(R.id.jt)).setText(item.jt);
((TextView) view.findViewById(R.id.dp)).setText(item.dp);
((TextView) view.findViewById(R.id.cn)).setText(item.cn);
((TextView) view.findViewById(R.id.loc)).setText(item.loc.name);
final TextView body = ((TextView) view.findViewById(R.id.e));
body.setText(item.e);
body.setTag(item.src[0]);
((TextView) view.findViewById(R.id.src)).setText(item.src[1]);
return view;
}
}

Categories

Resources