简体   繁体   中英

pass list<data> to custom adapter

I have created a list for custom adapter by writing following code:

public class TweetListActivity extends ListActivity {

private ListView tweetListView;
private ArrayAdapter tweetItemArrayAdapter;
private final List<Tweet> tweets = new ArrayList<Tweet>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tweet_list);
    for (int i = 1; i < 21; i++)

    {
        Tweet tweet = new Tweet();
        tweet.setTitle("A nice header for Tweet # " + i);
        tweet.setBody("Some random body text for the tweet # " + i);
        tweets.add(tweet);
    }
    tweetItemArrayAdapter = new TweetAdapter(this,tweets);

    setListAdapter(tweetItemArrayAdapter);
}
}

code for TweetAdapter is as below

public class TweetAdapter extends ArrayAdapter<Tweet> 
{
    private List<Tweet> tweetslocal;
    private Context context;
    private LayoutInflater inflater;

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

@Override
public Tweet getItem(int arg0) {
    return tweetslocal.get(arg0);
}

@Override
public long getItemId(int arg0) {
    return arg0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = inflater.inflate(R.layout.row_tweet, parent, false);
    TextView tweetTitle = (TextView) row.findViewById(R.id.tweetTitle);
    Tweet tweet = tweetslocal.get(position);
    tweetTitle.setText(tweet.getTitle());
    TextView tweetBody = (TextView) row.findViewById(R.id.tweetBody);
    tweetBody.setText(tweet.getBody());
    return row;
}
}

But, I am not getting the desired output. The list is showing all tweets with header 20 instead of increamental tweets from tweet1 to tweet 20.

Looking at your code I see you already pass on the list of tweets to your TweetAdapter .

In TweetAdapter , declare a list of Tweet 's:

    private List<Tweet> tweets;

Then, make sure your constructor looks like this:

    public TweetAdapter(Context ctx, List<Tweet> tweets) {
        this.context = ctx; //Context == activity
        this.tweets = tweets;
    }

Now, in your getView() , you can do this:

final Tweet currentTweet = tweets.get(position);

Hope this helped!

Get tweets object like this if the array named tweets in your TweetAdapter:

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

    Tweet tweet = tweets.get(position);
    // TODO using tweet.
}

Do you mean this?

solved

implemented

import java.io.Serializable;

in Tweet.java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM