主页微博:
获取当前登录用户及其所关注(授权)用户的最新微博接口: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;@Overrideprotected 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() {@Overridepublic void onClick(View v) {refresh();}});//listview下拉刷新listView.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {@Overridepublic void onRefresh() {new GetDataTask(HomeActivity.this, 0).execute();}@Overridepublic 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() {@Overridepublic 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();}}@Overridepublic 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) {//通知数据改变,更新listviewadapater.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;}@Overrideprotected String[] doInBackground(Void... params) {return new String[0];}@Overrideprotected 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 {@Overridepublic 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
该界面功能与主页微博功能除了数据处理略有不同,其余完全一致,不再详细叙述,有疑问请参考代码。