Reinhard Armstrong
Reinhard Armstrong

Reputation: 99

Add value to array in Android

I have class named as login (without encapsulate fields, I just want to make it simple)

public class login
{
    String username;
    String password;

    public login(String username, String password)
    {
        this.username = username;
        this.password = password;
    }
}

DisplayList.java

public class DisplayList extends ListActivity
{
    login[] values;

    protected void onCreate(Bundle savedInstanceState)
    {
        String username, password;
        int count = 0;
        while (count < somelength)
        {
            username = somestring;
            password = somestring;

            values[count] = new login(username, password);

            //if I Toast it
            //Toast.makeText(this, username + " . " + password, Toast.LENGTH_SHORT).show();

            count++;
        }

        login_adapter = new login_adapter(this, values);
        setListAdapter(login_adapter);
    }
}

I want to pass values (login[]values) to login_adapter (class login_adapter extends ArrayAdapter)

but I always come with NullPointerException on "values[count] = new login(username, password);"

if I Toast it "Toast.makeText(this, username + " . " + password, Toast.LENGTH_SHORT).show();" the Toast come with all values.

Upvotes: 1

Views: 1400

Answers (2)

Pavneet_Singh
Pavneet_Singh

Reputation: 37414

Use somelength to initialize your array ,because you are traversing in loop equal to the size of somelength and creating an object of login every time so

public class DisplayList extends ListActivity
{
    login[] values;

    protected void onCreate(Bundle savedInstanceState)
    {
        String username, password;
        int count = 0;

        values = new longin[somelength];
        // ^^^^   initialize your array 

        while (count < somelength)
        {
            username = somestring;
            password = somestring;
            values[count] = new login(username, password);
            count++;
        }
        login_adapter = new login_adapter(this, values);
        // make sure the login_adapter class name and object name is different            
        setListAdapter(login_adapter);
    }
}

For convention you can rename classes to login => Login ,login_adapter=> LoginAdapter

Upvotes: 2

firegloves
firegloves

Reputation: 5709

You are not initializing your array. You need something like this at start of onCreate:

values = new login[2];

Note that for convention class names must start with uppercase carachter.

I suggest you to use ArrayList so you don't need to know array length at creation time

Upvotes: 0

Related Questions