【问题标题】:Refresh listview with new JSON objects?用新的 JSON 对象刷新列表视图?
【发布时间】:2014-10-05 06:15:13
【问题描述】:

我的列表视图旨在直接从 JSONArray 添加结果。有什么办法可以让它只添加列表视图中不存在的项目?我正在使用自定义适配器。

getTweets AsyncTask

public class getTweets extends AsyncTask<Void, Void, Void>{

    int counter;

    @Override
    protected Void doInBackground(Void... params) {
        BufferedReader reader =null;
        // TODO Auto-generated method stub
        try{
            HttpClient hc = new DefaultHttpClient();
            HttpGet get = new HttpGet("https://api.twitter.com/1.1/statuses/home_timeline.json?count=40");
            ParseTwitterUtils.getTwitter().signRequest(get);
            HttpResponse rp = hc.execute(get);
            String result2 = EntityUtils.toString(rp.getEntity());
            JSONArray array = new JSONArray(result2);
            for(int i=0; i < array.length(); i++){
                JSONObject session = array.getJSONObject(i);
                JSONObject profilePic = session.getJSONObject("user");
                addTweet(profilePic.getString("name"),profilePic.getString("screen_name"),session.getString("text"),profilePic.getString("profile_image_url"));
            }
            }catch (Exception e) {
           Log.e("TwitterFeedActivity", "Error loading JSON", e);

}
        return null;

    }
    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        tweetListView.setAdapter(tweetAdapter);
        return;
   }


}
public void addTweet(String user,String mentionname,String tweet,String profile_picture){
    tweetAdapter.add(new TweetList(user,mentionname, tweet,profile_picture));
}

ListView 适配器

public class TweetArrayAdapter extends ArrayAdapter<Object> {

    private TextView tweet,twitterUser,twitterMention;
    ImageView profile_picture;
    private List<TweetList> tweetList = new ArrayList<TweetList>();


    public void add(TweetList object) {
        tweetList.add(object);
        super.add(object);
    }

    public TweetArrayAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
    }

    public int getCount() {
        return this.tweetList.size();
    }

    public TweetList getItem(int position) {
        return this.tweetList.get(position);
    }

    @SuppressLint("ViewHolder")
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;

            LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.tweet_list_item, parent, false);
            twitterUser = (TextView)row.findViewById(R.id.display_name);
            tweet = (TextView) row.findViewById(R.id.display_tweet);
            twitterMention = (TextView)row.findViewById(R.id.display_twitter_mentionname);
            profile_picture = (ImageView)row.findViewById(R.id.profile_picture);

            TweetList tweetMessageObj = getItem(position);
            SpannableString hashtag = new SpannableString(tweetMessageObj.tweet);
            Matcher matcher = Pattern.compile("@([A-Za-z0-9_-]+)").matcher(hashtag);
            Matcher matcher2 = Pattern.compile("#([A-Za-z0-9_-]+)").matcher(hashtag);
            while (matcher.find())
            {
                hashtag.setSpan(new ForegroundColorSpan(Color.rgb(79, 120, 216)), matcher.start(), matcher.end(), 0);
                hashtag.setSpan(new ClickableSpan() {

                    @Override
                    public void onClick(View widget) {
                        // TODO Auto-generated method stub
                         TextView tv = (TextView)widget;
                         String tags = tv.getText().subSequence(tv.getSelectionStart(),tv.getSelectionEnd()).toString();
                         Toast.makeText(getActivity(), tags,  Toast.LENGTH_LONG).show();
                    }
                    public void updateDrawState(TextPaint ds) {// override updateDrawState
                           ds.setUnderlineText(false); // set to false to remove underline
                        }
                },matcher.start(), matcher.end(), 0);
            }
            while (matcher2.find())
            { hashtag.setSpan(new ForegroundColorSpan(Color.rgb(79, 120, 216)), matcher2.start(), matcher2.end(), 0);
                hashtag.setSpan(new ClickableSpan() {

                    @Override
                    public void onClick(View widget) {
                        // TODO Auto-generated method stub
                        TextView tv = (TextView)widget;
                         String tags = tv.getText().subSequence(tv.getSelectionStart(),tv.getSelectionEnd()).toString();
                         Toast.makeText(getActivity(), tags,  Toast.LENGTH_LONG).show();
                    }
                    public void updateDrawState(TextPaint ds) {// override updateDrawState
                           ds.setUnderlineText(false); // set to false to remove underline
                        }
                },matcher2.start(), matcher2.end(), 0);
            }
            tweet.setText(hashtag, BufferType.SPANNABLE);
            tweet.setMovementMethod(LinkMovementMethod.getInstance());
            tweet.setHighlightColor(Color.TRANSPARENT);
            Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), "fonts/light.ttf");
            tweet.setTypeface(tf);
            Typeface tf2 = Typeface.createFromAsset(getActivity().getAssets(), "fonts/bold.ttf");
            twitterUser.setText(tweetMessageObj.twittername);
            twitterUser.setTypeface(tf2);
            twitterMention.setText("@" + tweetMessageObj.mentionname);
            Picasso.with(getActivity()).load(tweetMessageObj.pictureURL).resize(400,400).into(profile_picture);
        return row;
    }


}

推文列表

public class TweetList {
    public String twittername,mentionname,tweet,pictureURL;



    public TweetList(String twittername,String mentionname,String tweet,String pictureURL) {
        super();
        this.twittername = twittername;
        this.tweet = tweet;
        this.pictureURL = pictureURL;
        this.mentionname = mentionname;


    }

}

【问题讨论】:

    标签: android json listview twitter custom-adapter


    【解决方案1】:

    我能想到的就是再弄一个ArrayList,

        ArrayList<String> mArrayList = new ArrayList<String>();
    

    然后同时添加过滤,

        for (int i = 0; i < array.length(); i++) {
            JSONObject session = array.getJSONObject(i);
            JSONObject profilePic = session.getJSONObject("user");
            if (mArrayList.contains(profilePic.getString("name"))) {
                mArrayList.add(profilePic.getString("name"));
                addTweet(profilePic.getString("name"),
                        profilePic.getString("screen_name"),
                        session.getString("text"),
                        profilePic.getString("profile_image_url"));
            }
        }
    

    您可以在这些行中过滤您想要的任何字符串参数,

                if (mArrayList.contains(profilePic.getString("name")))
                mArrayList.add(profilePic.getString("name"));
    

    【讨论】:

    • 效果很好,但由于某种原因,它会将新的添加到底部。有什么线索吗?
    • 你想在哪里添加新的??或者,如果您不想要以前的数据,则清除异步类的 onpreExecute 方法的适配器和数组列表。
    • 我希望新数据加载到列表视图的最顶部,同时保留以前的数据。
    • 疯狂的想法但是,尝试使用反向 for 循环意味着长度为 0。或者为什么不按顺序从服务器发送数据。
    猜你喜欢
    • 1970-01-01
    • 2011-08-31
    • 2011-03-18
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多