public class App extends Application {
	private static App mAppApplication;
	public static final String SP_FILE_NAME = "qiquying_msg_sp";
	private static SharePreferenceUtil mSpUtil;
	public static User currentUser = null;
	public static List<Activity> activities = new ArrayList<Activity>(); //用于记录已经开启的activity,便于退出应用时全部关闭
	// Tencent类是SDK的主要实现类，开发者可通过Tencent类访问腾讯开放的OpenAPI。
	// 其中APP_ID是分配给第三方应用的appid，类型为String。
	public static Tencent mTencent;
	public static Map<String, Long> smsCodeRecode;  //注册验证码发送记录
	public static Map<String, Long> smsCodeRecodeFindPwd;  //找回密码验证码发送记录
	public static boolean isStart = false;
	public static boolean isStartOtherActivity = false;
	@Override
	public void onCreate() {
		super.onCreate();
		mAppApplication = this;
		mSpUtil = new SharePreferenceUtil(this, SP_FILE_NAME);
		CrashHandler crashHandler = CrashHandler.getInstance();   
        crashHandler.init(getApplicationContext());
	}
	
	/** 获取Application */
    public static App getInstance() {
        return mAppApplication;
    }
    
    /** 获取mSpUtil */
    public synchronized SharePreferenceUtil getSpUtil() {
		if (mSpUtil == null)
			mSpUtil = new SharePreferenceUtil(this, SP_FILE_NAME);
		return mSpUtil;
	}


	/*添加activity*/
	public static void addActivity(Activity activity) {
		activities.add(activity);
	}
	
	/*添加activity*/
	public static void removeActivity(Activity activity) {
		if(activities.contains(activity)) {
			activities.remove(activity);
		}
	}
	
	/*关闭所有已打开的activity*/
	public static void clearActivitys() {
		for (Activity ac : activities) {
			if(ac!=null && !ac.isFinishing()) {
				ac.finish();
			}
		}
	}
	
	@SuppressLint("NewApi")
	@Override
	public void onTrimMemory(int level) {
		super.onTrimMemory(level);
		if(Constants.DEBUG) Log.w("App", "onTrimMemory");
		if (level >= ComponentCallbacks2.TRIM_MEMORY_MODERATE) {
			BitmapUtil.cleanMemCache();  //清除图片内存的中缓存
	    }
	}
} @ContentView(R.layout.activity_all_joke)
public class AllJokeActivity extends BaseActivity {
	private final String TAG = "AllJokeActivity";
	@ViewInject(R.id.mViewPager)
	private ViewPager mViewPager;
	
	private QQYFragmentPagerAdapter mAdapetr;
	private ArrayList<Fragment> mFragments;
	@ViewInject(R.id.refresh)
	private ImageView mRefreshIV;
	
	@ViewInject(R.id.categoryTabStrip)
	private CategoryTabStrip mCategoryTabStrip;
	/** tab栏目（最新、最热）*/
	private ArrayList<String> mCategoryList = new ArrayList<String>();
	
	private Animation mRefreshAnimation;  //刷新图标动画
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.e(TAG, "onCreate");
		ViewUtils.inject(this);
		mCategoryList.add("最新");
		mCategoryList.add("最热");
		mFragments = new ArrayList<Fragment>();
		initFragment();
	}
	
	/**
	 * 初始化fragment
	 */
	private void initFragment() {
		Bundle data = new Bundle();
		data.putInt("newOrHotFlag", Joke.SORT_NEW);
		AllFragment allNewFragment = new AllFragment();
		allNewFragment.setArguments(data);
		mFragments.add(allNewFragment);
		
		Bundle data1 = new Bundle();
		data1.putInt("newOrHotFlag", Joke.SORT_HOT);
		AllFragment allHotFragment = new AllFragment();
		allHotFragment.setArguments(data1);
		mFragments.add(allHotFragment);
		
		mAdapetr = new QQYFragmentPagerAdapter(getSupportFragmentManager(), mFragments);
		mViewPager.setOffscreenPageLimit(2);
        mViewPager.setAdapter(mAdapetr);
        
        mCategoryTabStrip.setViewPager(mViewPager);
        mCategoryTabStrip.setCatalogs(mCategoryList);
	}
	
	@OnClick(R.id.refresh)
	private void refresh(View view) {
		if(mRefreshAnimation == null) {
			mRefreshAnimation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.progress_anim);
		}
		AllFragment allFragment = (AllFragment)mFragments.get(mViewPager.getCurrentItem());
		if(allFragment.isRefresh()) {
			return;
		}
		view.startAnimation(mRefreshAnimation);
		allFragment.refresh();
	}
	
	/**
	 * 刷新完毕，结束刷新动画
	 */
	public void refreshCompete() {
		Log.e("refreshCompete", "refreshCompete");
		mRefreshIV.clearAnimation();
		if(mRefreshAnimation != null) {
			mRefreshAnimation.cancel();
		}
	}
	
	@Override
	protected void onResume() {
		MobclickAgent.onPageStart("AllJokeActivity"); //统计页面
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		MobclickAgent.onPageEnd("AllJokeActivity");
		super.onPause();
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
//		super.onSaveInstanceState(outState);
	}

} @ContentView(R.layout.activity_qushi_detail)
public class QuShiDetailActivity extends BaseActivity {

	private final String TAG = "QuShiDetailActivity";
	
	@ViewInject(R.id.user_nick)
	private TextView mUserNickTV;
	@ViewInject(R.id.create_date)
	private TextView mCreateTimeTV;
	@ViewInject(R.id.qushi_content)
	private TextView mContentTV;
	@ViewInject(R.id.ding_tv)
	private TextView mDingTV;
	@ViewInject(R.id.cai_tv)
	private TextView mCaiTV;
	@ViewInject(R.id.comment_tv)
	private TextView mCommentTV;
	@ViewInject(R.id.share_tv)
	private TextView mShareTV;
	@ViewInject(R.id.user_img)
	private ImageView mUserPortraitIV;
	@ViewInject(R.id.listview)
	private LoadListView mListView;
	@ViewInject(R.id.content_et)
	private EditText mCommentContentET;
	@ViewInject(R.id.scrollview)
	private Scroll2BottomListenerScrollView mScrollView;
	@ViewInject(R.id.qushi_list)
	private LinearLayout mQushiLayout;
	@ViewInject(R.id.progress)
	private ProgressBar mLoadProgressBar;
	
	private Joke mJoke;
	private Handler mHandler = new ClassHandler(this);
	private IJokeService mQuShiService;
	private CommentAdapter mCommentAdapter;
	private List<Comment> mCommentLists = new ArrayList<Comment>();
	private int mPageId = 1;
	private int mCount = 5;
	private boolean mHasNext = true;
	private DingCaiDAO mDingOrCaiDAO = new DingCaiDAO(this);
	private int mUserId = -1;
	private boolean isCommnet = false;  //是否点击评论进来的
	private SharePopWindow mSharePopWindow;
	private int mJokeId = 1;
	private boolean mIsOpenFromPush = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		mQuShiService = new JokeServiceImpl(this);
		if(App.currentUser != null) {
    		mUserId = App.currentUser.getId();
    	}
		mSharePopWindow = new SharePopWindow(this);
		mListView.setHaveScrollbar(false);
		mCommentAdapter = new CommentAdapter(this);
		mListView.setAdapter(mCommentAdapter);
		mListView.setOnFootLoadingListener(new OnFootLoadingListener() {
			@Override
			public void onFootLoading() {
				loadComments();
			}
		});
		initQuShiContent();
	}
	
	/**
	 * 如果此界面已经打开，再点通知界面打开，则调用此方法
	 */
	protected void onNewIntent(Intent intent) {
		if(Constants.DEBUG) Log.d(TAG, "onNewIntent");
		setIntent(intent);
		reSet();   //重置
		initQuShiContent();  //加载
	}
	
	private void reSet() {
		mPageId = 1;
		mHasNext = true;
		mCommentLists.clear();
		if(mCommentAdapter != null) {
			mCommentAdapter.notifyDataSetChanged();
		}
	}
	
	ApiCallBack getJokeApiCallBack = new ApiCallBack() {
		@Override
		public void onSuccess(Object data) {
			mJoke = (Joke) data;
			if(mJoke != null) {
				setQushiContent();
			}
		}
		@Override
		public void onFailure(String msg) {
			mLoadProgressBar.setVisibility(View.GONE);
		}
		@Override
		public void onError(Exception e, String msg) {
			mLoadProgressBar.setVisibility(View.GONE);
		}
	};

	//初始化笑话内容
	private void initQuShiContent() {
		mJoke = (Joke)getIntent().getSerializableExtra("qushi");
		if(mJoke == null) {  //从push进来的
			try {
				mJokeId = Integer.valueOf(getIntent().getStringExtra("id"));
				mIsOpenFromPush = true;
				init();
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
			mQuShiService.getJokeById(getJokeApiCallBack, mJokeId);
		} else {   //从界面进来的
			isCommnet = getIntent().getBooleanExtra("isComment", false);
			mJokeId = mJoke.getId();
			setQushiContent();
		}
	}
	
	//push进来的界面要进行应用程序初始化
	private void init() {
		initYouMeng();
		App.currentUser = (User)spUtil.getObject("user", null);
		//初始化短信接口
        SMSSDK.initSDK(this, getString(R.string.sina_appid), getString(R.string.youmeng_appid));
        initWeiXin();
        initTencent();
	}
	
	private void setQushiContent() {
		loadComments();
		mLoadProgressBar.setVisibility(View.GONE);
		mScrollView.setVisibility(View.VISIBLE);
		BitmapUtil.display(mUserPortraitIV, mJoke.getPortraitUrl());
		mUserNickTV.setText(mJoke.getUserNike());
		mCreateTimeTV.setText(Util.getFormatDate(mJoke.getCreateDate()));
		mContentTV.setText(mJoke.getContent());
        mDingTV.setText(String.valueOf(mJoke.getSupportsNum()));
        mCaiTV.setText(String.valueOf(mJoke.getOpposesNum()));
        mCommentTV.setText(String.valueOf(mJoke.getCommentNum()));
        
        final DingOrCai dingOrCai = mDingOrCaiDAO.getDingOrCai(mUserId, mJokeId);
        if(dingOrCai != null) {
        	if(dingOrCai.isDing()) {
        		mDingTV.setSelected(true);
        		mCaiTV.setSelected(false);
        		if(mJoke.getSupportsNum() < dingOrCai.getNum()) {
        			mJoke.setSupportsNum(dingOrCai.getNum());
        		}
        	} else {
        		mDingTV.setSelected(false);
        		mCaiTV.setSelected(true);
        		if(mJoke.getOpposesNum() < dingOrCai.getNum()) {
        			mJoke.setOpposesNum(dingOrCai.getNum());
        		}
        	}
        }
        
        mDingTV.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(dingOrCai != null) {
					if(dingOrCai.isDing()) {
						ToastUtils.showMessage(QuShiDetailActivity.this, R.string.has_ding);
					} else {
						ToastUtils.showMessage(QuShiDetailActivity.this, R.string.has_cai);
					}
					return;
				}
				if(v.isSelected()) {
					ToastUtils.showMessage(QuShiDetailActivity.this, R.string.has_ding);
					return;
				}
				View caiView = ((LinearLayout)v.getParent().getParent()).findViewById(R.id.cai_tv);
				if(caiView.isSelected()) {
					ToastUtils.showMessage(QuShiDetailActivity.this, R.string.has_cai);
					return;
				}
				final View view = ((RelativeLayout)v.getParent()).getChildAt(1);
				Animation addOneAnimation = AnimationUtils.loadAnimation(
						QuShiDetailActivity.this, R.anim.add_one);
				addOneAnimation.setAnimationListener(new AnimationListener() {
					@Override
					public void onAnimationStart(Animation animation) {
						view.setVisibility(View.VISIBLE);
					}
					@Override
					public void onAnimationRepeat(Animation animation) {
					}
					@Override
					public void onAnimationEnd(Animation animation) {
						view.setVisibility(View.GONE);
					}
				});
				view.startAnimation(addOneAnimation);
				v.setSelected(true);
				mJoke.setSupportsNum(mJoke.getSupportsNum()+1);
				((TextView)v).setText(String.valueOf(mJoke.getSupportsNum()));
				mDingOrCaiDAO.dingOrCai(mUserId, mJokeId, DingOrCai.DING, mJoke.getSupportsNum());
			}
		});
        
        mCaiTV.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(dingOrCai != null) {
					if(dingOrCai.isDing()) {
						ToastUtils.showMessage(QuShiDetailActivity.this, R.string.has_ding);
					} else {
						ToastUtils.showMessage(QuShiDetailActivity.this, R.string.has_cai);
					}
					return;
				}
				if(v.isSelected()) {
					ToastUtils.showMessage(QuShiDetailActivity.this, R.string.has_cai);
					return;
				}
				View dingView = ((LinearLayout)v.getParent().getParent()).findViewById(R.id.ding_tv);
				if(dingView.isSelected()) {
					ToastUtils.showMessage(QuShiDetailActivity.this, R.string.has_ding);
					return;
				}
				final View view = ((RelativeLayout)v.getParent()).getChildAt(1);
				Animation addOneAnimation = AnimationUtils.loadAnimation(
						QuShiDetailActivity.this, R.anim.add_one);
				addOneAnimation.setAnimationListener(new AnimationListener() {
					@Override
					public void onAnimationStart(Animation animation) {
						view.setVisibility(View.VISIBLE);
					}
					@Override
					public void onAnimationRepeat(Animation animation) {
					}
					@Override
					public void onAnimationEnd(Animation animation) {
						view.setVisibility(View.GONE);
					}
				});
				view.startAnimation(addOneAnimation);
				v.setSelected(true);
				mJoke.setOpposesNum(mJoke.getOpposesNum()+1);
				((TextView)v).setText(String.valueOf(mJoke.getOpposesNum()));
				mDingOrCaiDAO.dingOrCai(mUserId, mJokeId, DingOrCai.CAI, mJoke.getOpposesNum());
			}
		});
        mShareTV.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mSharePopWindow.setmJoke(mJoke);
				mSharePopWindow.showAtLocation(v.getRootView(), Gravity.LEFT | Gravity.BOTTOM, 0, 0);
			}
		});
        mCommentTV.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mCommentContentET.requestFocus();
				ToolsUtils.openKeybord(mCommentContentET, QuShiDetailActivity.this);
			}
		});
	}
	
	/**
	 * 加载趣事评论
	 */
	private void loadComments() {
		if(!mHasNext){
			mListView.onFootLoadingComplete(true);
			return;
		}
		mQuShiService.getCommentByJokeId(mHandler, mJokeId, mPageId, mCount);
	}
	
	/**
	 * 加载数据成功，更新界面
	 * @param pageResult
	 */
	private void loadSuccess(PageResult pageResult) {
		mScrollView.setmListView(mListView);
		if(pageResult == null || pageResult.isEmpty()) {
			if(Constants.DEBUG) Log.w(TAG, "load qushi success, but no data!");
			mHasNext = false;
			return;
		}
		
		String tmp = FastjsonUtil.serialize(pageResult.getList());
		List<Comment> list = FastjsonUtil.deserializeList(tmp,
				Comment.class);
		mCommentLists.addAll(list);
		
		if(mCommentLists.size() <= 0) {   //无数据，显示无数据布局
		} else {
			mCommentAdapter.onDataChange(mCommentLists);
			mListView.setVisibility(View.VISIBLE);
		}
//		ToolsUtils.setListViewHeightBasedOnChildren(mListView);
		if(isCommnet && mPageId == 1) {   //如果点击评论进来的，则滚动到评论处
			TaskExecutor.scheduleTaskOnUiThread(150, new Runnable() {
				@Override
				public void run() {
					int height = mQushiLayout.getHeight();
					mScrollView.scrollTo(0, height);
				}
			});
		}
		mHasNext = pageResult.getHasNext();
		mListView.setHasMoreData(mHasNext);  //设置是否还有更多数据
		if (pageResult.getHasNext()) {
			mPageId = pageResult.getNext();
		}
	}
	
	@OnClick(R.id.add_comment_btn)
	private void sendComment(View view) {
		ToolsUtils.hideKeyboard(mCommentTV);
		if(App.currentUser == null) {  //用户未登录
			Intent intent = new Intent(this, LoginActivity.class);
			startActivityWithAnimation(intent);
			return;
		}
		String content = mCommentContentET.getText().toString().trim();
		if(Util.isEmpty(content)) {
			ToastUtils.showMessage(getApplicationContext(), 
					R.string.comment_content_null);
			return;
		}
		content = ToolsUtils.Html2Text(content);
		if(Util.isEmpty(content)) {
			ToastUtils.showMessage(getApplicationContext(), 
					R.string.input_invalide);
			return;
		}
		if(mJoke == null) {
			return;
		}
		ProgressDialogUtils.showProgressDialog(this, getString(R.string.commenting));
		mQuShiService.addComment(mHandler, mJokeId, content);
	}
	
	@OnClick(R.id.back)
	private void back(View view) {
		if(mIsOpenFromPush && !App.isStart) {
			Intent intent = new Intent(this, SplashActivity.class);
			startActivityWithAnimation(intent);
		}
		finishWithAnimation();
	}
	
	@Override
	public void onBackPressed() {
		if(mIsOpenFromPush && !App.isStart) {
			Intent intent = new Intent(this, SplashActivity.class);
			startActivityWithAnimation(intent);
		}
		super.onBackPressed();
	}
	
	/**
	 * 消息处理类
	 * @author lling
	 * 
	 */
	static class ClassHandler extends Handler {
		WeakReference<QuShiDetailActivity> mReference;
		ClassHandler(QuShiDetailActivity activity) {
			mReference = new WeakReference<QuShiDetailActivity>(activity);
		}
		public void handleMessage(Message msg) {
			final QuShiDetailActivity activity = mReference.get();
			if(activity == null) {
				return;
			}
			switch (msg.what) {
			case Constants.SUCCESS: // 获取评论数据成功
				PageResult pageResult = (PageResult)msg.getData().getSerializable("pageResult");
				activity.loadSuccess(pageResult);
				activity.mListView.onFootLoadingComplete(true);
				break;
			case Constants.FAILURE:
				activity.mListView.onFootLoadingComplete(true);
				break;
			case Constants.SUCCESS_1: // 发表评论成功
				ProgressDialogUtils.dismiss();
				activity.commentSuccess();
				break;
			case Constants.FAILURE_1:
				ProgressDialogUtils.dismiss();
				break;
			}
		}
	}

	/**
	 * 评论成功
	 */
	private void commentSuccess() {
		Comment comment = new Comment();
		comment.setContent(mCommentContentET.getText().toString().trim());
		comment.setUserId(App.currentUser.getId());
		comment.setPortraitUrl(App.currentUser.getPortraitUrl());
		comment.setUserNike(App.currentUser.getUserNike());
		comment.setCreateDate(new Date());
		mCommentLists.add(0, comment);
		mCommentAdapter.onDataChange(mCommentLists);
		mCommentContentET.setText("");
		
		mJoke.setCommentNum(mJoke.getCommentNum()+1);
		mCommentTV.setText(String.valueOf(mJoke.getCommentNum()));
		
		mListView.setSelectionAfterHeaderView();//选中第一条
	}
	
	@Override
	protected void onResume() {
		MobclickAgent.onPageStart("QuShiDetailActivity"); //统计页面
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		MobclickAgent.onPageEnd("QuShiDetailActivity");
		if(ToolsUtils.isKeybordShow(this)) {
			ToolsUtils.hideKeyboard(mCommentContentET);
		}
		super.onPause();
	}
	
	
	private void initYouMeng() {
		AnalyticsConfig.enableEncrypt(true);
		MobclickAgent.openActivityDurationTrack(false);
		PushAgent mPushAgent = PushAgent.getInstance(this);
		mPushAgent.onAppStart();
		if(spUtil.getBoolean(Constants.IS_RECEIVE_PUSH, true)) {
			mPushAgent.enable();
		} else {
			mPushAgent.disable();
		}
	}
	
	private void initWeiXin() {
		IWXAPI api = WXAPIFactory.createWXAPI(this, com.lling.qiqu.wxapi.Constants.APP_ID);
		api.registerApp(com.lling.qiqu.wxapi.Constants.APP_ID);
	}
	
	private void initTencent() {
		try {
			ApplicationInfo appInfo = this.getPackageManager()
			        .getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
			int appId = appInfo.metaData.getInt("TECENT_APPID", -1);
			if(appId == -1) {
				return;
			}
			App.mTencent = Tencent.createInstance(String.valueOf(appId), 
					this.getApplicationContext());
			String openId = spUtil.getString(com.tencent.connect.common.Constants.PARAM_OPEN_ID, null);
			String token = spUtil.getString(com.tencent.connect.common.Constants.PARAM_ACCESS_TOKEN, null);
			long expires = spUtil.getLong(com.tencent.connect.common.Constants.PARAM_EXPIRES_IN, System.currentTimeMillis());
			if(openId != null) {
				App.mTencent.setOpenId(openId);
			}
			if(token != null) {
				App.mTencent.setAccessToken(token, String.valueOf((expires-System.currentTimeMillis())/1000));
			}
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
	}
	
} @ContentView(R.layout.activity_tu_detail)
public class TuDetailActivity extends BaseActivity {
	private final String TAG = "TuDetailActivity";
	@ViewInject(R.id.user_nick)
	private TextView mUserNickTV;
	@ViewInject(R.id.create_date)
	private TextView mCreateTimeTV;
	@ViewInject(R.id.qutu_title)
	private TextView mTitleTV;
	@ViewInject(R.id.qutu_content)
	private LoadPercentImageView mContentIV;
	@ViewInject(R.id.ding_tv)
	private TextView mDingTV;
	@ViewInject(R.id.cai_tv)
	private TextView mCaiTV;
	@ViewInject(R.id.comment_tv)
	private TextView mCommentTV;
	@ViewInject(R.id.share_tv)
	private TextView mShareTV;
	@ViewInject(R.id.user_img)
	private ImageView mUserPortraitIV;
	@ViewInject(R.id.listview)
	private LoadListView mListView;
	@ViewInject(R.id.content_et)
	private EditText mCommentContentET;
	@ViewInject(R.id.scrollview)
	private Scroll2BottomListenerScrollView mScrollView;
	@ViewInject(R.id.qutu_layout)
	private LinearLayout mQuTuLayout;
	@ViewInject(R.id.progress)
	private ProgressBar mLoadProgressBar;
	
	private Joke mJoke;
	private Handler mHandler = new ClassHandler(this);
	private IJokeService mQuShiService;
	private CommentAdapter mCommentAdapter;
	private List<Comment> mCommentLists = new ArrayList<Comment>();
	private int mPageId = 1;
	private int mCount = 10;
	private boolean mHasNext = true;
	private int mMaxWidth;
	private DingCaiDAO mDingOrCaiDAO = new DingCaiDAO(this);
	private int mUserId = -1;
	private boolean isCommnet = false;  //是否点击评论进来的
	private SharePopWindow mSharePopWindow;
	private int mJokeId = 1;
	private boolean mIsOpenFromPush = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		mQuShiService = new JokeServiceImpl(this);
		if(App.currentUser != null) {
    		mUserId = App.currentUser.getId();
    	}
		mSharePopWindow = new SharePopWindow(this);
		mListView.setHaveScrollbar(false);
		mCommentAdapter = new CommentAdapter(this);
		mListView.setAdapter(mCommentAdapter);
		mListView.setOnFootLoadingListener(new OnFootLoadingListener() {
			@Override
			public void onFootLoading() {
				loadComments();
			}
		});
		initContent();
	}
	
	/**
	 * 如果此界面已经打开，再点通知界面打开，则调用此方法
	 */
	protected void onNewIntent(Intent intent) {
		if(Constants.DEBUG) Log.d(TAG, "onNewIntent");
		setIntent(intent);
		reSet();
		initContent();
	}
	
	private void reSet() {
		mPageId = 1;
		mHasNext = true;
		mCommentLists.clear();
		
	}
	
	ApiCallBack getJokeApiCallBack = new ApiCallBack() {
		@Override
		public void onSuccess(Object data) {
			mJoke = (Joke) data;
			if(mJoke != null) {
				setContent();
			}
		}
		@Override
		public void onFailure(String msg) {
			mLoadProgressBar.setVisibility(View.GONE);
		}
		@Override
		public void onError(Exception e, String msg) {
			mLoadProgressBar.setVisibility(View.GONE);
		}
	};
	
	//初始化笑话内容
	private void initContent() {
		mJoke = (Joke)getIntent().getSerializableExtra("content");
		if(mJoke == null) {
			try {
				mJokeId = Integer.valueOf(getIntent().getStringExtra("id"));
				mIsOpenFromPush = true;
				init();
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
			mQuShiService.getJokeById(getJokeApiCallBack, mJokeId);
		} else {
			isCommnet = getIntent().getBooleanExtra("isComment", false);
			mJokeId = mJoke.getId();
			setContent();
		}
	}
	
	private void setContent() {
		loadComments();  //把加载评论放在加载内容之后（推送进来）
		mLoadProgressBar.setVisibility(View.GONE);
		mScrollView.setVisibility(View.VISIBLE);
		mMaxWidth = DensityUtil.getWidthInPx(this) - DensityUtil.dip2px(this, 32);
		mContentIV.setMaxWidth(mMaxWidth);
		int width = mJoke.getImgWidth();
        int height = mJoke.getImgHeight();
        if(width != 0 && width != 0) {
        	float scale = (float)width / (float)mMaxWidth;
            height = (int)(height / scale);
            mContentIV.setLayoutParams(new LinearLayout.LayoutParams(mMaxWidth, height));
        }
		mContentIV.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(TuDetailActivity.this, ImageShowActivity.class);
				intent.putExtra("url", mJoke.getImgUrl());
				startActivity(intent);
			}
		});
		BitmapUtil.display(mUserPortraitIV, mJoke.getPortraitUrl());
		mUserNickTV.setText(mJoke.getUserNike());
		mCreateTimeTV.setText(Util.getFormatDate(mJoke.getCreateDate()));
		if(Util.isEmpty(mJoke.getTitle())) {
			mTitleTV.setVisibility(View.GONE);
		} else {
			mTitleTV.setText(mJoke.getTitle());
		}
        mDingTV.setText(String.valueOf(mJoke.getSupportsNum()));
        mCaiTV.setText(String.valueOf(mJoke.getOpposesNum()));
        mCommentTV.setText(String.valueOf(mJoke.getCommentNum()));
        
        final DingOrCai dingOrCai = mDingOrCaiDAO.getDingOrCai(mUserId, mJokeId);
        if(dingOrCai != null) {
        	if(dingOrCai.isDing()) {
        		mDingTV.setSelected(true);
        		mCaiTV.setSelected(false);
        		if(mJoke.getSupportsNum() < dingOrCai.getNum()) {
        			mJoke.setSupportsNum(dingOrCai.getNum());
        		}
        	} else {
        		mDingTV.setSelected(false);
        		mCaiTV.setSelected(true);
        		if(mJoke.getOpposesNum() < dingOrCai.getNum()) {
        			mJoke.setOpposesNum(dingOrCai.getNum());
        		}
        	}
        }
        
        mDingTV.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(dingOrCai != null) {
					if(dingOrCai.isDing()) {
						ToastUtils.showMessage(TuDetailActivity.this, R.string.has_ding);
					} else {
						ToastUtils.showMessage(TuDetailActivity.this, R.string.has_cai);
					}
					return;
				}
				if(v.isSelected()) {
					ToastUtils.showMessage(TuDetailActivity.this, R.string.has_ding);
					return;
				}
				View caiView = ((LinearLayout)v.getParent().getParent()).findViewById(R.id.cai_tv);
				if(caiView.isSelected()) {
					ToastUtils.showMessage(TuDetailActivity.this, R.string.has_cai);
					return;
				}
				final View view = ((RelativeLayout)v.getParent()).getChildAt(1);
				Animation addOneAnimation = AnimationUtils.loadAnimation(
						TuDetailActivity.this, R.anim.add_one);
				addOneAnimation.setAnimationListener(new AnimationListener() {
					@Override
					public void onAnimationStart(Animation animation) {
						view.setVisibility(View.VISIBLE);
					}
					@Override
					public void onAnimationRepeat(Animation animation) {
					}
					@Override
					public void onAnimationEnd(Animation animation) {
						view.setVisibility(View.GONE);
					}
				});
				view.startAnimation(addOneAnimation);
				v.setSelected(true);
				mJoke.setSupportsNum(mJoke.getSupportsNum()+1);
				((TextView)v).setText(String.valueOf(mJoke.getSupportsNum()));
				mDingOrCaiDAO.dingOrCai(mUserId, mJokeId, DingOrCai.DING, mJoke.getSupportsNum());
			}
		});
        
        mCaiTV.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(dingOrCai != null) {
					if(dingOrCai.isDing()) {
						ToastUtils.showMessage(TuDetailActivity.this, R.string.has_ding);
					} else {
						ToastUtils.showMessage(TuDetailActivity.this, R.string.has_cai);
					}
					return;
				}
				if(v.isSelected()) {
					ToastUtils.showMessage(TuDetailActivity.this, R.string.has_cai);
					return;
				}
				View dingView = ((LinearLayout)v.getParent().getParent()).findViewById(R.id.ding_tv);
				if(dingView.isSelected()) {
					ToastUtils.showMessage(TuDetailActivity.this, R.string.has_ding);
					return;
				}
				final View view = ((RelativeLayout)v.getParent()).getChildAt(1);
				Animation addOneAnimation = AnimationUtils.loadAnimation(
						TuDetailActivity.this, R.anim.add_one);
				addOneAnimation.setAnimationListener(new AnimationListener() {
					@Override
					public void onAnimationStart(Animation animation) {
						view.setVisibility(View.VISIBLE);
					}
					@Override
					public void onAnimationRepeat(Animation animation) {
					}
					@Override
					public void onAnimationEnd(Animation animation) {
						view.setVisibility(View.GONE);
					}
				});
				view.startAnimation(addOneAnimation);
				v.setSelected(true);
				mJoke.setOpposesNum(mJoke.getOpposesNum()+1);
				((TextView)v).setText(String.valueOf(mJoke.getOpposesNum()));
				mDingOrCaiDAO.dingOrCai(mUserId, mJokeId, DingOrCai.CAI, mJoke.getOpposesNum());
			}
		});
        mShareTV.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mSharePopWindow.setmJoke(mJoke);
				mSharePopWindow.showAtLocation(v.getRootView(), Gravity.LEFT | Gravity.BOTTOM, 0, 0);
			}
		});
        mCommentTV.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mCommentContentET.requestFocus();
				ToolsUtils.openKeybord(mCommentContentET, TuDetailActivity.this);
			}
		});
        if(HttpUtil.isWifi(this) || spUtil.getBoolean(Constants.IS_LOAD_IMG, true)) {  //仅wifi状态下加载网络
        	mContentIV.setLoadImg(true);
        	BitmapUtil.display(mContentIV, mJoke.getImgUrl(), new PercentImageViewLoadCallBack());
        } else {
        	mContentIV.setLoadImg(false);
        }
	}
	
	/**
	 * 加载评论
	 */
	private void loadComments() {
		if(!mHasNext){
			mListView.onFootLoadingComplete(true);
			return;
		}
		mQuShiService.getCommentByJokeId(mHandler, mJokeId, mPageId, mCount);
	}
	
	/**
	 * 加载数据成功，更新界面
	 * @param pageResult
	 */
	private void loadSuccess(PageResult pageResult) {
		mScrollView.setmListView(mListView);
		if(pageResult == null || pageResult.isEmpty()) {
			if(Constants.DEBUG) Log.w(TAG, "load data success, but no data!");
			mHasNext = false;
			return;
		}
		
		String tmp = FastjsonUtil.serialize(pageResult.getList());
		List<Comment> list = FastjsonUtil.deserializeList(tmp,
				Comment.class);
		mCommentLists.addAll(list);
		
		if(mCommentLists.size() <= 0) {   //无数据，显示无数据布局
		} else {
			mCommentAdapter.onDataChange(mCommentLists);
			mListView.setVisibility(View.VISIBLE);
		}
		if(mPageId == 1) {
			scroll2Target();
		}
		mHasNext = pageResult.getHasNext();
		mListView.setHasMoreData(mHasNext);  //设置是否还有更多数据
		if (pageResult.getHasNext()) {
			mPageId = pageResult.getNext();
		}
	}
	
	/**
	 * 第一次进来，如果点击评论则scrollview滚动到评论部分，否则滚到顶部
	 * scrollview嵌套listview时候，有时候会自动滚动到listview的第一个item
	 * 所以如果不是点击评论进来的要滚动到顶部
	 */
	private void scroll2Target() {
		if(isCommnet) {   //如果点击评论进来的，则滚动到评论处
			TaskExecutor.scheduleTaskOnUiThread(150, new Runnable() {
				@Override
				public void run() {
					int height = mQuTuLayout.getHeight();
					mScrollView.scrollTo(0, height);
				}
			});
		} else {
			TaskExecutor.scheduleTaskOnUiThread(150, new Runnable() {
				@Override
				public void run() {
					mScrollView.scrollTo(0, 0);
				}
			});
		}
	}

	/**
	 * 消息处理类
	 * @author lling
	 * 
	 */
	static class ClassHandler extends Handler {
		WeakReference<TuDetailActivity> mReference;
		ClassHandler(TuDetailActivity activity) {
			mReference = new WeakReference<TuDetailActivity>(activity);
		}
		public void handleMessage(Message msg) {
			final TuDetailActivity activity = mReference.get();
			if(activity == null) {
				return;
			}
			switch (msg.what) {
			case Constants.SUCCESS: // 获取评论数据成功
				PageResult pageResult = (PageResult)msg.getData().getSerializable("pageResult");
				activity.loadSuccess(pageResult);
				activity.mListView.onFootLoadingComplete(true);
				break;
			case Constants.FAILURE:
				activity.mListView.onFootLoadingComplete(true);
				break;
			case Constants.SUCCESS_1: // 发表评论成功
				ProgressDialogUtils.dismiss();
				activity.commentSuccess();
				break;
			case Constants.FAILURE_1:
				ProgressDialogUtils.dismiss();
				break;
			}
		}
	}

	/**
	 * 评论成功
	 */
	private void commentSuccess() {
		Comment comment = new Comment();
		comment.setContent(mCommentContentET.getText().toString().trim());
		comment.setUserId(App.currentUser.getId());
		comment.setPortraitUrl(App.currentUser.getPortraitUrl());
		comment.setUserNike(App.currentUser.getUserNike());
		comment.setCreateDate(new Date());
		mCommentLists.add(0, comment);
		mCommentAdapter.onDataChange(mCommentLists);
		mCommentContentET.setText("");
		
		mJoke.setCommentNum(mJoke.getCommentNum()+1);
		mCommentTV.setText(String.valueOf(mJoke.getCommentNum()));
		
		mListView.setSelectionAfterHeaderView();//选中第一条
	}
	
	@OnClick(R.id.add_comment_btn)
	private void sendComment(View view) {
		ToolsUtils.hideKeyboard(mCommentTV);
		if(App.currentUser == null) {  //用户未登录
			Intent intent = new Intent(this, LoginActivity.class);
			startActivityWithAnimation(intent);
			return;
		}
		String content = mCommentContentET.getText().toString().trim();
		if(Util.isEmpty(content)) {
			ToastUtils.showMessage(getApplicationContext(), 
					R.string.comment_content_null);
			return;
		}
		content = ToolsUtils.Html2Text(content);
		if(Util.isEmpty(content)) {
			ToastUtils.showMessage(getApplicationContext(), 
					R.string.input_invalide);
			return;
		}
		if(mJoke == null) {
			return;
		}
		ProgressDialogUtils.showProgressDialog(this, getString(R.string.commenting));
		mQuShiService.addComment(mHandler, mJokeId, content);
	}
	
	@OnClick(R.id.back)
	private void back(View view) {
		if(mIsOpenFromPush && !App.isStart) {
			Intent intent = new Intent(this, SplashActivity.class);
			startActivityWithAnimation(intent);
		}
		finishWithAnimation();
	}
	
	@Override
	public void onBackPressed() {
		if(mIsOpenFromPush && !App.isStart) {
			Intent intent = new Intent(this, SplashActivity.class);
			startActivityWithAnimation(intent);
		}
		super.onBackPressed();
	}
	
	@Override
	protected void onResume() {
		MobclickAgent.onPageStart("TuDetailActivity"); //统计页面
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		MobclickAgent.onPageEnd("TuDetailActivity");
		if(ToolsUtils.isKeybordShow(this)) {
			ToolsUtils.hideKeyboard(mCommentContentET);
		}
		super.onPause();
	}
	
	// push进来的界面要进行应用程序初始化
	private void init() {
		initYouMeng();
		App.currentUser = (User) spUtil.getObject("user", null);
		// 初始化短信接口
		SMSSDK.initSDK(this, getString(R.string.sina_appid),
				getString(R.string.youmeng_appid));
		initWeiXin();
		initTencent();
	}

	private void initYouMeng() {
		AnalyticsConfig.enableEncrypt(true);
		MobclickAgent.openActivityDurationTrack(false);
		PushAgent mPushAgent = PushAgent.getInstance(this);
		mPushAgent.onAppStart();
		if (spUtil.getBoolean(Constants.IS_RECEIVE_PUSH, true)) {
			mPushAgent.enable();
		} else {
			mPushAgent.disable();
		}
	}

	private void initWeiXin() {
		IWXAPI api = WXAPIFactory.createWXAPI(this,
				com.lling.qiqu.wxapi.Constants.APP_ID);
		api.registerApp(com.lling.qiqu.wxapi.Constants.APP_ID);
	}

	private void initTencent() {
		try {
			ApplicationInfo appInfo = this.getPackageManager()
					.getApplicationInfo(getPackageName(),
							PackageManager.GET_META_DATA);
			int appId = appInfo.metaData.getInt("TECENT_APPID", -1);
			if (appId == -1) {
				return;
			}
			App.mTencent = Tencent.createInstance(String.valueOf(appId),
					this.getApplicationContext());
			String openId = spUtil.getString(
					com.tencent.connect.common.Constants.PARAM_OPEN_ID, null);
			String token = spUtil.getString(
					com.tencent.connect.common.Constants.PARAM_ACCESS_TOKEN,
					null);
			long expires = spUtil.getLong(
					com.tencent.connect.common.Constants.PARAM_EXPIRES_IN,
					System.currentTimeMillis());
			if (openId != null) {
				App.mTencent.setOpenId(openId);
			}
			if (token != null) {
				App.mTencent
						.setAccessToken(token, String.valueOf((expires - System
								.currentTimeMillis()) / 1000));
			}
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
	}
} public class JokeAdapter extends BaseAdapter{
	
	private final static int TYPE_COUNT = 2;  //类型种类
	private final static int TYPE_TEXT = 0;  //文本类型
	private final static int TYPE_IMG = 1;   //图片类型
	
	private List<Joke> mList;
	private Context mContext;
	private DingCaiDAO mDingOrCaiDAO;
	private int mUserId = -1;
	private int mMaxWidth;
	private int mMaxHeight;
	
	private SharePopWindow mSharePopWindow;
	private SharePreferenceUtil mSpUtil;
 	
    public JokeAdapter(Context context) {
    	mContext = context;
    	mDingOrCaiDAO = new DingCaiDAO(context);
    	mMaxWidth = DensityUtil.getWidthInPx(context) - DensityUtil.dip2px(context, 32);
    	mMaxHeight = DensityUtil.getHeightInPx(context) - DensityUtil.getStatusHeight(mContext)
    			- DensityUtil.dip2px(context, 96);
    	mSharePopWindow = new SharePopWindow(context);
    	mSpUtil = App.getInstance().getSpUtil();
	}
    
    public void setList(List<Joke> lists) {
		this.mList = lists;
	}
    
    public void onDataChange(List<Joke> lists) {
		this.mList = lists;
		notifyDataSetChanged();
	}
    
	@Override
	public int getCount() {
		if(mList == null) {
			return 0;
		}
		return mList.size();
	}

	@Override
	public Object getItem(int position) {
		if(mList == null) {
			return null;
		}
		return mList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}
	
	// 每个convert view都会调用此方法，获得当前所需要的view样式
	@Override
	public int getItemViewType(int position) {
		int type = mList.get(position).getType();
		if(type == Joke.TYPE_QUSHI) {
			return TYPE_TEXT;
		} else if(type == Joke.TYPE_QUTU || type == Joke.TYPE_MEITU) {
			return TYPE_IMG;
		}
		return TYPE_TEXT;
	}

	@Override
	public int getViewTypeCount() {
		return TYPE_COUNT;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		TextHolder textHolder = null;
		ImgHolder imgHolder = null;
		int type = getItemViewType(position);
		if(convertView == null) {
			switch (type) {
			case TYPE_TEXT:
				textHolder = new TextHolder();
	            convertView = LayoutInflater.from(mContext).inflate(
	                    R.layout.listitem_qushi, null);
	            textHolder.userPortraitIV = (ImageView) convertView.findViewById(R.id.user_img);
	            textHolder.userNickTV = (TextView) convertView.findViewById(R.id.user_nick);
	            textHolder.createTimeTV = (TextView) convertView.findViewById(R.id.create_date);
	            textHolder.contentTV = (TextView) convertView.findViewById(R.id.qushi_content);
	            textHolder.dingTV = (TextView) convertView.findViewById(R.id.ding_tv);
	            textHolder.caiTV = (TextView) convertView.findViewById(R.id.cai_tv);
	            textHolder.commentTV = (TextView) convertView.findViewById(R.id.comment_tv);
	            textHolder.shareTV = (TextView) convertView.findViewById(R.id.share_tv);
	            convertView.setTag(textHolder);
				break;
			case TYPE_IMG:
				imgHolder = new ImgHolder();
	            convertView = LayoutInflater.from(mContext).inflate(
	                    R.layout.listitem_qutu, null);
	            imgHolder.userPortraitIV = (ImageView) convertView.findViewById(R.id.user_img);
	            imgHolder.userNickTV = (TextView) convertView.findViewById(R.id.user_nick);
	            imgHolder.createTimeTV = (TextView) convertView.findViewById(R.id.create_date);
	            imgHolder.titleTV = (TextView) convertView.findViewById(R.id.qutu_title);
	            imgHolder.contentIV = (LoadPercentImageView) convertView.findViewById(R.id.qutu_content);
	            imgHolder.dingTV = (TextView) convertView.findViewById(R.id.ding_tv);
	            imgHolder.caiTV = (TextView) convertView.findViewById(R.id.cai_tv);
	            imgHolder.commentTV = (TextView) convertView.findViewById(R.id.comment_tv);
	            imgHolder.shareTV = (TextView) convertView.findViewById(R.id.share_tv);
	            imgHolder.contentIV.setMaxWidth(mMaxWidth);
	            imgHolder.contentIV.setMaxHeight(mMaxHeight);
	            convertView.setTag(imgHolder);
				break;
			}
		} else {
			switch (type) {
			case TYPE_TEXT:
				textHolder = (TextHolder) convertView.getTag();
				break;
			case TYPE_IMG:
				imgHolder = (ImgHolder) convertView.getTag();
				break;
			}
		}
		if(App.currentUser != null) {
    		mUserId = App.currentUser.getId();
    	}
		final Joke joke = mList.get(position);
	    final DingOrCai dingOrCai = mDingOrCaiDAO.getDingOrCai(mUserId, joke.getId());
	    OnClickListener dingListener = new DingClickListenner(dingOrCai, joke);
		OnClickListener caiListener = new CaiClickListenner(dingOrCai, joke);
	    switch (type) {
		case TYPE_TEXT:
			if(dingOrCai != null) {
	        	if(dingOrCai.isDing()) {
	        		textHolder.dingTV.setSelected(true);
	        		textHolder.caiTV.setSelected(false);
	        		if(joke.getSupportsNum() < dingOrCai.getNum()) {
	        			joke.setSupportsNum(dingOrCai.getNum());
	        		}
	        	} else {
	        		textHolder.dingTV.setSelected(false);
	        		textHolder.caiTV.setSelected(true);
	        		if(joke.getOpposesNum() < dingOrCai.getNum()) {
	        			joke.setOpposesNum(dingOrCai.getNum());
	        		}
	        	}
	        } else {
	        	textHolder.dingTV.setSelected(false);
	        	textHolder.caiTV.setSelected(false);
	        }
	        textHolder.createTimeTV.setText(Util.getFormatDate(joke.getCreateDate()));
	        textHolder.dingTV.setText(String.valueOf(joke.getSupportsNum()));
	        textHolder.caiTV.setText(String.valueOf(joke.getOpposesNum()));
	        textHolder.contentTV.setText(joke.getContent());
	        textHolder.commentTV.setText(String.valueOf(joke.getCommentNum()));
	        textHolder.dingTV.setOnClickListener(dingListener);
	        textHolder.caiTV.setOnClickListener(caiListener);
	        textHolder.commentTV.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(mContext, QuShiDetailActivity.class);
					intent.putExtra("qushi", joke);
					intent.putExtra("isComment", true);
					mContext.startActivity(intent);
					App.isStartOtherActivity = true;
				}
			});
	        textHolder.shareTV.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mSharePopWindow.setmJoke(joke);
					mSharePopWindow.showAtLocation(v.getRootView(), Gravity.LEFT | Gravity.BOTTOM, 0, 0);
				}
			});
	        //是自己发的
	        if(App.currentUser != null && App.currentUser.getId()==joke.getUserId()) {
	        	textHolder.userNickTV.setText(App.currentUser.getUserNike());
	        	BitmapUtil.display(textHolder.userPortraitIV, App.currentUser.getPortraitUrl());
	        } else {
	        	textHolder.userNickTV.setText(joke.getUserNike());
	        	BitmapUtil.display(textHolder.userPortraitIV, joke.getPortraitUrl());
	        }
			break;
		case TYPE_IMG:
			if(dingOrCai != null) {
	        	if(dingOrCai.isDing()) {
	        		imgHolder.dingTV.setSelected(true);
	        		imgHolder.caiTV.setSelected(false);
	        		if(joke.getSupportsNum() < dingOrCai.getNum()) {
	        			joke.setSupportsNum(dingOrCai.getNum());
	        		}
	        	} else {
	        		imgHolder.dingTV.setSelected(false);
	        		imgHolder.caiTV.setSelected(true);
	        		if(joke.getOpposesNum() < dingOrCai.getNum()) {
	        			joke.setOpposesNum(dingOrCai.getNum());
	        		}
	        	}
	        } else {
	        	imgHolder.dingTV.setSelected(false);
	        	imgHolder.caiTV.setSelected(false);
	        }
			int width = joke.getImgWidth();
	        int height = joke.getImgHeight();
	        if(width != 0 && width != 0) {
	        	float scale = (float)width / (float)mMaxWidth;
	            height = (int)(height / scale);
	            if(height > mMaxHeight) {
	            	height = mMaxHeight;
	            }
	            imgHolder.contentIV.setLayoutParams(new LinearLayout.LayoutParams(mMaxWidth, height));
	        }
	        imgHolder.contentIV.setProgress(0);
	        imgHolder.contentIV.setComplete(false);
	        imgHolder.createTimeTV.setText(Util.getFormatDate(joke.getCreateDate()));
	        if(Util.isNotEmpty(joke.getTitle())) {
	        	imgHolder.titleTV.setText(joke.getTitle());
	        	imgHolder.titleTV.setVisibility(View.VISIBLE);
	        } else {
	        	imgHolder.titleTV.setVisibility(View.GONE);
	        }
	        imgHolder.dingTV.setText(String.valueOf(joke.getSupportsNum()));
	        imgHolder.caiTV.setText(String.valueOf(joke.getOpposesNum()));
	        imgHolder.commentTV.setText(String.valueOf(joke.getCommentNum()));
	        imgHolder.dingTV.setOnClickListener(dingListener);
	        imgHolder.caiTV.setOnClickListener(caiListener);
	        imgHolder.commentTV.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(mContext, TuDetailActivity.class);
					intent.putExtra("content", joke);
					intent.putExtra("isComment", true);
					mContext.startActivity(intent);
					App.isStartOtherActivity = true;
				}
			});
	        imgHolder.shareTV.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mSharePopWindow.setmJoke(joke);
					mSharePopWindow.showAtLocation(v.getRootView(), Gravity.LEFT | Gravity.BOTTOM, 0, 0);
				}
			});
	        //图片的加载放后面
	        //是自己发的
	        if(App.currentUser != null && App.currentUser.getId()==joke.getUserId()) {
	        	imgHolder.userNickTV.setText(App.currentUser.getUserNike());
	        	BitmapUtil.display(imgHolder.userPortraitIV, App.currentUser.getPortraitUrl());
	        } else {
	        	imgHolder.userNickTV.setText(joke.getUserNike());
	        	BitmapUtil.display(imgHolder.userPortraitIV, joke.getPortraitUrl());
	        }
	        if(HttpUtil.isWifi(mContext) || mSpUtil.getBoolean(Constants.IS_LOAD_IMG, true)) {  //仅wifi状态下加载网络
	        	imgHolder.contentIV.setLoadImg(true);
	        	BitmapUtil.display(imgHolder.contentIV, joke.getImgUrl(), new PercentImageViewLoadCallBack());
	        } else {
	        	imgHolder.contentIV.setLoadImg(false);
	        }
			break;
		}
	    
        return convertView;
	}

	private class TextHolder {
		private ImageView userPortraitIV;
		private TextView userNickTV;
		private TextView createTimeTV;
		private TextView contentTV;
		private TextView dingTV;
		private TextView caiTV;
		private TextView commentTV;
		private TextView shareTV;
    }
	
	private class ImgHolder {
		private ImageView userPortraitIV;
		private TextView userNickTV;
		private TextView createTimeTV;
		private LoadPercentImageView contentIV;
		private TextView titleTV;
		private TextView dingTV;
		private TextView caiTV;
		private TextView commentTV;
		private TextView shareTV;
    }
	
	class DingClickListenner implements OnClickListener {
		private DingOrCai dingOrCai;
		private Joke joke;
		public DingClickListenner(DingOrCai dingOrCai, Joke joke) {
			this.dingOrCai = dingOrCai;
			this.joke = joke;
		}
		
		@Override
		public void onClick(View v) {
			if(dingOrCai != null) {
				if(dingOrCai.isDing()) {
					ToastUtils.showMessage(mContext, R.string.has_ding);
				} else {
					ToastUtils.showMessage(mContext, R.string.has_cai);
				}
				return;
			}
			if(v.isSelected()) {
				ToastUtils.showMessage(mContext, R.string.has_ding);
				return;
			}
			View caiView = ((LinearLayout)v.getParent().getParent()).findViewById(R.id.cai_tv);
			if(caiView.isSelected()) {
				ToastUtils.showMessage(mContext, R.string.has_cai);
				return;
			}
			final View view = ((RelativeLayout)v.getParent()).getChildAt(1);
			Animation addOneAnimation = AnimationUtils.loadAnimation(mContext, R.anim.add_one);
			addOneAnimation.setAnimationListener(new AnimationListener() {
				@Override
				public void onAnimationStart(Animation animation) {
					view.setVisibility(View.VISIBLE);
				}
				@Override
				public void onAnimationRepeat(Animation animation) {
				}
				@Override
				public void onAnimationEnd(Animation animation) {
					view.setVisibility(View.GONE);
				}
			});
			view.startAnimation(addOneAnimation);
			v.setSelected(true);
			joke.setSupportsNum(joke.getSupportsNum()+1);
			((TextView)v).setText(String.valueOf(joke.getSupportsNum()));
			mDingOrCaiDAO.dingOrCai(mUserId, joke.getId(), DingOrCai.DING, joke.getSupportsNum());
		}
	}
	
	class CaiClickListenner implements OnClickListener {
		private DingOrCai dingOrCai;
		private Joke joke;
		public CaiClickListenner(DingOrCai dingOrCai, Joke joke) {
			this.dingOrCai = dingOrCai;
			this.joke = joke;
		}
		
		@Override
		public void onClick(View v) {
			if(dingOrCai != null) {
				if(dingOrCai.isDing()) {
					ToastUtils.showMessage(mContext, R.string.has_ding);
				} else {
					ToastUtils.showMessage(mContext, R.string.has_cai);
				}
				return;
			}
			if(v.isSelected()) {
				ToastUtils.showMessage(mContext, R.string.has_cai);
				return;
			}
			View dingView = ((LinearLayout)v.getParent().getParent()).findViewById(R.id.ding_tv);
			if(dingView.isSelected()) {
				ToastUtils.showMessage(mContext, R.string.has_ding);
				return;
			}
			final View view = ((RelativeLayout)v.getParent()).getChildAt(1);
			Animation addOneAnimation = AnimationUtils.loadAnimation(mContext, R.anim.add_one);
			addOneAnimation.setAnimationListener(new AnimationListener() {
				@Override
				public void onAnimationStart(Animation animation) {
					view.setVisibility(View.VISIBLE);
				}
				@Override
				public void onAnimationRepeat(Animation animation) {
				}
				@Override
				public void onAnimationEnd(Animation animation) {
					view.setVisibility(View.GONE);
				}
			});
			view.startAnimation(addOneAnimation);
			v.setSelected(true);
			joke.setOpposesNum(joke.getOpposesNum()+1);
			((TextView)v).setText(String.valueOf(joke.getOpposesNum()));
			mDingOrCaiDAO.dingOrCai(mUserId, joke.getId(), DingOrCai.CAI, joke.getOpposesNum());
		}
	}
	
} public class Joke implements Serializable{

	private static final long serialVersionUID = 4646260119535165219L;

	//type标记
	public static final int TYPE_QUSHI = 1;
	public static final int TYPE_QUTU = 2;
	public static final int TYPE_MEITU = 3;
	public static final int TYPE_GIF = 4;
	
	//是否通过审核标记
	public static final int NOT_PASS = 0;
	public static final int PASS = 1;
	
	//是否被删除标记
	public static final int NOT_DELETE = 0;
	public static final int DELETE = 1;
	
	//最新最热排序标记
	public static final int SORT_NEW = 0;
	public static final int SORT_HOT = 1;
	
	/**
	 * 笑话id
	 */
	private int id;
	
	/**
	 * 笑话标题
	 */
	private String title;
	
	/**
	 * 笑话内容
	 */
	private String content;
	
	/**
	 * 图片地址
	 */
	private String ImgUrl;
	
	/**
	 * gif地址
	 */
	private String GifUrl;
	
	/**
	 * 笑话支持数
	 */
	private int supportsNum;
	
	/**
	 * 笑话反对数
	 */
	private int opposesNum;
	
	/**
	 * 笑话评论数
	 */
	private int commentNum;
	
	/**
	 * 笑话创建日期
	 */
	private Date createDate;
	
	/**
	 * 是否删除标记（0：未删除、1：已删除）
	 */
	private int isDelete;
	
	/**
	 * 笑话类别（1：趣事、2：趣图、3：美图、4：gif）
	 */
	private int type;
	
	/**
	 * 是否审核通过（0：未通过、1：已通过）
	 */
	private int isPass;
	
	/**
	 * 发表用户
	 */
	private int userId;
	
	/**
	 * 发表用户头像
	 */
	private String portraitUrl;

	/**
	 * 用户昵称
	 */
	private String userNike;
	
	/**
	 * 图片宽度
	 */
	private int imgWidth;
	
	/**
	 * 图片高度
	 */
	private int imgHeight;
	
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getImgUrl() {
		return ImgUrl;
	}

	public void setImgUrl(String imgUrl) {
		ImgUrl = imgUrl;
	}

	public String getGifUrl() {
		return GifUrl;
	}

	public void setGifUrl(String gifUrl) {
		GifUrl = gifUrl;
	}

	public int getSupportsNum() {
		return supportsNum;
	}

	public void setSupportsNum(int supportsNum) {
		this.supportsNum = supportsNum;
	}

	public int getOpposesNum() {
		return opposesNum;
	}

	public void setOpposesNum(int opposesNum) {
		this.opposesNum = opposesNum;
	}

	public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}

	public int getIsDelete() {
		return isDelete;
	}

	public void setIsDelete(int isDelete) {
		this.isDelete = isDelete;
	}

	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}

	public int getIsPass() {
		return isPass;
	}

	public void setIsPass(int isPass) {
		this.isPass = isPass;
	}

	public int getUserId() {
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	public String getPortraitUrl() {
		return portraitUrl;
	}

	public void setPortraitUrl(String portraitUrl) {
		this.portraitUrl = portraitUrl;
	}

	public String getUserNike() {
		return userNike;
	}

	public void setUserNike(String userNike) {
		this.userNike = userNike;
	}

	public int getCommentNum() {
		return commentNum;
	}

	public void setCommentNum(int commentNum) {
		this.commentNum = commentNum;
	}

	public int getImgWidth() {
		return imgWidth;
	}

	public void setImgWidth(int imgWidth) {
		this.imgWidth = imgWidth;
	}

	public int getImgHeight() {
		return imgHeight;
	}

	public void setImgHeight(int imgHeight) {
		this.imgHeight = imgHeight;
	}
	
} public class Constants {
	
	public static final boolean DEBUG = false;

	//SplashActivity
	public static final String FIRST_USE = "firstUse";
	public static final String IS_RECEIVE_PUSH = "isReceivePush";
	public static final String IS_LOAD_IMG = "isLoadImg";
	
	//http请求超时时间
	public static final int REQUEST_TIME_OUT = 15 * 1000;
	
	public static final int SUCCESS = 200;
	public static final int FAILURE = 500;
	public static final int SUCCESS_1 = 201;
	public static final int FAILURE_1 = 501;
	public static final int SUCCESS_2 = 202;
	public static final int FAILURE_2 = 502;
	
	public static final String SERVER_EXCEPTION = "500";
	public static final String PARAM_INVALUD = "501";
	public static final String SOURCE_EXISTS = "502";
	public static final String SOURCE_NOT_EXISTS = "503";
	public static final String OTHER_ERROR = "504";
	
	public static final String UPLOADFILE_PRE = "http://7xjehg.com1.z0.glb.clouddn.com/";
	public static final String LOGP_URL = "http://7xjehg.com1.z0.glb.clouddn.com/logo.png";
	
	public static final String CACHE_ALL_NEW = "cache_all_new";
	public static final String CACHE_ALL_HOT = "cache_all_hot";
	public static final String CACHE_QUSHI_NEW = "cache_qushi_new";
	public static final String CACHE_QUSHI_HOT = "cache_qushi_hot";
	public static final String CACHE_QUTU_NEW = "cache_qutu_new";
	public static final String CACHE_QUTU_HOT = "cache_qutu_hot";
	public static final String CACHE_MEITU_NEW = "cache_meitu_new";
	public static final String CACHE_MEITU_HOT = "cache_meitu_hot";
	
	//广点通
	public static final boolean TESTAD = false;   //标记测试
	public static final String GDT_APPId = "1104671631";
	public static final String GDT_APPWallPosId = "9050601571008638";
	public static final String GDT_SPLASHPosId = "5040000561500800";
	public static final String GDT_BANNERPosId = "7040104593531094";
	public static final String GDT_MEITU_BANNERPosId = "1030305547810972";
	
	//验证码发送短信
	public static final String SMS_SENDER = "10657120610111";
	
} public class PageResult<T> implements Serializable {

	private static final long serialVersionUID = -8689423380671812808L;

	public static final int DEFAULT_PAGE_SIZE = 10;
	
	private int pageIndex;
	private int pageSize;
	private int totalCount;
	private int pageCount;
	private List<T> list;

	public PageResult() {
		pageIndex = 1;
		pageSize = DEFAULT_PAGE_SIZE;
	}

	public PageResult(String _pageIndex) {
		this(_pageIndex, "");
	}

	public PageResult(String _pageIndex, String _pageSize) {
		int pageIndex = 1;
		int pageSize = DEFAULT_PAGE_SIZE;
		if (null == _pageIndex || "".equals(_pageIndex)) {
			pageIndex = 1;
		} else {
			try {
				pageIndex = Integer.parseInt(_pageIndex);
			} catch (Exception e) {
				pageIndex = 1;
			}
		}

		if (null == _pageSize || "".equals(_pageSize)) {
			pageSize = DEFAULT_PAGE_SIZE;
		} else {
			try {
				pageSize = Integer.parseInt(_pageSize);
			} catch (Exception e) {
				pageSize = DEFAULT_PAGE_SIZE;
			}
		}
		if (pageIndex < 1) {
			pageIndex = 1;
		}
		if (pageSize < 1) {
			pageSize = 1;
		}
		this.pageIndex = pageIndex;
		this.pageSize = pageSize;

	}

	public PageResult(int totalCount, Limit limit, List<T> list) {
		this.list = list;
        if(null == limit){
        	return;
        }
		this.pageIndex = limit.getPageId();
		this.pageSize = limit.getSize();
		this.setTotalCount(totalCount);
	}

	public PageResult(int pageIndex, int pageSize) {
		if (pageIndex < 1) {
			pageIndex = 1;
		}
		if (pageSize < 1) {
			pageSize = 1;
		}
		this.pageIndex = pageIndex;
		this.pageSize = pageSize;

	}

	/**
	 * @return the list
	 */
	public List<T> getList() {
		return list;
	}

	/**
	 * @param list the list to set
	 */
	public void setList(List<T> list) {
		this.list = list;
	}

	public PageResult(int pageIndex) {
		this(pageIndex, DEFAULT_PAGE_SIZE);
	}

	public int getPageIndex() {
		return pageIndex;
	}

	public int getPageSize() {
		return pageSize;
	}

	public int getTotalCount() {
		return totalCount;
	}

	public int getPageCount() {
		return pageCount;
	}

	public int getFirstResult() {
		return (pageIndex - 1) * pageSize;
	}

	public boolean getHasPrevious() {
		return pageIndex > 1;
	}

	public boolean getHasNext() {
		return pageIndex < pageCount;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
		pageCount = totalCount / pageSize + (totalCount % pageSize == 0 ? 0 : 1);
		if (0 == totalCount) {
			if (pageIndex != 1) {
				pageIndex = 1;
			}
		} else {
			if (pageIndex > pageCount) {
				pageIndex = pageCount;
			}
		}
	}

	public int getPrev() {
		return this.pageIndex - 1;
	}

	public int getNext() {
		return this.pageIndex + 1;
	}

	public boolean isEmpty() {
		return 0 == totalCount;
	}

	public void setPageIndex(int pageIndex) {
		this.pageIndex = pageIndex;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public void setPageCount(int countInPage) {
		this.pageCount = countInPage;
	}

} public interface IJokeService {

	/**
	 * 获取趣事列表
	 * @param handler
	 * @param newOrHotFlag
	 * @param offset
	 * @param count
	 */
	public void getList(Handler handler, int type, int newOrHotFlag, int offset, int count);
	
	/**
	 * 刷新趣事列表
	 * @param handler
	 * @param newOrHotFlag
	 * @param count
	 */
	public void refush(Handler handler, int type, int newOrHotFlag, int count);
	
	/**
	 * 获取所有内容列表
	 * @param handler
	 * @param newOrHotFlag
	 * @param offset
	 * @param count
	 */
	public void getAll(Handler handler, int newOrHotFlag, int offset, int count);
	
	/**
	 * 刷新所有内容列表
	 * @param handler
	 * @param newOrHotFlag
	 * @param count
	 */
	public void refushAll(Handler handler, int newOrHotFlag, int count);
	
	/**
	 * 根据jokeid获取评论列表
	 * @param handler
	 * @param jokeId
	 * @param offset
	 * @param count
	 */
	public void getCommentByJokeId(Handler handler, int jokeId, int offset, int count);
	
	/**
	 * 顶joke
	 * @param dingOrCais
	 */
	public void ding(List<DingOrCai> dingOrCais);
	
	/**
	 * 踩joke
	 * @param dingOrCais
	 */
	public void cai(List<DingOrCai> dingOrCais);
	
	/**
	 * 用户评论joke
	 * @param handler
	 * @param jokeId
	 * @param userId
	 * @param userPortrait
	 * @param userNick
	 * @param content
	 */
	public void addComment(Handler handler, Integer jokeId, String content);
	
	/**
	 * 根据jokeId获取joke对象
	 * @param apiCallBack
	 * @param jokeId
	 */
	public void getJokeById(ApiCallBack apiCallBack, Integer jokeId);
} public class JokeServiceImpl implements IJokeService {
	private static final String TAG = "QuShiServiceImpl";
	private Context mContext;
	private DingCaiDAO mDingCaiDAO;
	
	public JokeServiceImpl(Context context) {
		mContext = context;
		mDingCaiDAO = new DingCaiDAO(context);
	}
	
	@Override
	public void getAll(final Handler handler, int newOrHotFlag, int offset, int count) {
		HttpUtils http = new HttpUtils();
		http.configDefaultHttpCacheExpiry(1000 * 60 * 10); //缓存超期时间10分钟
		http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("newOrHotFlag", String.valueOf(newOrHotFlag));
		params.addQueryStringParameter("offset", String.valueOf(offset));
		params.addQueryStringParameter("count", String.valueOf(count));
		http.send(HttpRequest.HttpMethod.GET,
			RcpUri.INTERFACE_URI_LIST, params,
			new RequestCallBack<String>() {
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					try {
						String rs = responseInfo.result;
						Map map = FastjsonUtil.json2Map(rs);
						int code = Integer.parseInt(String.valueOf(map.get("code")));
						if (code != 200) {
							//请求失败
							handler.sendEmptyMessage(Constants.FAILURE);
							return;
						}
						PageResult page = FastjsonUtil.deserialize(
								map.get("data").toString(), PageResult.class);
						Message message = new Message();
						Bundle bundle = new Bundle();
						bundle.putSerializable("pageResult", page);
						message.what = Constants.SUCCESS;
						message.setData(bundle);
						handler.sendMessage(message);
					} catch (Exception e) {
						handler.sendEmptyMessage(Constants.FAILURE);
					}
				}
				@Override
				public void onFailure(HttpException error, String msg) {
					handler.sendEmptyMessage(Constants.FAILURE);
				}
			});
	}

	@Override
	public void refushAll(final Handler handler, int newOrHotFlag, int count) {
		HttpUtils http = new HttpUtils();
		http.configDefaultHttpCacheExpiry(0); //缓存超期时间0分钟
		http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("newOrHotFlag", String.valueOf(newOrHotFlag));
		params.addQueryStringParameter("count", String.valueOf(count));
		http.send(HttpRequest.HttpMethod.GET,
			RcpUri.INTERFACE_URI_LIST, params,
			new RequestCallBack<String>() {
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					try {
						String rs = responseInfo.result;
						Map map = FastjsonUtil.json2Map(rs);
						int code = Integer.parseInt(String.valueOf(map.get("code")));
						if (code != 200) {
							//请求失败
							handler.sendEmptyMessage(Constants.FAILURE);
							return;
						}
						PageResult page = FastjsonUtil.deserialize(
								map.get("data").toString(), PageResult.class);
						Message message = new Message();
						Bundle bundle = new Bundle();
						bundle.putSerializable("pageResult", page);
						message.what = Constants.SUCCESS_1;
						message.setData(bundle);
						handler.sendMessage(message);
					} catch (Exception e) {
						handler.sendEmptyMessage(Constants.FAILURE);
					}
				}
				@Override
				public void onFailure(HttpException error, String msg) {
					handler.sendEmptyMessage(Constants.FAILURE);
				}
			});
	}
	
	@Override
	public void getList(final Handler handler, int type, int newOrHotFlag, int offset,
			int count) {
		HttpUtils http = new HttpUtils();
		http.configDefaultHttpCacheExpiry(1000 * 60 * 10); //缓存超期时间10分钟
		http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("type", String.valueOf(type));
		params.addQueryStringParameter("newOrHotFlag", String.valueOf(newOrHotFlag));
		params.addQueryStringParameter("offset", String.valueOf(offset));
		params.addQueryStringParameter("count", String.valueOf(count));
		http.send(HttpRequest.HttpMethod.GET,
			RcpUri.INTERFACE_URI_LIST, params,
			new RequestCallBack<String>() {
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					try {
						String rs = responseInfo.result;
						Map map = FastjsonUtil.json2Map(rs);
						int code = Integer.parseInt(String.valueOf(map.get("code")));
						if (code != 200) {
							//请求失败
							handler.sendEmptyMessage(Constants.FAILURE);
							return;
						}
						PageResult page = FastjsonUtil.deserialize(
								map.get("data").toString(), PageResult.class);
						Message message = new Message();
						Bundle bundle = new Bundle();
						bundle.putSerializable("pageResult", page);
						message.what = Constants.SUCCESS;
						message.setData(bundle);
						handler.sendMessage(message);
					} catch (Exception e) {
						handler.sendEmptyMessage(Constants.FAILURE);
					}
				}
				@Override
				public void onFailure(HttpException error, String msg) {
					handler.sendEmptyMessage(Constants.FAILURE);
				}
			});
	}

	@Override
	public void refush(final Handler handler, int type, int newOrHotFlag, int count) {
		HttpUtils http = new HttpUtils();
		http.configDefaultHttpCacheExpiry(0); //缓存超期时间0分钟
		http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("type", String.valueOf(type));
		params.addQueryStringParameter("newOrHotFlag", String.valueOf(newOrHotFlag));
		params.addQueryStringParameter("count", String.valueOf(count));
		http.send(HttpRequest.HttpMethod.GET,
			RcpUri.INTERFACE_URI_LIST, params,
			new RequestCallBack<String>() {
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					try {
						String rs = responseInfo.result;
						Map map = FastjsonUtil.json2Map(rs);
						int code = Integer.parseInt(String.valueOf(map.get("code")));
						if (code != 200) {
							//请求失败
							handler.sendEmptyMessage(Constants.FAILURE);
							return;
						}
						PageResult page = FastjsonUtil.deserialize(
								map.get("data").toString(), PageResult.class);
						Message message = new Message();
						Bundle bundle = new Bundle();
						bundle.putSerializable("pageResult", page);
						message.what = Constants.SUCCESS_1;
						message.setData(bundle);
						handler.sendMessage(message);
					} catch (Exception e) {
						handler.sendEmptyMessage(Constants.FAILURE);
					}
				}
				@Override
				public void onFailure(HttpException error, String msg) {
					handler.sendEmptyMessage(Constants.FAILURE);
				}
			});
	}

	@Override
	public void getCommentByJokeId(final Handler handler, int jokeId, int offset,
			int count) {
		HttpUtils http = new HttpUtils();
		http.configDefaultHttpCacheExpiry(60); //缓存超期时间10分钟
		http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("qushiId", String.valueOf(jokeId));
		params.addQueryStringParameter("offset", String.valueOf(offset));
		params.addQueryStringParameter("count", String.valueOf(count));
		http.send(HttpRequest.HttpMethod.GET,
			RcpUri.INTERFACE_URI_GET_COMMENTS, params,
			new RequestCallBack<String>() {
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					String rs = responseInfo.result;
					Map map = FastjsonUtil.json2Map(rs);
					int code = Integer.parseInt(String.valueOf(map.get("code")));
					if (code != 200) {
						//请求失败
						handler.sendEmptyMessage(Constants.FAILURE);
						return;
					}
					PageResult page = FastjsonUtil.deserialize(
							map.get("data").toString(), PageResult.class);
					Message message = new Message();
					Bundle bundle = new Bundle();
					bundle.putSerializable("pageResult", page);
					message.what = Constants.SUCCESS;
					message.setData(bundle);
					handler.sendMessage(message);
				}
				@Override
				public void onFailure(HttpException error, String msg) {
					handler.sendEmptyMessage(Constants.FAILURE);
				}
			});
	}

	@Override
	public void ding(final List<DingOrCai> dingOrCais) {
		if(dingOrCais == null || dingOrCais.size() == 0) {
			return;
		}
		StringBuilder sb = new StringBuilder();
		for (DingOrCai dingOrCai : dingOrCais) {
			sb.append(dingOrCai.getJokeId()).append(",");
		}
		String ids = sb.toString().substring(0, sb.toString().length() - 1);
		HttpUtils http = new HttpUtils();
		http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("ids", ids);
		http.send(HttpRequest.HttpMethod.POST,
			RcpUri.INTERFACE_URI_DING, params,
			new RequestCallBack<String>() {
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					String rs = responseInfo.result;
					Map map = FastjsonUtil.json2Map(rs);
					int code = Integer.parseInt(String.valueOf(map.get("code")));
					if (code != 200) {
						//请求失败
						Log.e(TAG, "ding failure:" + map.get("desc"));
						return;
					}
					//修改本地数据库
					TaskExecutor.executeTask(new Runnable() {
						@Override
						public void run() {
							mDingCaiDAO.upload(dingOrCais);
						}
					});
				}
				@Override
				public void onFailure(HttpException error, String msg) {
					Log.e(TAG, "ding failure", error);
				}
			});
	}

	@Override
	public void cai(final List<DingOrCai> dingOrCais) {
		if(dingOrCais == null || dingOrCais.size() == 0) {
			return;
		}
		StringBuilder sb = new StringBuilder();
		for (DingOrCai dingOrCai : dingOrCais) {
			sb.append(dingOrCai.getJokeId()).append(",");
		}
		String ids = sb.toString().substring(0, sb.toString().length() - 1);
		HttpUtils http = new HttpUtils();
		http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("ids", ids);
		http.send(HttpRequest.HttpMethod.POST,
			RcpUri.INTERFACE_URI_CAI, params,
			new RequestCallBack<String>() {
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					String rs = responseInfo.result;
					Map map = FastjsonUtil.json2Map(rs);
					int code = Integer.parseInt(String.valueOf(map.get("code")));
					if (code != 200) {
						//请求失败
						Log.e(TAG, "cai failure:" + map.get("desc"));
						return;
					}
					//修改本地数据库
					TaskExecutor.executeTask(new Runnable() {
						@Override
						public void run() {
							mDingCaiDAO.upload(dingOrCais);
						}
					});
				}
				@Override
				public void onFailure(HttpException error, String msg) {
					Log.e(TAG, "cai failure", error);
				}
			});
	}

	@Override
	public void addComment(final Handler handler, Integer jokeId, String content) {
		if(App.currentUser == null || Util.isEmpty(content)) {
			return;
		}
		HttpUtils http = new HttpUtils();
		http.configDefaultHttpCacheExpiry(1000 * 60 * 10); //缓存超期时间10分钟
		http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("jokeId", String.valueOf(jokeId));
		params.addQueryStringParameter("userId", String.valueOf(App.currentUser.getId()));
		params.addQueryStringParameter("userPortrait", App.currentUser.getPortraitUrl());
		try {
			params.addQueryStringParameter("userNick", 
					URLEncoder.encode(App.currentUser.getUserNike(), "UTF-8"));
			params.addQueryStringParameter("content", 
					URLEncoder.encode(content, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		http.send(HttpRequest.HttpMethod.POST,
			RcpUri.INTERFACE_URI_COMMENT, params,
			new RequestCallBack<String>() {
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					String rs = responseInfo.result;
					Map map = FastjsonUtil.json2Map(rs);
					int code = Integer.parseInt(String.valueOf(map.get("code")));
					if (code != 200) {
						//请求失败
						Log.e(TAG, "comment failure");
						ToastUtils.showMessage(mContext, R.string.comment_fail);
						handler.sendEmptyMessage(Constants.FAILURE_1);
						return;
					}
					Log.e(TAG, "comment success");
					handler.sendEmptyMessage(Constants.SUCCESS_1);
				}
				@Override
				public void onFailure(HttpException error, String msg) {
					Log.e(TAG, "comment failure", error);
					handler.sendEmptyMessage(Constants.FAILURE_1);
					if(!HttpUtil.isNetworkAvailable(mContext)) {
						ToastUtils.showMessage(mContext, R.string.no_net);
					} else {
						ToastUtils.showMessage(mContext, R.string.comment_fail);
					}
				}
			});
	}

	@Override
	public void getJokeById(final ApiCallBack apiCallBack, Integer jokeId) {
		HttpUtils http = new HttpUtils();
		http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
		http.configDefaultHttpCacheExpiry(0); 
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("jokeId", String.valueOf(jokeId));
		http.send(HttpRequest.HttpMethod.GET,
			RcpUri.INTERFACE_URI_GET_JOKE, params,
			new RequestCallBack<String>() {
				@SuppressWarnings("rawtypes")
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					String rs = responseInfo.result;
					Map map = FastjsonUtil.json2Map(rs);
					int code = Integer.parseInt(String.valueOf(map.get("code")));
					if(code == Constants.SUCCESS) {
						Log.e(TAG, "getJokeById success");
						Joke joke = FastjsonUtil.deserialize(
								map.get("data").toString(), Joke.class);
						apiCallBack.onSuccess(joke);
					} else {
						Log.e(TAG, "getJokeById fail, fail msg is " + map.get("msg"));
						apiCallBack.onFailure(String.valueOf(code));
					}
				}
				@Override
				public void onFailure(HttpException error, String msg) {
					Log.e(TAG, "getJokeById error", error);
					if(!HttpUtil.isNetworkAvailable(mContext)) {
						ToastUtils.showMessage(mContext, R.string.no_net);
					} else {
						apiCallBack.onError(error, msg);
					}
				}
			});
	}

} public class LoadListView extends ListView implements
		OnScrollListener {

    private LayoutInflater inflater;  
  
    //上啦加载布局
    private View footView;
    
    private ImageView footerProgressImg;
    private Animation progressAnimation;
    
    private boolean haveScrollbar = true;  
  
    public LoadListView(Context context) {  
        super(context);  
        init(context);  
    }  
  
    public LoadListView(Context context, AttributeSet attrs) {  
        super(context, attrs);  
        init(context);  
    }  
  
    private void init(Context context) { 
    	progressAnimation = AnimationUtils.loadAnimation(context,
				R.anim.progress_anim);
    	inflater = LayoutInflater.from(context);
        footView = inflater.inflate(R.layout.footer, null);
//        footView.findViewById(R.id.load_layout).setVisibility(View.GONE);
        footerProgressImg = (ImageView) footView.findViewById(R.id.progress);
        footerProgressImg.startAnimation(progressAnimation);
        addFooterView(footView, null, false);
        // 设置滚动监听事件  
//        setOnScrollListener(this);  
        //设置listview加载时不滚动
		setOnScrollListener(new PauseOnScrollListener(BitmapUtil.mBitmapUtils, false, true, this));
  
    }  
	private boolean isLoadingable = false; //是否可以加载更多
	private boolean hasMoreData = false;  //有更多数据
	//正在加载底部数据
	private boolean isFootLoading = false;
	
	public void setHasMoreData(boolean hasMoreData) {
		this.hasMoreData = hasMoreData;
		if(!hasMoreData) {
			footView.findViewById(R.id.load_layout).setVisibility(View.GONE);
		}
	}
    @Override  
    public void onScrollStateChanged(AbsListView view, int scrollState) {  
    	if(isFootLoading)
			return;		
		if(isLoadingable && scrollState==SCROLL_STATE_IDLE && hasMoreData){
			prepareFootLoading();
		}
    }  
    
    public void prepareFootLoading() {
    	if(isFootLoading) {
    		return;
    	}
    	footerProgressImg.startAnimation(progressAnimation);
		footView.findViewById(R.id.load_layout).setVisibility(View.VISIBLE);
		isFootLoading = true;
		setSelectionFromTop(getCount()-1, 0);  //滚动到最底端
		onFootLoading();
    }
  
    @Override  
    public void onScroll(AbsListView view, int firstVisibleItem,  
        int visibleItemCount, int totalItemCount) {  
		//因为刚进入的时候,lastPos=-1,count=0,这个时候不能让它执行onAddFoot方法
		if(getLastVisiblePosition()==totalItemCount-1 && !isLoadingable && getLastVisiblePosition() != -1){
			isLoadingable = true;
		}	
    }  
  
    /**
	 * 上拉刷新监听器
	 *
	 */
	public interface OnFootLoadingListener{
		/**
		 * 这里是执行后台获取数据的过程
		 */
		void onFootLoading();
	}
	private OnFootLoadingListener onFootLoadingListener;
	public void setOnFootLoadingListener(
			OnFootLoadingListener onFootLoadingListener) {
		this.onFootLoadingListener = onFootLoadingListener;
	}
	
	//加载更多
	private void onFootLoading() {
		if(onFootLoadingListener != null) {
			onFootLoadingListener.onFootLoading();
		}
	}
	
	/**
	 * 底部数据加载完成,用户需要加入一个removeFootView的操作
	 */
	public void onFootLoadingComplete(boolean goneFooter){
		isLoadingable = false;
		isFootLoading = false;
		if(goneFooter){
			if(progressAnimation != null) {
				progressAnimation.cancel();
			}
			footView.findViewById(R.id.load_layout).setVisibility(View.GONE);
		}		
	}
  
    public void setMoreDataMsg(String moreDataMsg) {
    	if(footView != null) {
    		((TextView) footView.findViewById(R.id.more_data_msg)).setText(moreDataMsg);
    	}
	}
    
    public void setHaveScrollbar(boolean haveScrollbar) {   
        this.haveScrollbar = haveScrollbar;   
    }  
	
	@Override   
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {   
        if (haveScrollbar == false) {   
            int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);   
            super.onMeasure(widthMeasureSpec, expandSpec);   
        } else {   
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);   
        }   
    } 
}   public interface OnFootLoadingListener{
	/**
	 * 这里是执行后台获取数据的过程
	 */
	void onFootLoading();
} public class FastjsonUtil {
	
	private static SerializeConfig mapping = new SerializeConfig(); static { 
        mapping.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss")); 
	} 

	/** 
	 * @Title: main 
	 * @Description: TODO 
	 * @param @param args  
	 * @return void 
	 */

	public static void main(String[] args) {
	}
	
	/**
      * 将java类型的对象转换为JSON格式的字符串
      * @param object java类型的对象
      * @return JSON格式的字符串
    */
    public static <T> String serialize(T object) {
        return JSON.toJSONString(object);
    }
    
    /**
     * 将JSON格式的字符串转换成任意Java类型的对象或者java数组类型的对象，不包括java集合类型
     * @param json JSON格式的字符串
     * @param clz java类型或者java数组类型，不包括java集合类型
     * @return java类型的对象或者java数组类型的对象，不包括java集合类型的对象
     */
    public static <T> T deserialize(String json, Class<T> clz) {
       return JSON.parseObject(json, clz);
    }
	
    /**
    * 将JSON格式的字符串转换成任意Java类型的对象
    * @param json JSON格式的字符串
    * @param type 任意Java类型
    * @return 任意Java类型的对象
    */
    public static <T> T deserializeAny(String json, TypeReference<T> type) {
       return JSON.parseObject(json, type);
    }
   
    /**
    * 将JSON格式的字符串转换成任意Java类型的对象
    * @param json JSON格式的字符串
    * @param type 任意Java类型
    * @return 任意Java类型的对象
    */
    public static <T> List<T> deserializeList(String json, Class<T> clz) {
       return JSON.parseArray(json, clz);
    }
	
    /**
    * 将JSON格式的字符串转换为List<T>类型的对象
    * @param json JSON格式的字符串
    * @param clz 指定泛型集合里面的T类型
    * @return List<T>类型的对象
    */
    public static <T> List<T> json2List(String json, Class<T> clz){ 
        //JSON array -> List 
	   return JSON.parseArray(json, clz); 
    } 
	
    /**
     * 将JSON格式的字符串转换为Map类型的对象
     * @param json JSON格式的字符串
     * @return Map类型的对象
     */
	public static Map json2Map(String json){ 
		//JSON -> Map 
		return (Map)JSON.parse(json); 
	} 
	
	/**
     * 将数组格式的转换为String类型的对象
     * @param 数组格式的字符串
     * @return String类型的对象
     */
	public static String array2json(Object[] obj){ 
		return JSON.toJSONString(obj,true); 
	} 
	
	/**
     * 将Map格式的转换为String类型的对象
     * @param Map格式的字符串
     * @return String类型的对象
     */
	public static String map2json(Map map){ 
	    return JSON.toJSONString(map); 
	} 
	
	/**
     * 将List格式的转换为String类型的对象
     * @param List格式的字符串
     * @return String类型的对象
     */
	public static String list2json(List list){ 
	    return JSON.toJSONString(list); 
	} 

} public class HttpUtil {
	
	/**
	 * 判断网络是否可用
	 * @param context
	 * @return
	 */
	public static boolean isNetworkAvailable(Context context) {   
        ConnectivityManager cm = (ConnectivityManager) context   
                .getSystemService(Context.CONNECTIVITY_SERVICE);   
        if (cm != null) { 
        	//如果仅仅是用来判断网络连接
        	//则可以使用 cm.getActiveNetworkInfo().isAvailable();
        	NetworkInfo[] info = cm.getAllNetworkInfo();   
            if (info != null) {   
                for (int i = 0; i < info.length; i++) {   
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {   
                        return true;   
                    }   
                }   
            }
        }  
        return false;   
    } 
	
	/**
	 * 判断是否是3G网络
	 * @param context
	 * @return
	 */
	public static boolean is3rd(Context context) {   
        ConnectivityManager cm = (ConnectivityManager) context   
                .getSystemService(Context.CONNECTIVITY_SERVICE);   
        NetworkInfo networkINfo = cm.getActiveNetworkInfo();   
        if (networkINfo != null   
                && networkINfo.getType() == ConnectivityManager.TYPE_MOBILE) {   
            return true;   
        }   
        return false;   
    }  
	
	/**
	 * 判断是否是wifi网络
	 * @param context
	 * @return
	 */
	public static boolean isWifi(Context context) {   
        ConnectivityManager cm = (ConnectivityManager) context   
                .getSystemService(Context.CONNECTIVITY_SERVICE);   
        NetworkInfo networkINfo = cm.getActiveNetworkInfo();   
        if (networkINfo != null   
                && networkINfo.getType() == ConnectivityManager.TYPE_WIFI) {   
            return true;   
        }   
        return false;   
    }
	
} public class ToastUtils {  
    private static Handler mHandler = new Handler(Looper.getMainLooper());  
    private static Toast mToast;
    protected static LayoutInflater inflater;
    private static int marginBottem = 48;

    /** 
     * Toast发送消息，默认Toast.LENGTH_SHORT 
     * @param act 
     * @param msg 
     */ 
    public static void showMessage(final Context act, final String msg) {  
        showMessage(act, msg, Toast.LENGTH_SHORT);  
    }
    
    /** 
     * Toast发送消息，默认Toast.LENGTH_SHORT 
     * @param act 
     * @param msg 
     */ 
    public static void showMessageInCenter(final Context act, final String msg) {  
    	/*new Thread(new Runnable() {  
            public void run() {  */
            	mHandler.post(new Runnable() {  
                    @Override 
                    public void run() {  
                    	if (mToast != null) {
                    		mToast.setGravity(Gravity.CENTER, 0, 0);
                    		mToast.setText(msg);
                    	} else {
                    		mToast = Toast.makeText(act, msg, Toast.LENGTH_SHORT);
                    		if(inflater == null) {
                    			inflater = (LayoutInflater) act
                        	            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    		}
                    		mToast.setView(inflater.inflate(R.layout.toast, null));
                    		mToast.setGravity(Gravity.CENTER, 0, 0);
                    		mToast.setText(msg);
                    	}
                    	mToast.show();
                    }  
                });  
           /* }  
        }).start();  */
    }  
       
    /** 
     * Toast发送消息，默认Toast.LENGTH_LONG 
     * @param act 
     * @param msg 
     */ 
    public static void showMessageLong(final Context act, final String msg) {  
        showMessage(act, msg, Toast.LENGTH_LONG);  
    }  
   
    /** 
     * Toast发送消息，默认Toast.LENGTH_SHORT 
     * @param act 
     * @param msg 
     */ 
    public static void showMessage(final Context act, final int msg) {  
        showMessage(act, msg, Toast.LENGTH_SHORT);  
    }  
       
    /** 
     * Toast发送消息，默认Toast.LENGTH_LONG 
     * @param act 
     * @param msg 
     */ 
    public static void showMessageLong(final Context act, final int msg) {  
        showMessage(act, msg, Toast.LENGTH_LONG);  
    }  
   
    /** 
     * Toast发送消息 
     * @param act 
     * @param msg 
     * @param len 
     */ 
    public static void showMessage(final Context act, final int msg,  
            final int len) {  
        /*new Thread(new Runnable() {  
            public void run() {  */
            	mHandler.post(new Runnable() {  
                    @Override 
                    public void run() {  
                    	if (mToast != null) {
                    		mToast.setText(msg);
//                    		mToast.setGravity(Gravity.BOTTOM, 0, marginBottem);
                    		mToast.setGravity(Gravity.CENTER, 0, 0);
                    	} else {
                    		mToast = Toast.makeText(act, msg, len);
                    		if(inflater == null) {
                    			inflater = (LayoutInflater) act
                        	            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    		}
                    		mToast.setView(inflater.inflate(R.layout.toast, null));
//                    		mToast.setGravity(Gravity.BOTTOM, 0, marginBottem);
                    		mToast.setGravity(Gravity.CENTER, 0, 0);
                    		mToast.setText(msg);
                    	}
                    	mToast.show();
                    }  
                });  
           /* }  
        }).start();*/  
    }  
       
    /** 
     * Toast发送消息 
     * @param act 
     * @param msg 
     * @param len 
     */ 
    public static void showMessage(final Context act, final String msg,  
            final int len) {  
        /*new Thread(new Runnable() {  
            public void run() {*/  
            	mHandler.post(new Runnable() {  
                    @Override 
                    public void run() {  
                    	if (mToast != null) {
                    		mToast.setText(msg);
//                    		mToast.setGravity(Gravity.BOTTOM, 0, marginBottem);
                    		mToast.setGravity(Gravity.CENTER, 0, 0);
                    	} else {
                    		mToast = Toast.makeText(act, msg, len);
                    		if(inflater == null) {
                    			inflater = (LayoutInflater) act
                        	            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    		}
                    		mToast.setView(inflater.inflate(R.layout.toast, null));
//                    		mToast.setGravity(Gravity.BOTTOM, 0, marginBottem);
                    		mToast.setGravity(Gravity.CENTER, 0, 0);
                    		mToast.setText(msg);
                    	}
                    	mToast.show();
                    }  
                });  
            /*}  
        }).start();  */
    }  
   
}  
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import com.lling.qiqu.App;
import com.lling.qiqu.R;
import com.lling.qiqu.activitys.AllJokeActivity;
import com.lling.qiqu.activitys.QuShiDetailActivity;
import com.lling.qiqu.activitys.TuDetailActivity;
import com.lling.qiqu.adapters.JokeAdapter;
import com.lling.qiqu.beans.Joke;
import com.lling.qiqu.commons.Constants;
import com.lling.qiqu.commons.PageResult;
import com.lling.qiqu.service.IJokeService;
import com.lling.qiqu.service.impl.JokeServiceImpl;
import com.lling.qiqu.ui.LoadListView;
import com.lling.qiqu.ui.LoadListView.OnFootLoadingListener;
import com.lling.qiqu.utils.FastjsonUtil;
import com.lling.qiqu.utils.HttpUtil;
import com.lling.qiqu.utils.ToastUtils;
import com.umeng.analytics.MobclickAgent;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
package com.lling.qiqu.ui.fragments;




/**
 * @ClassName: QuShiFragment
 * @Description: 所有类型Fragment
 * @author lling
 * @date 2015-7-16
 */
public class AllFragment extends Fragment implements
			SwipeRefreshLayout.OnRefreshListener {
	private final static String TAG = "AllFragment";
	private SwipeRefreshLayout mSwipeLayout;
	private LoadListView mListView;
	private AllJokeActivity mAllJokeActivity;
	private ArrayList<Joke> mJokeLists = new ArrayList<Joke>();
	private Handler mHandler = new ClassHandler(this);
	private IJokeService mQuShiService;
	private JokeAdapter mJokeAdapter;
	private int mPageId;
	private int mCount;
	private boolean mHasNext;
	private int mNewOrHotFlag = Joke.SORT_NEW;
	private String mKey = Constants.CACHE_ALL_NEW;