Bruno
Bruno

Reputation: 11

Unable to correctly use .setLayoutParams(...) - Android

I wanted to try using a database on Android, so I made a small app that allows you to add contacts to the database and then it displays them.

I have been able to display contacts (from the database) if I create the layout in XML and then edit the text field in code. But I wanted to build the layouts in code so I can add as many contacts as I want.

The following code is the method I use to create the layout and the app crashes whenever I make it run this code. My guess is that there is a problem with the parameters. If only type LayoutParams.MatchContent, it asks me to import and it gives me many options, and that’s why it says LinearLayout.LayoutParams...;

I add the resulting layout to a LinearLayout.

private LinearLayout createContactView (Contact contact) {
    LinearLayout contactInfoWrapper = new LinearLayout(this);
    contactInfoWrapper.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    contactInfoWrapper.setOrientation(LinearLayout.VERTICAL);

    TextView nameView = new TextView(this);
    nameView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    nameView.setText(contact.getName());
    contactInfoWrapper.addView(nameView);

    TextView numberView = new TextView(this);
    numberView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    numberView.setText(contact.getPhoneNumber());
    contactInfoWrapper.addView(numberView);

    return contactInfoWrapper;
}

Upvotes: 1

Views: 104

Answers (2)

Knossos
Knossos

Reputation: 16038

Instead of using setLayoutParams, use the LayoutParams in the addView(View v, LayoutParams params) method of your LinearLayout:

TextView nameView = new TextView(this);
nameView.setText(contact.getName());
contactInfoWrapper.addView(nameView, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

Upvotes: 1

Yadu CR
Yadu CR

Reputation: 25

Change the line

numberView.setText(contact.getPhoneNumber());

to this:

numberView.setText(String.valueOf(contact.getPhoneNumber()));

Upvotes: 0

Related Questions