getApplicationContext() throws an exception when u

2020-04-19 06:57发布

问题:

I've specified a class, based on another one in an existing Android project. The addRow() method is supposed to dynamically add rows to a table. When creating a new TextView to add to my row and also when creating that row, I'm supposed to specify the "context". The current way, trying "getApplicationContext()" throws a NullPointerException. So where am I supposed to get that context from?

public class DistanceTableView extends ContactListActivity
{
    public void addRow(LocationMessage locationMsg){
        View messageView = theInflater.inflate(R.layout.homepage, null);
        TableLayout table = (TableLayout)messageView.findViewById(R.id.distanceTable);

        TextView senderNameTextView = new TextView(getApplicationContext());
        senderNameTextView.setText(locationMsg.getSenderName());

        TableRow tr = new TableRow(getApplicationContext());
        tr.addView(distanceTextView);
        table.addView(tr);

        rows.addFirst(messageView);
    }
}

The class that my view is extending:

public class ContactListActivity extends MapActivity implements
        ConnectionListener {}

回答1:

I guess you have to pass the context to the constructor of your class.



回答2:

Try this instead:

TableRow tr = new TableRow(this);