Android模仿新浪微博(主页微博,评论界面)
来源:互联网 发布:怎样增加淘宝账号的心 编辑:程序博客网 时间:2024/05/25 19:58
主页微博:
获取当前登录用户及其所关注(授权)用户的最新微博接口:http://open.weibo.com/wiki/2/statuses/friends_timeline
代码详解:
1.异步get请求数据,由于数据中带图片,故需要多线程管理,参数设置按照接口一一对应。
2.请求的数据respone数据解析后,单条保存WeiboInfo数据域集合中,然后add到ArrayList中。
3.获取的数据,按布局加载到自定义Listview中(后面讲解),该自定义Listview具有滑动下拉刷新的功能。
4.刷新页面数据的方法,使用 adapater.notifyDataSetChanged()释放listview里的原数据,然后异步线程通知主线程重新获取数据。
5.GetDataTask类继承AsyncTask,以响应滑动下拉事件。改事件与手动按钮的刷新方法完全一致。
/** * Created by D&LL on 2016/7/20. * 主页模块 */public class HomeActivity extends Activity { private OAuth oAuth = null; private RequestParams params; private String TAG = "HomeActivity"; private Tools tools; private WeiboAdapter adapater = null; // 保存需要显示的多条微博数据 public ArrayList<WeiBoInfo> weiboList = null; public static PullToRefreshListView listView; private ImageButton refresh; private TextView user_name; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.home); listView = (PullToRefreshListView) findViewById(R.id.Msglist); user_name = (TextView) findViewById(R.id.user_name); refresh = (ImageButton) findViewById(R.id.refresh); init(); //按钮刷新微博 refresh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { refresh(); } }); //listview下拉刷新 listView.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() { @Override public void onRefresh() { new GetDataTask(HomeActivity.this, 0).execute(); } @Override public void onLoadMore() { } }); } /** * 加载首页数据 */ private void init() { tools = Tools.getInstance(); getUserName(); //获取微博数据 weiboList = tools.getWeiboContent(this); if (weiboList != null) { // 创建一个Adapter设置ListView中的每项Item项数据 adapater = new WeiboAdapter(HomeActivity.this, weiboList); listView.setAdapter(adapater); } else { adapater = new WeiboAdapter(HomeActivity.this, null); listView.setAdapter(adapater); } } /** * 用于标题栏显示用户名 */ public void getUserName() { if (oAuth == null) { oAuth = OAuth.getOAuth(this); } params = new RequestParams(); params.put("access_token", oAuth.getAccessToken()); params.put("uid", oAuth.getUid()); WeiboRestClient.get("2/users/show.json", params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { try { String screen_name = response.getString("screen_name"); user_name.setText(screen_name); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); Log.i(TAG, "获取失败"); } }); } Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { //通知数据改变,更新listview adapater.weiboList = (ArrayList<WeiBoInfo>) msg.obj; adapater.notifyDataSetChanged(); } }; //刷新页面数据的方法 public void refresh() { adapater.weiboList.clear(); adapater.notifyDataSetChanged(); ArrayList<WeiBoInfo> new_contentList = tools.getWeiboContent(HomeActivity.this); Message msg = handler.obtainMessage(); msg.obj = new_contentList; handler.sendMessage(msg); if (new_contentList != null) { // 创建一个Adapter设置ListView中的每项Item项数据 adapater = new WeiboAdapter(HomeActivity.this, new_contentList); listView.setAdapter(adapater); } else { adapater = new WeiboAdapter(HomeActivity.this, null); listView.setAdapter(adapater); } } private class GetDataTask extends AsyncTask<Void, Void, String[]> { private Context context; private int index; public GetDataTask(Context context, int index) { this.context = context; this.index = index; } @Override protected String[] doInBackground(Void... params) { return new String[0]; } @Override protected void onPostExecute(String[] result) { if (index == 0) { refresh(); SimpleDateFormat format = new SimpleDateFormat( "yyyy年MM月dd日 HH:mm"); String date = format.format(new Date()); // Call onRefreshComplete when the list has been refreshed. listView.onRefreshComplete(date); } super.onPostExecute(result); } }}
使用httpClient get方法获得所需数据,对获得的json数据逐条解析,由于原创微博与转发微博json数据格式不同,故需要先判断解析不同部分然后处理相同部分。
使用 thread.start()释放异步线程的数据,以获得所需数据。
此处包含一个时间处理类(后面详解),计算微博发出时间距现在的时长。
该方法位于Tools类中
/** * 自定义异步线程加载微博 * 并对微博评论数据进行处理 * 对线程进行处理可以获得返回值 * @param context * @return */ public ArrayList<WeiBoInfo> getWeiboContent(Context context) { if (oAuth == null) { oAuth = oAuth.getOAuth(context); } class MyThread extends Thread { @Override public void run() { String url = "https://api.weibo.com/2/statuses/friends_timeline.json"; List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("access_token", oAuth.getAccessToken())); params.add(new BasicNameValuePair("count", "100")); String param = URLEncodedUtils.format(params, "UTF-8"); HttpGet get = new HttpGet(url + "?" + param); httpClient = new DefaultHttpClient(); try { HttpResponse responses = httpClient.execute(get); if (responses.getStatusLine().getStatusCode() == 200) { String r = EntityUtils.toString(responses.getEntity()); JSONObject response = new JSONObject(r); //对获得的100条微博json数据遍历解析,放到对象集合中,然后添加到ArrayList里 for (int i = 0; i < 100; i++) { WeiBoInfo weiBoInfo = new WeiBoInfo(); JSONArray statuses = response.getJSONArray("statuses"); JSONObject world = statuses.getJSONObject(i); JSONObject user = world.getJSONObject("user"); //转发的微博 if (world.has("retweeted_status")) { JSONObject retweeted_status = world.getJSONObject("retweeted_status"); JSONObject retweeted_user = retweeted_status.getJSONObject("user"); String retweeted_name = "@" + retweeted_user.getString("screen_name") + ":"; String text = world.getString("text") + ":\n" + retweeted_name + retweeted_status.getString("text"); JSONArray img = retweeted_status.getJSONArray("pic_urls"); weiBoInfo.setText(text); Boolean haveImg = false; if (img != null) { haveImg = true; String[] pics = new String[img.length()]; for (int n = 0; n < img.length(); n++) { JSONObject pic = img.getJSONObject(n); pics[n] = pic.getString("thumbnail_pic"); } weiBoInfo.setImage_context(pics); } weiBoInfo.setHaveImage(haveImg); } else { // 获得weibo内容 String text = world.getString("text"); JSONArray img = world.getJSONArray("pic_urls"); weiBoInfo.setText(text); Boolean haveImg = false; if (img != null) { haveImg = true; String[] pics = new String[img.length()]; for (int n = 0; n < img.length(); n++) { JSONObject pic = img.getJSONObject(n); pics[n] = pic.getString("thumbnail_pic"); } weiBoInfo.setImage_context(pics); } weiBoInfo.setHaveImage(haveImg); } // 获得发weibo 用户的名称 String name = user.getString("screen_name"); // 获得发weibo 用户的头像url链接 String userIcon = user.getString("avatar_large"); // 获得发weibo的时间 String time = world.getString("created_at"); Date startDate = new Date(time); SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); time = sd.format(startDate); String nowtime = new DateUtils().getInterval(time); if (weiboList == null) { // 创建存储每条微博的集合 weiboList = new ArrayList<>(); } //数据设置 weiBoInfo.setUserName(name); weiBoInfo.setTime(nowtime); weiBoInfo.setUserIcon(userIcon); // 将单条微博数据设置到集合中 weiboList.add(weiBoInfo); /* Log.i(TAG, time); Log.i(TAG, world.getString("text")); Log.i(TAG, user.getString("avatar_large"));*/ } } } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } } //处理异步线程,以获得weibilist的返回值 MyThread thread = new MyThread(); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } return weiboList; }
HomeActivity布局home.xml 改布有一个标题栏(包含手动刷新按钮,和显示用户名的TextView),一个自定义的ListView。
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/ly_main_weixin" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/backgroundimage" android:orientation="vertical"> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="45dp" android:background="@drawable/title_bar"> <ImageButton android:id="@+id/refresh" android:layout_width="60dp" android:layout_height="match_parent" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginStart="10dp" android:background="@drawable/refresh"/> <TextView android:id="@+id/user_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textColor="#fff" android:textSize="20sp" android:textStyle="bold"/> </RelativeLayout> <study.sinatest.util.PullToRefreshListView android:id="@+id/Msglist" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="0px" android:background="#BBFFFFFF" android:cacheColorHint="#00000000" android:divider="@drawable/link" android:dividerHeight="5px" android:fastScrollEnabled="true" android:focusable="true"/></LinearLayout>
评论
获取当前登录用户的最新评论包括接收到的与发出的接口:http://open.weibo.com/wiki/2/comments/timeline
该界面功能与主页微博功能除了数据处理略有不同,其余完全一致,不再详细叙述,有疑问请参考代码。
- Android模仿新浪微博(主页微博,评论界面)
- Android模仿新浪微博(启动界面&登陆界面)
- Android模仿新浪微博(oauth2.0授权界面)
- Android模仿新浪微博(分页管理界面)
- Android模仿新浪微博(写微博界面)
- Android模仿新浪微博(个人信息界面及其他)
- css3模仿新浪微博主页文字滚动
- Android模仿新浪微博(前言)
- Android 模仿新浪微博“@”功能
- Android模仿新浪微博(自定义ListView下拉刷新)
- 模仿新浪微博界面设计
- Android新浪微博之主页面布局
- 模仿android新浪微博手机客户端项目
- 模仿android新浪微博手机客户端项目
- Android新浪微博获取评论信息、发表评论、转发微博等.
- Android 模仿微信主页面
- 模仿新浪微博使用帮助
- 模仿 新浪微博--随便看看
- 集合与IO流结合编写的简单的学生信息管理系统
- 俩种方法实现一个数的二进制位模式从左到右翻转后的值
- u-boot-2016.07README文档结构
- 不使用(a+b)/2这种方式,求两个数的平均值
- URAL 2026 Dean and Schedule 贪心、双端队列(deque)、队列(queue)
- Android模仿新浪微博(主页微博,评论界面)
- swift学习第四天
- 线程的创建和启动
- 反射:集合泛型的本质
- HDU 5008 B - Boring String Problem(非常好的题目)
- 51单片机之外设——玩转数码管
- 类加载器的父委托机制
- 字符串、列表、元组、字典、集合的区别
- UltraEdit右键菜单注册及删除 另附最新版绿色版