Barry the Beginner
Barry the Beginner

Reputation: 31

CodeLearn Twitter Tutorial nullpointer error on TweetAdapter.java

I'm currently doing the Codelearn Twitter tutorial but I'm getting a null pointer in my code below - can someone please help me?

public class TweetAdapter extends ArrayAdapter<Tweet> {

private LayoutInflater inflater;
private ArrayList<Tweet> tweetsList;

 public TweetAdapter(Activity activity, List<Tweet> tweets) {
     super(activity, R.layout.row_tweet, tweets);
     tweetsList = (ArrayList<Tweet>) tweets;
     inflater = activity.getWindow().getLayoutInflater();
}

@Override
 public View getView(int position, View convertView, ViewGroup parent){

    Tweet t = tweetsList.get(position);

    ***TextView title = (TextView) convertView.findViewById(R.id.tweetTitle);***
    TextView body = (TextView) convertView.findViewById(R.id.tweetBody);

    title.setText(t.getTitle());
    body.setText(t.getBody());

    return inflater.inflate(R.layout.row_tweet, parent, false);
    }

}

Upvotes: 2

Views: 140

Answers (1)

Apoorv
Apoorv

Reputation: 13520

Your convertView can be null. There is no guarantee that it will be non null. If there is no old view to reuse it will be null

Change

public View getView(int position, View convertView, ViewGroup parent)
{

Tweet t = tweetsList.get(position);

***TextView title = (TextView) convertView.findViewById(R.id.tweetTitle);***
TextView body = (TextView) convertView.findViewById(R.id.tweetBody);

title.setText(t.getTitle());
body.setText(t.getBody());

return inflater.inflate(R.layout.row_tweet, parent, false);
}

to

public View getView(int position, View convertView, ViewGroup parent)
{
  if(convertView==null)
    convertView = inflater.inflate(R.layout.row_tweet, parent, false);

  Tweet t = tweetsList.get(position);

  ***TextView title = (TextView) convertView.findViewById(R.id.tweetTitle);***
  TextView body = (TextView) convertView.findViewById(R.id.tweetBody);

  title.setText(t.getTitle());
  body.setText(t.getBody());

  return convertView;
}

You have to check whether convertView is non null or not and if it is null you need to inflate your layout in it.

You should also take a look at ViewHolder pattern

Upvotes: 1

Related Questions