• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Trying to Make ListView (new developer)

Twan

Lurker
I'm just trying to spit out a ListView based on the Strings in an ArrayList of mine. I'm getting a NullPointerException.

Code:
package org.me.mixtapes;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author achuinard
 */
public class MixTape extends Activity {

    /** Called when the activity is first created. */


    private Button generator;
    private LinearLayout myLayout;
    private List<String> urlList = new ArrayList<String> ();
    private TextView tempTextView;
    private ListView songList;
    private List<TextView> textViews  = new ArrayList<TextView>();
    private AttributeSet textViewAttr;
    private AlertDialog alerter;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        songList = (ListView) findViewById(R.id.songlist);
        urlList.add("http://1.com");
        urlList.add("http://2.com");
        urlList.add("http://3.com");
        urlList.add("http://4.com");
        // setContentView(R.layout.main);

        // grab display elements
        // generator = (Button) findViewById(R.id.generate);
        
        myLayout = new LinearLayout(this);
        for (String url : urlList) {
            tempTextView = new TextView(this);
            tempTextView.setText(url);
            textViews.add(tempTextView);

        }

        for (TextView t : textViews) {
            songList.addFooterView(t);
        }
        
        myLayout.addView(songList);
        setContentView(myLayout);
    }

}
 
Twan,

I think you're going about this the wrong way. You should take a look at the Android ListView tutorial. ListViews are much easier than you think.

The code that should handle what you're intending to do should be fairly small. Something like:
Code:
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        
        songList = (ListView) findViewById(R.id.songlist);
        
        urlList.add("http://1.com");
        ...
        
        songList.setAdapter(new ArrayAdapter(this, R.layout.row, R.id.text1, urlList);
    }
The only thing that I really added was the ArrayAdapter which tells the ListView what the contents of each row will be. What I'm not showing you is that you need to create another layout file called "row.xml", and it should have a TextView with an id of "text1".

--Boogs
 
Back
Top Bottom