簡體   English   中英

我如何使用列表<data>並將其傳遞給另一個類

[英]How can i use List<data> and pass it to another class

我在 TweetAdapter.java 中創建了一個自定義適配器。 我已經把代碼寫成

公共類 TweetAdapter 擴展 ArrayAdapter {

private List<Tweet> tweets;
private Context context;
public TweetAdapter(TweetListActivity ctx, List<Tweet> tweets) {
    super(ctx, R.layout.row_tweet, tweets);
}

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

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;
    if (v == null) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.row_tweet, parent);
    }
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
    TextView tweetTitle = (TextView) v.findViewById(R.id.tweetTitle);
    TextView tweetBody = (TextView) v.findViewById(R.id.tweetBody);
    final Tweet currentTweet = tweets.get(position);
    String a = currentTweet.getTitle();
    String b = currentTweet.getBody();
    tweetTitle.setText(a);
    tweetBody.setText(b);
    return v;
}

}

但得到錯誤

java.lang.NullPointerException:嘗試在空對象引用上調用虛擬方法“java.lang.Object android.content.Context.getSystemService(java.lang.String)”

在 android.view.LayoutInflater.from(LayoutInflater.java:219)

看起來您的context變量為空,因為它從未被設置。

嘗試將您的構造函數修改為:

public TweetAdapter(TweetListActivity ctx, List<Tweet> tweets) {
    super(ctx, R.layout.row_tweet, tweets); 
    context=ctx;
}

解決了

實施的

導入 java.io.Serializable;

在 Tweet.java 中

檢查此鏈接是否對您有幫助:

https://github.com/codelearn-org/CodelearnTwitterApp/blob/master/src/org/codelearn/twitter/TweetAdapter.java

這是相關部分:

public class TweetAdapter extends ArrayAdapter<Tweet> {

     private LayoutInflater inflater;
     private List<Tweet> tweetsLocal;

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

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM