Android GridView

Status
Not open for further replies.
I constructed a GridView with an adapter that gets data from an array of maps, and its getView returns a LinearLayout after filling in the objects in it. The grid behaves like this: first, it fills all the entries from 0 to getCount. Then it queries item 0, adding it to the end. Then it queries all items, including 0, AGAIN. So it ends up like so:
Code:
0
1
2
0
0
1
2

WTF? Actually, this is not the first WTF I've had with Android, but I generally managed to find a workaround. Not today, though.
 

Mile Zero

Ars Praetorian
578
Subscriptor++
Watch the ListView video from Google I/O. It addresses some of these questions:

http://code.google.com/events/io/2010/s ... droid.html

Short answer: without seeing your code, I can't be sure, but it looks like you're hooking into getView() in a way that's trying to outsmart the library. The Android layout manager may often call getView() in order to determine sizing, then throw away the results--the pattern you've shown is consistent with that kind of behavior. If you try to store or cache the results of getView(), then interpret from the cache on the assumption that the adapter was called in contiguous ascending order, bad things happen.

Can you post your Adapter code? It might be easier to help from that. Your description of what you're doing--returning a linear layout into a grid view--is kind of weird, and I don't think I really understand.
 
TL;DR: I create a Dialog, assign it a layout, extract the top-level view, manipulate it, and return it. If convertView is supplied, I return that.

Why create a dialog? Because I got an error when I tried getLayoutInflater().inflate(resource, root); If you could help me with that, I would appreciate that, too.

Code:
        ListAdapter adapter = new BaseAdapter()
        {
            byte show = 0;

            public int getCount()
            {
                return mylist.size();
            }

            public Object getItem(int pos)
            {
                return mylist.get(pos);
            }

            public long getItemId(int pos)
            {
                return mylist.get(pos).hashCode();
            }

            public View getView(int pos, View convertView, ViewGroup parent)
            {
                if (convertView != null)
                {
                    return convertView;
                }
                Dialog d = new Dialog(*Class name*.this); //I tried and failed to use LayoutInflater
                d.setContentView(R.layout.row);
                View out = d.findViewById(R.id.callHistoryLayout);

                out.setLayoutParams(//has to be the gridview kind, or it crashes
                        new GridView.LayoutParams(out.getLayoutParams()));

                TextView *var1* = (TextView) out.findViewById(R.id.*var1*);
                fromCall.setText(mylist.get(pos).get("*var1*"));
                if (pos == 0)
                {
                    *var1*.setTypeface(Typeface.DEFAULT_BOLD, Typeface.BOLD);
                }

                TextView *var2* = (TextView) out.findViewById(R.id.*var2*);
                *var2*.setText(mylist.get(pos).get("*var2*"));
                if (pos == 0)
                {
                    *var2*.setTypeface(Typeface.DEFAULT_BOLD, Typeface.BOLD);
                }

                TextView *var3* = (TextView) out.findViewById(
                        R.id.*var3*);
                *var3*.setText(mylist.get(pos).get("*var3*"));
                if (pos == 0)
                {
                    *var3*.setTypeface(Typeface.DEFAULT_BOLD, Typeface.BOLD);
                }

                return out;
            }
        };
 

Mile Zero

Ars Praetorian
578
Subscriptor++
Okay, so here's the thing. Your code, as is, does the following things with every call to getView():

1. Instantiates a new dialog, using a row (?) layout from your resources.
2. finds a sub-view inside that dialog, and sets its layout parameters.
3. Finally, runs through your data to populate the sub-view.

1 and 2 are unnecessary (and expensive), especially since (as the video mentions) the framework may call getView() several times for measurement purposes only. Removing those two steps entirely will wildly simplify the process of 3, and make your life a lot easier.

Here's the entire code I used for a simple list adapter:

Code:
public View getView(int position, View convertView, ViewGroup parent) {
                View row = super.getView(position, convertView, parent);
                View tag = row.findViewById(R.id.colorstrip);
                c.moveToPosition(position);
                //On every other row, we're going to add a slight grey tint.
                //In the light theme, this darkens it, and in the black theme it lightens it.
                //If we used custom colors, this should still work over an arbitrary list background.
                //This stripe effect could be made optional pretty easily.
                if (position % 2 == 1) {
                        row.setBackgroundColor(0x20808080);
                } else {
                        row.setBackgroundColor(0x00FFFFFF);
                }
                tag.setBackgroundColor(c.getInt(DB_COLOR));
                return row;
        }

You will note that mine is a lot simpler than yours. That's because all mine does is worry about returning a view with data filled in. The other stuff is up to the framework that calls the Adapter.

If I were you, I'd instantiate the dialog separately, setContentView() to a ListView-based layout, and then set that ListView's adapter to your adapter class. That's a lot simpler, it avoids instantiating/parsing a bunch of unused dialogs, and it will take advantage of the heavy optimizations in the framework for populating views from an adapter.
 
I don't get it. super.getView is abstract. What superclass are you using?

"If I were you, I'd instantiate the dialog separately, setContentView() to a ListView-based layout, and then set that ListView's adapter to your adapter class. That's a lot simpler, it avoids instantiating/parsing a bunch of unused dialogs, and it will take advantage of the heavy optimizations in the framework for populating views from an adapter."

???
 

Mile Zero

Ars Praetorian
578
Subscriptor++
See for yourself:

http://code.google.com/p/android-underg ... round.java

I'm subclassing SimpleCursorAdapter. I don't remember why I initially decided that--probably I found something in the SDK that made it seem like a good idea. But it's nice to be able to rely on super.getView() to properly handle returning the convertView for me.

edit: I remember now, I'm using a subclass of SimpleCursorAdapter because my view is database-backed. The SQLiteHelper returns a cursor for its queries, so that was a natural fit.


Guess that was confusing. Here's some quick, off-the-top-of-my-head code for what I said:

Code:
Dialog d = new Dialog();
d.setContentView(R.layout.dialogListView);
ListView lv = d.findViewById(R.id.dialogListView);
lv.setAdapter(new DialogListAdapter());
d.show();

private class DialogListAdapter extends BaseAdapter {
	
	public View getView(int position, View convertView, ViewGroup parent) {
		View row;
		if (convertView != null) {
			row = convertView;
		} else {
			//inflate your row layout from XML
		}
		TextView text = (TextView) row.findViewById(R.id.textView1);
		text.setText(myList.get(position));
		return row;
	}

}

So we create a dialog, give it a ListView layout, and set the ListView's adapter to our private class. Now it'll populate itself.

The idea of View Adapters on Android is that you shouldn't ever need to worry about laying something out yourself from data. You just provide a function that translates from your data into a completed View, and the framework takes care of putting it into the container.
 
Mile Zero":1vwo97r6 said:
Okay, you can skip that part, then, and just set the adapter for the GridView to an instance of your private class, as I did with the dialog's ListView. Sorry, I misunderstood. Using a dialog to unpack your layouts is Not Recommended.

What was the error that got thrown when you tried using LayoutInflater? Let's work from there.

UnsupportedOperationException: "addView(View, LayoutParams) is not supported in AdapterView"
 

Mile Zero

Ars Praetorian
578
Subscriptor++
Tiiba":2b839l2n said:
Mile Zero":2b839l2n said:
Okay, you can skip that part, then, and just set the adapter for the GridView to an instance of your private class, as I did with the dialog's ListView. Sorry, I misunderstood. Using a dialog to unpack your layouts is Not Recommended.

What was the error that got thrown when you tried using LayoutInflater? Let's work from there.

UnsupportedOperationException: "addView(View, LayoutParams) is not supported in AdapterView"

Add a third parameter, false, to your inflate() call. That will tell it to just use the provided viewgroup only for layout params, not as a parent view.
 

Mile Zero

Ars Praetorian
578
Subscriptor++
Well, I just noticed this from your code, but you shouldn't just return convertView. The point of it is that it saves you time inflating XML, not provides the exact view you need. You still need to put information into it. So changing your code to fit that:

Code:
public View getView(int pos, View convertView, ViewGroup parent)
            {
                LinearLayout out;
                if (convertView != null)
                {
                    out = convertView;
                } else {
                    out = //inflate from XML
                }
                TextView *var1* = (TextView) out.findViewById(R.id.*var1*);
                fromCall.setText(mylist.get(pos).get("*var1*"));
                if (pos == 0)
                {
                    *var1*.setTypeface(Typeface.DEFAULT_BOLD, Typeface.BOLD);
                }

                TextView *var2* = (TextView) out.findViewById(R.id.*var2*);
                *var2*.setText(mylist.get(pos).get("*var2*"));
                if (pos == 0)
                {
                    *var2*.setTypeface(Typeface.DEFAULT_BOLD, Typeface.BOLD);
                }

                TextView *var3* = (TextView) out.findViewById(
                        R.id.*var3*);
                *var3*.setText(mylist.get(pos).get("*var3*"));
                if (pos == 0)
                {
                    *var3*.setTypeface(Typeface.DEFAULT_BOLD, Typeface.BOLD);
                }

                return out;
            }

Does that help?
 
I need a bit of help again. When the list scrolls, all entries go black, and stay black until something is clicked. What could possibly be the cause of this?

Here, in fact, is a complete program:

Code:
<?xml version="1.0" encoding="UTF-8"?>
<ListView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF"
    android:id="@+id/lv">
</ListView>

package org.me.androidapplication1;

import android.app.*;
import android.os.*;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity
{
    @Override
    public void onCreate(Bundle icicle)
    {
        try
        {
            super.onCreate(icicle);
            setContentView(R.layout.main);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 100; i++)
            {
                sb.append(i + "\n");

            }
            ((ListView) findViewById(R.id.lv)).setAdapter(new BaseAdapter()
            {
                public int getCount()
                {
                    return 100;
                }

                public Object getItem(int i)
                {
                    return i;
                }

                public long getItemId(int i)
                {
                    return i;
                }

                public View getView(int pos, View v, ViewGroup parent)
                {
                    if (v == null)
                    {
                        v = new TextView(MainActivity.this);
                    }
                    ((TextView) v).setText("" + pos);
                    return v;
                }
            });
        }
        catch (Exception e)
        {
            finish();
        }
    }
}
 
Status
Not open for further replies.