Source: Miroslav | http://fangjie.sinaapp.com/?p=75 Reprint please indicate the source
Final Effect Demo: http://fangjie.sinaapp.com/?page_id=54
The project code has been put into Github:https://github.com/jayfang1993/sinaweibo
Two Get user information and save the database
There are two cases of loading authactivity, one of which is the authorization successful callback, after the authorization callback succeeds we start to obtain the user information through the microblogging API, and then save the database. This series of operations I use the main frame mode, the task sent to Mainservice to handle.
For the specific process of this task, first obtain the UID through token, and then obtain the userinfo through the UID. It is noteworthy in userinfo that Usericon is a bitmap type, which involves a method of acquiring bitmap through a URL, which is not detailed here.
The Dotask method in Mainservice.java:
public void Dotask (Task Task) {Message msg=handler.obtainmessage (); Msg.what=task.gettaskid (); Switch (Task.gettaskid ()) {//login operation case Task.WEIBO_LOGIN:break; Obtain user information through Access_token and save to database operation case Task.get_userinfo_by_token: {Oauth2accesstoken access_token= ( Oauth2accesstoken) Task.getparams (). Get ("token"); LOG.I ("OUTPUT", "Access_token:" +access_token.gettoken ()); /** * Step One: Use the authorization code to obtain the user UID *///request to get UID String uid= ""; Getuserinfo.requid (Access_token); Get UID do{uid=getuserinfo.getuid (); }while (Uid.equals ("")); /** * Step two: Get userinfo through Uid,token *//request to get user information long _uid=long.parselong (UID); UserInfo user=new UserInfo (); Getuserinfo.requserinfo (Access_token, _uid); Get UserInfo do{user=getuserinfo.getuserinfo (); }while (User.getusername (). Equals ("")); User.setuserid (UID); LOG.I ("OUTPUT", "Username:" +user.getusername () + "userid+" +user.getuserid () + "Usericon" +user.getusericon ()); /** * Step three: Save UserInfo data to database total *//CREATE DATABASE Dbuserinfo db=new dbuserinfo (getactiviTybyname ("authactivity")); If the data does not exist in the database if (Db.getuserinfobyuserid (UID) ==null) {//Insert db.insertuserinfo (user); LOG.I ("OUTPUT", "Save Database Success"); }//If the data already exists in the database else {//modify LOG.I ("OUTPUT", "Data modification succeeded"); } msg.obj= "Success";} Break Login interface to get user information display operation case Task.GET_USERINFO_IN_LOGIN:break; Default:break; } handler.sendmessage (msg);}
The above microblogging API operations are asynchronous operations so take the same action as requested first and then get. This approach has been made clear in the authorization section.
Then is to save the database operation, here are the most basic database usage, is one thing to note is that Usericon saved is the Bolb binary data.
Getuserinfo.java//tools and methods for obtaining user information using the Weibo API
Package Com.fangjie.weibo.util;import Java.io.bufferedinputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.net.url;import Java.net.urlconnection;import Org.json.jsonexception;import Org.json.jsonobject;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.util.Log; Import Com.fangjie.weibo.bean.userinfo;import Com.weibo.sdk.android.oauth2accesstoken;import Com.weibo.sdk.android.weiboexception;import Com.weibo.sdk.android.api.accountapi;import Com.weibo.sdk.android.api.usersapi;import com.weibo.sdk.android.net.requestlistener;/** * GetUserInfo class * Get user information via API * @author Miroslav * @date 2013-7-29 */public class GetUserInfo {public static String uid= ""; private static UserInfo user; /** * Request user information by Accesstoken UID * @param accesstoken */public static void Requid (Oauth2accesstoken accesstoken) {Acco Untapi account=new Accountapi (Accesstoken); Account.getuid (New Requestlistener () {@Override public void OnComplete (String result) {// TODO auto-generated Method Stub try {Jsonobject object =new jsonobject (result); Uid=object.getstring ("UID"); } catch (Jsonexception e) {//TODO auto-generated catch block E.printstacktrace (); }} @Override public void OnError (Weiboexception arg0) {//TODO auto-generated method stubs} @Override public void Onioexception (IOException arg0) {//TODO auto-generated Method stub}}); /** * After requesting UID, get UID * @return String */public static string Getuid () {string id=uid; Uid= ""; return ID; }/** * Accesstoken,uid request for user information UserInfo (Name,icon ...) * @param accesstoken * @param uid */public static void Requserinfo (final oauth2accesstoken accesstoken,long uid) {u Ser=new UserInfo (); Usersapi userapi=new Usersapi (Accesstoken); Userapi.show (UID, new Requestlistener () {@Override public void onioexception (IOException arg0) {//TODO auto-generate D method stub} @Override public void OnError (Weiboexception arg0) {//TODO auto-generated method Stub} @Override public void OnComplete (String arg0) {//TODO auto-generated method Stub Jsonobject object; try {object = new Jsonobject (arg0); Bitmap Bm=getuserinfo.getbitmap (object.getstring ("Profile_image_url")); GetUserInfo.user.setUserIcon (BM); GetUserInfo.user.setToken (Accesstoken.gettoken ()); GetUserInfo.user.setIsDefault ("0"); GetUserInfo.user.setUserName (object.getstring ("Screen_name")); } catch (Jsonexception e) {//TODO auto-generated catch block E.printstacktrace (); } } });} public static UserInfo GetUserInfo () {log.i ("OUTPUT", User.getusername ()); return user; } public static Bitmap Getbitmap (String biturl) {Bitmap bitmap=null; try {URL url=new url (biturl); URLConnection conn=url.openconnection (); InputStream in =conn.getinputstream (); Bitmap=bitmapfactory.decodestream (New Bufferedinputstream (in)); } catch (Exception e) {//TODO auto-generated catch block E.printstacktrace (); } return bitmap; }}
Dbuserinfo.java//Database Tool method class for manipulating user information
Package Com.fangjie.weibo.db;import Java.io.bytearrayinputstream;import Java.io.bytearrayoutputstream;import Java.util.arraylist;import Java.util.list;import Com.fangjie.weibo.bean.userinfo;import Android.content.contentvalues;import Android.content.context;import Android.database.cursor;import Android.database.sqlite.sqlitedatabase;import Android.graphics.bitmap;import Android.graphics.bitmap.compressformat;import Android.graphics.bitmapfactory;import Android.graphics.drawable.drawable;import Android.util.log;public class Dbuserinfo {private DBHelper DBHelper; Public Dbuserinfo (Context context) {DBHelper = new DBHelper (context); }/** * Add user information * @param UserInfo */public void Insertuserinfo (UserInfo user) {Sqlitedatabase db = Dbhelper.getwri Tabledatabase (); Bytearrayoutputstream baos=new Bytearrayoutputstream (); User.getusericon (). Compress (Bitmap.CompressFormat.PNG, BAOs); Byte[] Usericon=baos.tobytearray (); Contentvalues values = new Contentvalues (5); Values.Put (Userinfo.user_id,user.getuserid ()); Values.put (Userinfo.user_name, User.getusername ()); Values.put (Userinfo.token,user.gettoken ()); Values.put (Userinfo.is_default,user.getisdefault ()); Values.put (Userinfo.user_icon,usericon); Db.insert (userinfo.tb_name, null, values);//Table name Db.close (); /** * Gets user object based on user userid * @param string * @return UserInfo */Public UserInfo Getuserinfobyuserid (string uid) {S Qlitedatabase db = Dbhelper.getreadabledatabase (); Cursor cursor =db.query (userinfo.tb_name, New String[]{userinfo.id,userinfo.is_default,userinfo.token, Userinfo.user_id,userinfo.user_name,userinfo.user_icon}, userinfo.user_id + "=?", new String[]{uid}, NULL, NULL, NULL) ; UserInfo UserInfo =null; if (null! = cursor) {if (Cursor.getcount () >0) {Cursor.movetofirst (); UserInfo = new UserInfo (); Long ID =cursor.getlong (Cursor.getcolumnindex (userinfo.id)); String uId = cursor.getstring (Cursor.getcolumnindex (userinfo.user_id)); String userName = cursor.getstring (curSor.getcolumnindex (Userinfo.user_name)); String token = cursor.getstring (Cursor.getcolumnindex (Userinfo.token)); String IsDefault = cursor.getstring (Cursor.getcolumnindex (Userinfo.is_default)); byte[] Byteicon = Cursor.getblob (Cursor.getcolumnindex (Userinfo.user_icon)); Userinfo.setid (ID); Userinfo.setuserid (UID); Userinfo.setisdefault (IsDefault); Userinfo.settoken (token); Userinfo.settoken (token); Userinfo.setusername (UserName); if (null!=byteicon) {Bitmap usericon=bitmapfactory.decodebytearray (byteicon, 0, byteicon.length); Userinfo.setusericon (Usericon); }}} db.close (); return userInfo; /** * Get all authorized user information for database * @param * @return list<userinfo> */public list<userinfo> Getalluserinfo () {Li St<userinfo> users=new arraylist<userinfo> (); Sqlitedatabase db = Dbhelper.getreadabledatabase (); Cursor cursor =db.query (userinfo.tb_name, New String[]{userinfo.id,userinfo.is_default,userinfo.token, Userinfo.user_id,userinfo.user_name,userinfO.user_icon}, Null,null, NULL, NULL, NULL); UserInfo UserInfo =null; while (Cursor.movetonext ()) {userInfo = new userInfo (); Long ID =cursor.getlong (Cursor.getcolumnindex (userinfo.id)); String uId = cursor.getstring (Cursor.getcolumnindex (userinfo.user_id)); String userName = cursor.getstring (Cursor.getcolumnindex (userinfo.user_name)); String token = cursor.getstring (Cursor.getcolumnindex (Userinfo.token)); String IsDefault = cursor.getstring (Cursor.getcolumnindex (Userinfo.is_default)); byte[] Byteicon = Cursor.getblob (Cursor.getcolumnindex (Userinfo.user_icon)); Userinfo.setid (ID); Userinfo.setuserid (UID); Userinfo.setisdefault (IsDefault); Userinfo.settoken (token); Userinfo.setusername (UserName); if (null!=byteicon) {Bitmap usericon=bitmapfactory.decodebytearray (byteicon, 0, byteicon.length); LOG.I ("OUTPUT", "Dbuserinfo" +usericon); Userinfo.setusericon (Usericon); } users.add (UserInfo);} Db.close (); return users; }}
Three. Get all authorized user information and display it on the login screen
Remember that in the above authactivity we sent the Get_userinfo_by_token (get authorized user information and save the database) This task, after this task is completed, we will jump to loginactivity in the Refresh () method. At the beginning of the loginactivity, we send Get_userinfo_in_login (get all the authorized user information), which is the database operation when doing the task processing.
Login interface Get user information display operation case Task.get_userinfo_in_login: { dbuserinfo db=new dbuserinfo (Getactivitybyname (" Loginactivity ")); List<userinfo> users=db.getalluserinfo (); msg.obj=users; }
Other:
After all this, I suddenly wanted to talk about this addactivty,removeactivty,getactivitybyname.
/** * The UI layer sends a task to Mainservice, and also sends its own activity, * to invoke Refresh () in Mainservice; * @param task * /public static void addactivty (activity activity) { appactivities.add (activity); } /** * In the UI layer, the activity is passed to the Mainservice, and after the task is finished (refresh), the activity should be removed to prevent confusion! * Eg: the Get_userinfo_in_login task in Loginactivity will start once with each reload of the activity, if not removed * activity, This will cause the refresh to be an instance of the last activity. Because the activity is obtained through Getactivitybyname, the name of the activity instance of these two * times is the same. * @param activity * /public static void removeactivty (activity activity) { Appactivities.remove (activity); }
Especially removeactivty This method, I myself in the project when I forget to delete the activity instance every time I complete the task, resulting in such an error :
Program start time will go to loginactivity, this time do a get_userinfo_in_login, put loginacivity an instance to activities, when I add an authorized user information again, When you are done jumping to loginactivity again, there is no information displayed on the interface. Because when I jump to loginactivity for the second time, we pass a loginactivity instance again, and when I refresh () after I finish the task, I refresh the first instance of the Loginactivity, So for the second time the loginactivity is certainly not shown.
With these three methods, we can pass the context parameters to some tool class methods by activity, such as the context parameter when building the database, and the context parameter when jumping in the tool class. Although this kind of communication may increase the coupling between layer and layer, but I am at this level, please give me advice.
welcome attention to my personal site: http://fangjie.sinaapp.com/&NBSP;