code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
package com.ch_linghu.fanfoudroid.ui.module;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.AbsListView;
import android.widget.ListView;
public class MyListView extends ListView implements ListView.OnScrollListener {
private int mScrollState = OnScrollListener.SCROLL_STATE_IDLE;
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
setOnScrollListener(this);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
boolean result = super.onInterceptTouchEvent(event);
if (mScrollState == OnScrollListener.SCROLL_STATE_FLING) {
return true;
}
return result;
}
private OnNeedMoreListener mOnNeedMoreListener;
public static interface OnNeedMoreListener {
public void needMore();
}
public void setOnNeedMoreListener(OnNeedMoreListener onNeedMoreListener) {
mOnNeedMoreListener = onNeedMoreListener;
}
private int mFirstVisibleItem;
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (mOnNeedMoreListener == null) {
return;
}
if (firstVisibleItem != mFirstVisibleItem) {
if (firstVisibleItem + visibleItemCount >= totalItemCount) {
mOnNeedMoreListener.needMore();
}
} else {
mFirstVisibleItem = firstVisibleItem;
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
mScrollState = scrollState;
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.text.Layout;
import android.text.Spannable;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.URLSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
public class MyTextView extends TextView {
private static float mFontSize = 15;
private static boolean mFontSizeChanged = true;
public MyTextView(Context context) {
super(context, null);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setLinksClickable(false);
Resources res = getResources();
int color = res.getColor(R.color.link_color);
setLinkTextColor(color);
initFontSize();
}
public void initFontSize() {
if ( mFontSizeChanged ) {
mFontSize = getFontSizeFromPreferences(mFontSize);
setFontSizeChanged(false); // reset
}
setTextSize(mFontSize);
}
private float getFontSizeFromPreferences(float defaultValue) {
SharedPreferences preferences = TwitterApplication.mPref;
if (preferences.contains(Preferences.UI_FONT_SIZE)) {
Log.v("DEBUG", preferences.getString(Preferences.UI_FONT_SIZE, "null") + " CHANGE FONT SIZE");
return Float.parseFloat(preferences.getString(
Preferences.UI_FONT_SIZE, "14"));
}
return defaultValue;
}
private URLSpan mCurrentLink;
private ForegroundColorSpan mLinkFocusStyle = new ForegroundColorSpan(
Color.RED);
@Override
public boolean onTouchEvent(MotionEvent event) {
CharSequence text = getText();
int action = event.getAction();
if (!(text instanceof Spannable)) {
return super.onTouchEvent(event);
}
Spannable buffer = (Spannable) text;
if (action == MotionEvent.ACTION_UP
|| action == MotionEvent.ACTION_DOWN
|| action == MotionEvent.ACTION_MOVE) {
TextView widget = this;
int x = (int) event.getX();
int y = (int) event.getY();
x -= widget.getTotalPaddingLeft();
y -= widget.getTotalPaddingTop();
x += widget.getScrollX();
y += widget.getScrollY();
Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
URLSpan[] link = buffer.getSpans(off, off, URLSpan.class);
if (link.length != 0) {
if (action == MotionEvent.ACTION_UP) {
if (mCurrentLink == link[0]) {
link[0].onClick(widget);
}
mCurrentLink = null;
buffer.removeSpan(mLinkFocusStyle);
} else if (action == MotionEvent.ACTION_DOWN) {
mCurrentLink = link[0];
buffer.setSpan(mLinkFocusStyle,
buffer.getSpanStart(link[0]),
buffer.getSpanEnd(link[0]),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return true;
}
}
mCurrentLink = null;
buffer.removeSpan(mLinkFocusStyle);
return super.onTouchEvent(event);
}
public static void setFontSizeChanged(boolean isChanged) {
mFontSizeChanged = isChanged;
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
import android.content.Context;
import android.util.Log;
public class FeedbackFactory {
private static final String TAG = "FeedbackFactory";
public static enum FeedbackType {
DIALOG, PROGRESS, REFRESH
};
public static Feedback create(Context context, FeedbackType type) {
Feedback feedback = null;
switch (type) {
case PROGRESS:
feedback = new SimpleFeedback(context);
break;
}
if (null == feedback || !feedback.isAvailable()) {
feedback = new FeedbackAdapter(context);
Log.e(TAG, type + " feedback is not available.");
}
return feedback;
}
public static class FeedbackAdapter implements Feedback {
public FeedbackAdapter(Context context) {}
@Override
public void start(CharSequence text) {}
@Override
public void cancel(CharSequence text) {}
@Override
public void success(CharSequence text) {}
@Override
public void failed(CharSequence text) {}
@Override
public void update(Object arg0) {}
@Override
public boolean isAvailable() { return true; }
@Override
public void setIndeterminate(boolean indeterminate) {}
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.R;
public class SimpleFeedback implements Feedback, Widget {
private static final String TAG = "SimpleFeedback";
public static final int MAX = 100;
private ProgressBar mProgress = null;
private ProgressBar mLoadingProgress = null;
public SimpleFeedback(Context context) {
mProgress = (ProgressBar) ((Activity) context)
.findViewById(R.id.progress_bar);
mLoadingProgress = (ProgressBar) ((Activity) context)
.findViewById(R.id.top_refresh_progressBar);
}
@Override
public void start(CharSequence text) {
mProgress.setProgress(20);
mLoadingProgress.setVisibility(View.VISIBLE);
}
@Override
public void success(CharSequence text) {
mProgress.setProgress(100);
mLoadingProgress.setVisibility(View.GONE);
resetProgressBar();
}
@Override
public void failed(CharSequence text) {
resetProgressBar();
showMessage(text);
}
@Override
public void cancel(CharSequence text) {
}
@Override
public void update(Object arg0) {
if (arg0 instanceof Integer) {
mProgress.setProgress((Integer) arg0);
} else if (arg0 instanceof CharSequence) {
showMessage((String) arg0);
}
}
@Override
public void setIndeterminate(boolean indeterminate) {
mProgress.setIndeterminate(indeterminate);
}
@Override
public Context getContext() {
if (mProgress != null) {
return mProgress.getContext();
}
if (mLoadingProgress != null) {
return mLoadingProgress.getContext();
}
return null;
}
@Override
public boolean isAvailable() {
if (null == mProgress) {
Log.e(TAG, "R.id.progress_bar is missing");
return false;
}
if (null == mLoadingProgress) {
Log.e(TAG, "R.id.top_refresh_progressBar is missing");
return false;
}
return true;
}
/**
* @param total 0~100
* @param maxSize max size of list
* @param list
* @return
*/
public static int calProgressBySize(int total, int maxSize, List<?> list) {
if (null != list) {
return (MAX - (int)Math.floor(list.size() * (total/maxSize)));
}
return MAX;
}
private void resetProgressBar() {
if (mProgress.isIndeterminate()) {
//TODO: 第二次不会出现
mProgress.setIndeterminate(false);
}
mProgress.setProgress(0);
}
private void showMessage(CharSequence text) {
Toast.makeText(getContext(), text, Toast.LENGTH_LONG).show();
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.User;
import com.ch_linghu.fanfoudroid.fanfou.Weibo;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
//TODO:
/*
* 用于用户的Adapter
*/
public class UserArrayAdapter extends BaseAdapter implements TweetAdapter{
private static final String TAG = "UserArrayAdapter";
private static final String USER_ID="userId";
protected ArrayList<User> mUsers;
private Context mContext;
protected LayoutInflater mInflater;
public UserArrayAdapter(Context context) {
mUsers = new ArrayList<User>();
mContext = context;
mInflater = LayoutInflater.from(mContext);
}
@Override
public int getCount() {
return mUsers.size();
}
@Override
public Object getItem(int position) {
return mUsers.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
private static class ViewHolder {
public ImageView profileImage;
public TextView screenName;
public TextView userId;
public TextView lastStatus;
public TextView followBtn;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext);
boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true);
if (convertView == null) {
view = mInflater.inflate(R.layout.follower_item, parent, false);
ViewHolder holder = new ViewHolder();
holder.profileImage = (ImageView) view.findViewById(R.id.profile_image);
holder.screenName = (TextView) view.findViewById(R.id.screen_name);
holder.userId = (TextView) view.findViewById(R.id.user_id);
//holder.lastStatus = (TextView) view.findViewById(R.id.last_status);
holder.followBtn = (TextView) view.findViewById(R.id.follow_btn);
view.setTag(holder);
} else {
view = convertView;
}
ViewHolder holder = (ViewHolder) view.getTag();
final User user = mUsers.get(position);
String profileImageUrl = user.profileImageUrl;
if (useProfileImage){
if (!TextUtils.isEmpty(profileImageUrl)) {
holder.profileImage.setImageBitmap(TwitterApplication.mImageLoader
.get(profileImageUrl, callback));
}
}else{
holder.profileImage.setVisibility(View.GONE);
}
//holder.profileImage.setImageBitmap(ImageManager.mDefaultBitmap);
holder.screenName.setText(user.screenName);
holder.userId.setText(user.id);
//holder.lastStatus.setText(user.lastStatus);
holder.followBtn.setText(user.isFollowing ? mContext
.getString(R.string.general_del_friend) : mContext
.getString(R.string.general_add_friend));
holder.followBtn.setOnClickListener(user.isFollowing?new OnClickListener(){
@Override
public void onClick(View v) {
//Toast.makeText(mContext, user.name+"following", Toast.LENGTH_SHORT).show();
delFriend(user.id);
}}:new OnClickListener(){
@Override
public void onClick(View v) {
//Toast.makeText(mContext, user.name+"not following", Toast.LENGTH_SHORT).show();
addFriend(user.id);
}});
return view;
}
public void refresh(ArrayList<User> users) {
mUsers = users;
notifyDataSetChanged();
}
@Override
public void refresh() {
notifyDataSetChanged();
}
private ImageLoaderCallback callback = new ImageLoaderCallback(){
@Override
public void refresh(String url, Bitmap bitmap) {
UserArrayAdapter.this.refresh();
}
};
/**
* 取消关注
* @param id
*/
private void delFriend(final String id) {
Builder diaBuilder = new AlertDialog.Builder(mContext)
.setTitle("关注提示").setMessage("确实要取消关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (cancelFollowingTask != null
&& cancelFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
cancelFollowingTask = new CancelFollowingTask();
cancelFollowingTask
.setListener(cancelFollowingTaskLinstener);
TaskParams params = new TaskParams();
params.put(USER_ID, id);
cancelFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
private GenericTask cancelFollowingTask;
/**
* 取消关注
*
* @author Dino
*
*/
private class CancelFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
//TODO:userid
String userId=params[0].getString(USER_ID);
getApi().destroyFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener cancelFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
// followingBtn.setText("添加关注");
// isFollowingText.setText(getResources().getString(
// R.string.profile_notfollowing));
// followingBtn.setOnClickListener(setfollowingListener);
Toast.makeText(mContext, "取消关注成功", Toast.LENGTH_SHORT).show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(mContext, "取消关注失败", Toast.LENGTH_SHORT).show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
private GenericTask setFollowingTask;
/**
* 设置关注
* @param id
*/
private void addFriend(String id){
Builder diaBuilder = new AlertDialog.Builder(mContext)
.setTitle("关注提示").setMessage("确实要添加关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (setFollowingTask != null
&& setFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
setFollowingTask = new SetFollowingTask();
setFollowingTask
.setListener(setFollowingTaskLinstener);
TaskParams params = new TaskParams();
setFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
/**
* 设置关注
*
* @author Dino
*
*/
private class SetFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
String userId=params[0].getString(USER_ID);
getApi().createFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener setFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
// followingBtn.setText("取消关注");
// isFollowingText.setText(getResources().getString(
// R.string.profile_isfollowing));
// followingBtn.setOnClickListener(cancelFollowingListener);
Toast.makeText(mContext, "关注成功", Toast.LENGTH_SHORT).show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(mContext, "关注失败", Toast.LENGTH_SHORT).show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
public Weibo getApi() {
return TwitterApplication.mApi;
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
public interface IFlipper {
void showNext();
void showPrevious();
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
import android.content.Context;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
public interface Widget {
Context getContext();
// TEMP
public static interface OnGestureListener {
/**
* @param e1
* The first down motion event that started the fling.
* @param e2
* The move motion event that triggered the current onFling.
* @param velocityX
* The velocity of this fling measured in pixels per second
* along the x axis.
* @param velocityY
* The velocity of this fling measured in pixels per second
* along the y axis.
* @return true if the event is consumed, else false
*
* @see SimpleOnGestureListener#onFling
*/
boolean onFlingDown(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY);
boolean onFlingUp(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY);
boolean onFlingLeft(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY);
boolean onFlingRight(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY);
}
public static interface OnRefreshListener {
void onRefresh();
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.SearchActivity;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.WriteActivity;
import com.ch_linghu.fanfoudroid.ui.base.Refreshable;
public class NavBar implements Widget {
private static final String TAG = "NavBar";
public static final int HEADER_STYLE_HOME = 1;
public static final int HEADER_STYLE_WRITE = 2;
public static final int HEADER_STYLE_BACK = 3;
public static final int HEADER_STYLE_SEARCH = 4;
private ImageView mRefreshButton;
private ImageButton mSearchButton;
private ImageButton mWriteButton;
private TextView mTitleButton;
private Button mBackButton;
private ImageButton mHomeButton;
private MenuDialog mDialog;
private EditText mSearchEdit;
/** @deprecated 已废弃 */
protected AnimationDrawable mRefreshAnimation;
private ProgressBar mProgressBar = null; // 进度条(横)
private ProgressBar mLoadingProgress = null; // 旋转图标
public NavBar(int style, Context context) {
initHeader(style, (Activity) context);
}
private void initHeader(int style, final Activity activity) {
switch (style) {
case HEADER_STYLE_HOME:
addTitleButtonTo(activity);
addWriteButtonTo(activity);
addSearchButtonTo(activity);
addRefreshButtonTo(activity);
break;
case HEADER_STYLE_BACK:
addBackButtonTo(activity);
addWriteButtonTo(activity);
addSearchButtonTo(activity);
addRefreshButtonTo(activity);
break;
case HEADER_STYLE_WRITE:
addBackButtonTo(activity);
break;
case HEADER_STYLE_SEARCH:
addBackButtonTo(activity);
addSearchBoxTo(activity);
addSearchButtonTo(activity);
break;
}
}
/**
* 搜索硬按键行为
* @deprecated 这个不晓得还有没有用, 已经是已经被新的搜索替代的吧 ?
*/
public boolean onSearchRequested() {
/*
Intent intent = new Intent();
intent.setClass(this, SearchActivity.class);
startActivity(intent);
*/
return true;
}
/**
* 添加[LOGO/标题]按钮
* @param acticity
*/
private void addTitleButtonTo(final Activity acticity) {
mTitleButton = (TextView) acticity.findViewById(R.id.title);
mTitleButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int top = mTitleButton.getTop();
int height = mTitleButton.getHeight();
int x = top + height;
if (null == mDialog) {
Log.d(TAG, "Create menu dialog.");
mDialog = new MenuDialog(acticity);
mDialog.bindEvent(acticity);
mDialog.setPosition(-1, x);
}
// toggle dialog
if (mDialog.isShowing()) {
mDialog.dismiss(); // 没机会触发
} else {
mDialog.show();
}
}
});
}
/**
* 设置标题
* @param title
*/
public void setHeaderTitle(String title) {
if (null != mTitleButton) {
mTitleButton.setText(title);
TextPaint tp = mTitleButton.getPaint();
tp.setFakeBoldText(true); // 中文粗体
}
}
/**
* 设置标题
* @param resource R.string.xxx
*/
public void setHeaderTitle(int resource) {
if (null != mTitleButton) {
mTitleButton.setBackgroundResource(resource);
}
}
/**
* 添加[刷新]按钮
* @param activity
*/
private void addRefreshButtonTo(final Activity activity) {
mRefreshButton = (ImageView) activity.findViewById(R.id.top_refresh);
// FIXME: DELETE ME 暂时取消旋转效果, 测试ProgressBar
// refreshButton.setBackgroundResource(R.drawable.top_refresh);
// mRefreshAnimation = (AnimationDrawable)
// refreshButton.getBackground();
mProgressBar = (ProgressBar) activity.findViewById(R.id.progress_bar);
mLoadingProgress = (ProgressBar) activity
.findViewById(R.id.top_refresh_progressBar);
mRefreshButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (activity instanceof Refreshable) {
((Refreshable) activity).doRetrieve();
} else {
Log.e(TAG, "The current view "
+ activity.getClass().getName()
+ " cann't be retrieved");
}
}
});
}
/**
* Start/Stop Top Refresh Button's Animation
*
* @param animate
* start or stop
* @deprecated use feedback
*/
public void setRefreshAnimation(boolean animate) {
if (mRefreshAnimation != null) {
if (animate) {
mRefreshAnimation.start();
} else {
mRefreshAnimation.setVisible(true, true); // restart
mRefreshAnimation.start(); // goTo frame 0
mRefreshAnimation.stop();
}
} else {
Log.w(TAG, "mRefreshAnimation is null");
}
}
/**
* 添加[搜索]按钮
* @param activity
*/
private void addSearchButtonTo(final Activity activity) {
mSearchButton = (ImageButton) activity.findViewById(R.id.search);
mSearchButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startSearch(activity);
}
});
}
// 这个方法会在SearchActivity里重写
protected boolean startSearch(final Activity activity) {
Intent intent = new Intent();
intent.setClass(activity, SearchActivity.class);
activity.startActivity(intent);
return true;
}
/**
* 添加[搜索框]
* @param activity
*/
private void addSearchBoxTo(final Activity activity) {
mSearchEdit = (EditText) activity.findViewById(R.id.search_edit);
}
/**
* 添加[撰写]按钮
* @param activity
*/
private void addWriteButtonTo(final Activity activity) {
mWriteButton = (ImageButton) activity.findViewById(R.id.writeMessage);
mWriteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// forward to write activity
Intent intent = new Intent();
intent.setClass(v.getContext(), WriteActivity.class);
v.getContext().startActivity(intent);
}
});
}
/**
* 添加[回首页]按钮
* @param activity
*/
@SuppressWarnings("unused")
private void addHomeButton(final Activity activity) {
mHomeButton = (ImageButton) activity.findViewById(R.id.home);
mHomeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// 动画
Animation anim = AnimationUtils.loadAnimation(v.getContext(),
R.anim.scale_lite);
v.startAnimation(anim);
// forward to TwitterActivity
Intent intent = new Intent();
intent.setClass(v.getContext(), TwitterActivity.class);
v.getContext().startActivity(intent);
}
});
}
/**
* 添加[返回]按钮
* @param activity
*/
private void addBackButtonTo(final Activity activity) {
mBackButton = (Button) activity.findViewById(R.id.top_back);
// 中文粗体
// TextPaint tp = backButton.getPaint();
// tp.setFakeBoldText(true);
mBackButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Go back to previous activity
activity.finish();
}
});
}
public void destroy() {
// dismiss dialog before destroy
// to avoid android.view.WindowLeaked Exception
if (mDialog != null) {
mDialog.dismiss();
mDialog = null;
}
mRefreshButton = null;
mSearchButton = null;
mWriteButton = null;
mTitleButton = null;
mBackButton = null;
mHomeButton = null;
mSearchButton = null;
mSearchEdit = null;
mProgressBar = null;
mLoadingProgress = null;
}
public ImageView getRefreshButton() {
return mRefreshButton;
}
public ImageButton getSearchButton() {
return mSearchButton;
}
public ImageButton getWriteButton() {
return mWriteButton;
}
public TextView getTitleButton() {
return mTitleButton;
}
public Button getBackButton() {
return mBackButton;
}
public ImageButton getHomeButton() {
return mHomeButton;
}
public MenuDialog getDialog() {
return mDialog;
}
public EditText getSearchEdit() {
return mSearchEdit;
}
/** @deprecated 已废弃 */
public AnimationDrawable getRefreshAnimation() {
return mRefreshAnimation;
}
public ProgressBar getProgressBar() {
return mProgressBar;
}
public ProgressBar getLoadingProgress() {
return mLoadingProgress;
}
@Override
public Context getContext() {
if (null != mDialog) {
return mDialog.getContext();
}
if (null != mTitleButton) {
return mTitleButton.getContext();
}
return null;
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;
import com.ch_linghu.fanfoudroid.R;
/**
* ActivityFlipper, 和 {@link ViewFactory} 类似, 只是设计用于切换activity.
*
* 切换的前后顺序取决与注册时的先后顺序
*
* USAGE: <code>
* ActivityFlipper mFlipper = new ActivityFlipper(this);
* mFlipper.addActivity(TwitterActivity.class);
* mFlipper.addActivity(MentionActivity.class);
* mFlipper.addActivity(DmActivity.class);
*
* // switch activity
* mFlipper.setCurrentActivity(TwitterActivity.class);
* mFlipper.showNext();
* mFlipper.showPrevious();
*
* // or without set current activity
* mFlipper.showNextOf(TwitterActivity.class);
* mFlipper.showPreviousOf(TwitterActivity.class);
*
* // or auto mode, use the context as current activity
* mFlipper.autoShowNext();
* mFlipper.autoShowPrevious();
*
* // set toast
* mFlipper.setToastResource(new int[] {
* R.drawable.point_left,
* R.drawable.point_center,
* R.drawable.point_right
* });
*
* // set Animation
* mFlipper.setInAnimation(R.anim.push_left_in);
* mFlipper.setOutAnimation(R.anim.push_left_out);
* mFlipper.setPreviousInAnimation(R.anim.push_right_in);
* mFlipper.setPreviousOutAnimation(R.anim.push_right_out);
* </code>
*
*/
public class ActivityFlipper implements IFlipper {
private static final String TAG = "ActivityFlipper";
private static final int SHOW_NEXT = 0;
private static final int SHOW_PROVIOUS = 1;
private int mDirection = SHOW_NEXT;
private boolean mToastEnabled = false;
private int[] mToastResourcesMap = new int[]{};
private boolean mAnimationEnabled = false;
private int mNextInAnimation = -1;
private int mNextOutAnimation = -1;
private int mPreviousInAnimation = -1;
private int mPreviousOutAnimation = -1;
private Activity mActivity;
private List<Class<?>> mActivities = new ArrayList<Class<?>>();;
private int mWhichActivity = 0;
public ActivityFlipper() {
}
public ActivityFlipper(Activity activity) {
mActivity = activity;
}
/**
* Launch Activity
*
* @param cls
* class of activity
*/
public void launchActivity(Class<?> cls) {
Log.v(TAG, "launch activity :" + cls.getName());
Intent intent = new Intent();
intent.setClass(mActivity, cls);
mActivity.startActivity(intent);
}
public void setToastResource(int[] resourceIds) {
mToastEnabled = true;
mToastResourcesMap = resourceIds;
}
private void maybeShowToast(int whichActicity) {
if (mToastEnabled && whichActicity < mToastResourcesMap.length) {
final Toast myToast = new Toast(mActivity);
final ImageView myView = new ImageView(mActivity);
myView.setImageResource(mToastResourcesMap[whichActicity]);
myToast.setView(myView);
myToast.setDuration(Toast.LENGTH_SHORT);
myToast.setGravity(Gravity.BOTTOM | Gravity.CENTER, 0, 0);
myToast.show();
}
}
private void maybeShowAnimation(int whichActivity) {
if (mAnimationEnabled) {
boolean showPrevious = (mDirection == SHOW_PROVIOUS);
if (showPrevious && mPreviousInAnimation != -1
&& mPreviousOutAnimation != -1) {
mActivity.overridePendingTransition(
mPreviousInAnimation, mPreviousOutAnimation);
return; // use Previous Animation
}
if (mNextInAnimation != -1 && mNextOutAnimation != -1) {
mActivity.overridePendingTransition(
mNextInAnimation, mNextOutAnimation);
}
}
}
/**
* Launch Activity by index
*
* @param whichActivity
* the index of Activity
*/
private void launchActivity(int whichActivity) {
launchActivity(mActivities.get(whichActivity));
maybeShowToast(whichActivity);
maybeShowAnimation(whichActivity);
}
/**
* Add Activity NOTE: 添加的顺序很重要
*
* @param cls
* class of activity
*/
public void addActivity(Class<?> cls) {
mActivities.add(cls);
}
/**
* Get index of the Activity
*
* @param cls
* class of activity
* @return
*/
private int getIndexOf(Class<?> cls) {
int index = mActivities.indexOf(cls);
if (-1 == index) {
Log.e(TAG, "No such activity: " + cls.getName());
}
return index;
}
@SuppressWarnings("unused")
private Class<?> getActivityAt(int index) {
if (index > 0 && index < mActivities.size()) {
return mActivities.get(index);
}
return null;
}
/**
* Show next activity(already setCurrentActivity)
*/
@Override
public void showNext() {
mDirection = SHOW_NEXT;
setDisplayedActivity(mWhichActivity + 1, true);
}
/**
* Show next activity of
*
* @param cls
* class of activity
*/
public void showNextOf(Class<?> cls) {
setCurrentActivity(cls);
showNext();
}
/**
* Show next activity(use current context as a activity)
*/
public void autoShowNext() {
showNextOf(mActivity.getClass());
}
/**
* Show previous activity(already setCurrentActivity)
*/
@Override
public void showPrevious() {
mDirection = SHOW_PROVIOUS;
setDisplayedActivity(mWhichActivity - 1, true);
}
/**
* Show previous activity of
*
* @param cls
* class of activity
*/
public void showPreviousOf(Class<?> cls) {
setCurrentActivity(cls);
showPrevious();
}
/**
* Show previous activity(use current context as a activity)
*/
public void autoShowPrevious() {
showPreviousOf(mActivity.getClass());
}
/**
* Sets which child view will be displayed
*
* @param whichActivity
* the index of the child view to display
* @param display
* display immediately
*/
public void setDisplayedActivity(int whichActivity, boolean display) {
mWhichActivity = whichActivity;
if (whichActivity >= getCount()) {
mWhichActivity = 0;
} else if (whichActivity < 0) {
mWhichActivity = getCount() - 1;
}
if (display) {
launchActivity(mWhichActivity);
}
}
/**
* Set current Activity
*
* @param cls
* class of activity
*/
public void setCurrentActivity(Class<?> cls) {
setDisplayedActivity(getIndexOf(cls), false);
}
public void setInAnimation(int resourceId) {
setEnableAnimation(true);
mNextInAnimation = resourceId;
}
public void setOutAnimation(int resourceId) {
setEnableAnimation(true);
mNextOutAnimation = resourceId;
}
public void setPreviousInAnimation(int resourceId) {
mPreviousInAnimation = resourceId;
}
public void setPreviousOutAnimation(int resourceId) {
mPreviousOutAnimation = resourceId;
}
public void setEnableAnimation(boolean enable) {
mAnimationEnabled = enable;
}
/**
* Count activities
*
* @return the number of activities
*/
public int getCount() {
return mActivities.size();
}
}
| Java |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid.ui.module;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.BrowseActivity;
import com.ch_linghu.fanfoudroid.DmActivity;
import com.ch_linghu.fanfoudroid.FavoritesActivity;
import com.ch_linghu.fanfoudroid.FollowersActivity;
import com.ch_linghu.fanfoudroid.FollowingActivity;
import com.ch_linghu.fanfoudroid.MentionActivity;
import com.ch_linghu.fanfoudroid.ProfileActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.UserTimelineActivity;
/**
* 顶部主菜单切换浮动层
*
* @author lds
*
*/
public class MenuDialog extends Dialog {
private static final int PAGE_MINE = 0;
private static final int PAGE_PROFILE = 1;
private static final int PAGE_FOLLOWERS = 2;
private static final int PAGE_FOLLOWING = 3;
private static final int PAGE_HOME = 4;
private static final int PAGE_MENTIONS = 5;
private static final int PAGE_BROWSE = 6;
private static final int PAGE_FAVORITES = 7;
private static final int PAGE_MESSAGE = 8;
private List<int[]> pages = new ArrayList<int[]>();
{
pages.add(new int[] { R.drawable.menu_tweets,
R.string.pages_mine });
pages.add(new int[] { R.drawable.menu_profile,
R.string.pages_profile });
pages.add(new int[] { R.drawable.menu_followers,
R.string.pages_followers });
pages.add(new int[] { R.drawable.menu_following,
R.string.pages_following });
pages.add(new int[] { R.drawable.menu_list,
R.string.pages_home });
pages.add(new int[] { R.drawable.menu_mentions,
R.string.pages_mentions });
pages.add(new int[] { R.drawable.menu_listed,
R.string.pages_browse });
pages.add(new int[] { R.drawable.menu_favorites,
R.string.pages_search });
pages.add(new int[] { R.drawable.menu_create_list,
R.string.pages_message });
};
private GridView gridview;
public MenuDialog(Context context, boolean cancelable,
OnCancelListener cancelListener) {
super(context, cancelable, cancelListener);
// TODO Auto-generated constructor stub
}
public MenuDialog(Context context, int theme) {
super(context, theme);
// TODO Auto-generated constructor stub
}
public MenuDialog(Context context) {
super(context, R.style.Theme_Transparent);
setContentView(R.layout.menu_dialog);
// setTitle("Custom Dialog");
setCanceledOnTouchOutside(true);
// 设置window属性
LayoutParams a = getWindow().getAttributes();
a.gravity = Gravity.TOP;
a.dimAmount = 0; // 去背景遮盖
getWindow().setAttributes(a);
initMenu();
}
public void setPosition(int x, int y) {
LayoutParams a = getWindow().getAttributes();
if (-1 != x)
a.x = x;
if (-1 != y)
a.y = y;
getWindow().setAttributes(a);
}
private void goTo(Class<?> cls, Intent intent) {
if (getOwnerActivity().getClass() != cls) {
dismiss();
intent.setClass(getContext(), cls);
getContext().startActivity(intent);
} else {
String msg = getContext().getString(R.string.page_status_same_page);
Toast.makeText(getContext(), msg,
Toast.LENGTH_SHORT).show();
}
}
private void goTo(Class<?> cls){
Intent intent = new Intent();
goTo(cls, intent);
}
private void initMenu() {
// 准备要添加的数据条目
List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();
for (int[] item : pages) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("image", item[0]);
map.put("title", getContext().getString(item[1]) );
items.add(map);
}
// 实例化一个适配器
SimpleAdapter adapter = new SimpleAdapter(getContext(),
items, // data
R.layout.menu_item, // grid item layout
new String[] { "title", "image" }, // data's key
new int[] { R.id.item_text, R.id.item_image }); // item view id
// 获得GridView实例
gridview = (GridView) findViewById(R.id.mygridview);
// 将GridView和数据适配器关联
gridview.setAdapter(adapter);
}
public void bindEvent(Activity activity) {
setOwnerActivity(activity);
// 绑定监听器
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
switch (position) {
case PAGE_MINE:
String user = TwitterApplication.getMyselfId();
String name = TwitterApplication.getMyselfName();
Intent intent = UserTimelineActivity.createIntent(user, name);
goTo(UserTimelineActivity.class, intent);
break;
case PAGE_PROFILE:
goTo(ProfileActivity.class);
break;
case PAGE_FOLLOWERS:
goTo(FollowersActivity.class);
break;
case PAGE_FOLLOWING:
goTo(FollowingActivity.class);
break;
case PAGE_HOME:
goTo(TwitterActivity.class);
break;
case PAGE_MENTIONS:
goTo(MentionActivity.class);
break;
case PAGE_BROWSE:
goTo(BrowseActivity.class);
break;
case PAGE_FAVORITES:
goTo(FavoritesActivity.class);
break;
case PAGE_MESSAGE:
goTo(DmActivity.class);
break;
}
}
});
Button close_button = (Button) findViewById(R.id.close_menu);
close_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
import android.graphics.Color;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Selection;
import android.text.TextWatcher;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.TextView;
public class TweetEdit {
private EditText mEditText;
private TextView mCharsRemainText;
private int originTextColor;
public TweetEdit(EditText editText, TextView charsRemainText) {
mEditText = editText;
mCharsRemainText = charsRemainText;
originTextColor = mCharsRemainText.getTextColors().getDefaultColor();
mEditText.addTextChangedListener(mTextWatcher);
mEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
MAX_TWEET_INPUT_LENGTH) });
}
private static final int MAX_TWEET_LENGTH = 140;
private static final int MAX_TWEET_INPUT_LENGTH = 400;
public void setTextAndFocus(String text, boolean start) {
setText(text);
Editable editable = mEditText.getText();
if (!start){
Selection.setSelection(editable, editable.length());
}else{
Selection.setSelection(editable, 0);
}
mEditText.requestFocus();
}
public void setText(String text) {
mEditText.setText(text);
updateCharsRemain();
}
private TextWatcher mTextWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable e) {
updateCharsRemain();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
};
public void updateCharsRemain() {
int remaining = MAX_TWEET_LENGTH - mEditText.length();
if (remaining < 0 ) {
mCharsRemainText.setTextColor(Color.RED);
} else {
mCharsRemainText.setTextColor(originTextColor);
}
mCharsRemainText.setText(remaining + "");
}
public String getText() {
return mEditText.getText().toString();
}
public void setEnabled(boolean b) {
mEditText.setEnabled(b);
}
public void setOnKeyListener(OnKeyListener listener) {
mEditText.setOnKeyListener(listener);
}
public void addTextChangedListener(TextWatcher watcher){
mEditText.addTextChangedListener(watcher);
}
public void requestFocus() {
mEditText.requestFocus();
}
public EditText getEditText() {
return mEditText;
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
public interface Feedback {
public boolean isAvailable();
public void start(CharSequence text);
public void cancel(CharSequence text);
public void success(CharSequence text);
public void failed(CharSequence text);
public void update(Object arg0);
public void setIndeterminate (boolean indeterminate);
}
| Java |
/**
*
*/
package com.ch_linghu.fanfoudroid.ui.module;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.db.UserInfoTable;
public class UserCursorAdapter extends CursorAdapter implements TweetAdapter {
private static final String TAG = "TweetCursorAdapter";
private Context mContext;
public UserCursorAdapter(Context context, Cursor cursor) {
super(context, cursor);
mContext = context;
if (context != null) {
mInflater = LayoutInflater.from(context);
}
if (cursor != null) {
mScreenNametColumn=cursor.getColumnIndexOrThrow(UserInfoTable.FIELD_USER_SCREEN_NAME);
mUserIdColumn=cursor.getColumnIndexOrThrow(UserInfoTable._ID);
mProfileImageUrlColumn=cursor.getColumnIndexOrThrow(UserInfoTable.FIELD_PROFILE_IMAGE_URL);
// mLastStatusColumn=cursor.getColumnIndexOrThrow(UserInfoTable.FIELD_LAST_STATUS);
}
mMetaBuilder = new StringBuilder();
}
private LayoutInflater mInflater;
private int mScreenNametColumn;
private int mUserIdColumn;
private int mProfileImageUrlColumn;
//private int mLastStatusColumn;
private StringBuilder mMetaBuilder;
private ImageLoaderCallback callback = new ImageLoaderCallback(){
@Override
public void refresh(String url, Bitmap bitmap) {
UserCursorAdapter.this.refresh();
}
};
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = mInflater.inflate(R.layout.follower_item, parent, false);
Log.d(TAG,"load newView");
UserCursorAdapter.ViewHolder holder = new ViewHolder();
holder.screenName=(TextView) view.findViewById(R.id.screen_name);
holder.profileImage=(ImageView)view.findViewById(R.id.profile_image);
//holder.lastStatus=(TextView) view.findViewById(R.id.last_status);
holder.userId=(TextView) view.findViewById(R.id.user_id);
view.setTag(holder);
return view;
}
private static class ViewHolder {
public TextView screenName;
public TextView userId;
public TextView lastStatus;
public ImageView profileImage;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
UserCursorAdapter.ViewHolder holder = (UserCursorAdapter.ViewHolder) view
.getTag();
Log.d(TAG, "cursor count="+cursor.getCount());
Log.d(TAG,"holder is null?"+(holder==null?"yes":"no"));
SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext);;
boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true);
String profileImageUrl = cursor.getString(mProfileImageUrlColumn);
if (useProfileImage){
if (!TextUtils.isEmpty(profileImageUrl)) {
holder.profileImage.setImageBitmap(TwitterApplication.mImageLoader
.get(profileImageUrl, callback));
}
}else{
holder.profileImage.setVisibility(View.GONE);
}
holder.screenName.setText(cursor.getString(mScreenNametColumn));
holder.userId.setText(cursor.getString(mUserIdColumn));
}
@Override
public void refresh() {
getCursor().requery();
}
} | Java |
package com.ch_linghu.fanfoudroid.ui.module;
import com.ch_linghu.fanfoudroid.R;
import android.app.Activity;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
/**
* FlingGestureLIstener, 封装 {@link SimpleOnGestureListener} .
* 主要用于识别类似向上下或向左右滑动等基本手势.
*
* 该类主要解决了与ListView自带的上下滑动冲突问题.
* 解决方法为将listView的onTouchListener进行覆盖:<code>
* FlingGestureListener gListener = new FlingGestureListener(this,
* MyActivityFlipper.create(this));
* myListView.setOnTouchListener(gListener);
* </code>
*
* 该类一般和实现了 {@link Widget.OnGestureListener} 接口的类共同协作.
* 在识别到手势后会自动调用其相关的回调方法, 以实现手势触发事件效果.
*
* @see Widget.OnGestureListener
*
*/
public class FlingGestureListener extends SimpleOnGestureListener implements
OnTouchListener {
private static final String TAG = "FlipperGestureListener";
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_DISTANCE = 400;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
private Widget.OnGestureListener mListener;
private GestureDetector gDetector;
private Activity activity;
public FlingGestureListener(Activity activity,
Widget.OnGestureListener listener) {
this(activity, listener, null);
}
public FlingGestureListener(Activity activity,
Widget.OnGestureListener listener, GestureDetector gDetector) {
if (gDetector == null) {
gDetector = new GestureDetector(activity, this);
}
this.gDetector = gDetector;
mListener = listener;
this.activity = activity;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
Log.d(TAG, "On fling");
boolean result = super.onFling(e1, e2, velocityX, velocityY);
float xDistance = Math.abs(e1.getX() - e2.getX());
float yDistance = Math.abs(e1.getY() - e2.getY());
velocityX = Math.abs(velocityX);
velocityY = Math.abs(velocityY);
try {
if (xDistance > SWIPE_MAX_DISTANCE
|| yDistance > SWIPE_MAX_DISTANCE) {
Log.d(TAG, "OFF_PATH");
return result;
}
if (velocityX > SWIPE_THRESHOLD_VELOCITY
&& xDistance > SWIPE_MIN_DISTANCE) {
if (e1.getX() > e2.getX()) {
Log.d(TAG, "<------");
result = mListener.onFlingLeft(e1, e1, velocityX, velocityY);
activity.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
} else {
Log.d(TAG, "------>");
result = mListener.onFlingRight(e1, e1, velocityX, velocityY);
activity.overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
}
} else if (velocityY > SWIPE_THRESHOLD_VELOCITY
&& yDistance > SWIPE_MIN_DISTANCE) {
if (e1.getY() > e2.getY()) {
Log.d(TAG, "up");
result = mListener.onFlingUp(e1, e1, velocityX, velocityY);
} else {
Log.d(TAG, "down");
result = mListener.onFlingDown(e1, e1, velocityX, velocityY);
}
} else {
Log.d(TAG, "not hint");
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "onFling error " + e.getMessage());
}
return result;
}
@Override
public void onLongPress(MotionEvent e) {
// TODO Auto-generated method stub
super.onLongPress(e);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.d(TAG, "On Touch");
// Within the MyGestureListener class you can now manage the
// event.getAction() codes.
// Note that we are now calling the gesture Detectors onTouchEvent.
// And given we've set this class as the GestureDetectors listener
// the onFling, onSingleTap etc methods will be executed.
return gDetector.onTouchEvent(event);
}
public GestureDetector getDetector() {
return gDetector;
}
} | Java |
/**
*
*/
package com.ch_linghu.fanfoudroid.ui.module;
import java.text.ParseException;
import java.util.Date;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.app.SimpleImageLoader;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class TweetCursorAdapter extends CursorAdapter implements TweetAdapter {
private static final String TAG = "TweetCursorAdapter";
private Context mContext;
public TweetCursorAdapter(Context context, Cursor cursor) {
super(context, cursor);
mContext = context;
if (context != null) {
mInflater = LayoutInflater.from(context);
}
if (cursor != null) {
//TODO: 可使用:
//Tweet tweet = StatusTable.parseCursor(cursor);
mUserTextColumn = cursor
.getColumnIndexOrThrow(StatusTable.USER_SCREEN_NAME);
mTextColumn = cursor.getColumnIndexOrThrow(StatusTable.TEXT);
mProfileImageUrlColumn = cursor
.getColumnIndexOrThrow(StatusTable.PROFILE_IMAGE_URL);
mCreatedAtColumn = cursor
.getColumnIndexOrThrow(StatusTable.CREATED_AT);
mSourceColumn = cursor.getColumnIndexOrThrow(StatusTable.SOURCE);
mInReplyToScreenName = cursor
.getColumnIndexOrThrow(StatusTable.IN_REPLY_TO_SCREEN_NAME);
mFavorited = cursor.getColumnIndexOrThrow(StatusTable.FAVORITED);
mThumbnailPic = cursor.getColumnIndexOrThrow(StatusTable.PIC_THUMB);
mMiddlePic = cursor.getColumnIndexOrThrow(StatusTable.PIC_MID);
mOriginalPic = cursor.getColumnIndexOrThrow(StatusTable.PIC_ORIG);
}
mMetaBuilder = new StringBuilder();
}
private LayoutInflater mInflater;
private int mUserTextColumn;
private int mTextColumn;
private int mProfileImageUrlColumn;
private int mCreatedAtColumn;
private int mSourceColumn;
private int mInReplyToScreenName;
private int mFavorited;
private int mThumbnailPic;
private int mMiddlePic;
private int mOriginalPic;
private StringBuilder mMetaBuilder;
/*
private ProfileImageCacheCallback callback = new ProfileImageCacheCallback(){
@Override
public void refresh(String url, Bitmap bitmap) {
TweetCursorAdapter.this.refresh();
}
};
*/
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = mInflater.inflate(R.layout.tweet, parent, false);
TweetCursorAdapter.ViewHolder holder = new ViewHolder();
holder.tweetUserText = (TextView) view
.findViewById(R.id.tweet_user_text);
holder.tweetText = (TextView) view.findViewById(R.id.tweet_text);
holder.profileImage = (ImageView) view.findViewById(R.id.profile_image);
holder.metaText = (TextView) view.findViewById(R.id.tweet_meta_text);
holder.fav = (ImageView) view.findViewById(R.id.tweet_fav);
holder.has_image = (ImageView) view.findViewById(R.id.tweet_has_image);
view.setTag(holder);
return view;
}
private static class ViewHolder {
public TextView tweetUserText;
public TextView tweetText;
public ImageView profileImage;
public TextView metaText;
public ImageView fav;
public ImageView has_image;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TweetCursorAdapter.ViewHolder holder = (TweetCursorAdapter.ViewHolder) view
.getTag();
SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext);;
boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true);
holder.tweetUserText.setText(cursor.getString(mUserTextColumn));
TextHelper.setSimpleTweetText(holder.tweetText, cursor.getString(mTextColumn));
String profileImageUrl = cursor.getString(mProfileImageUrlColumn);
if (useProfileImage && !TextUtils.isEmpty(profileImageUrl)) {
SimpleImageLoader.display(holder.profileImage, profileImageUrl);
} else {
holder.profileImage.setVisibility(View.GONE);
}
if (cursor.getString(mFavorited).equals("true")) {
holder.fav.setVisibility(View.VISIBLE);
} else {
holder.fav.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(cursor.getString(mThumbnailPic))) {
holder.has_image.setVisibility(View.VISIBLE);
} else {
holder.has_image.setVisibility(View.GONE);
}
try {
Date createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(cursor
.getString(mCreatedAtColumn));
holder.metaText.setText(Tweet.buildMetaText(mMetaBuilder,
createdAt, cursor.getString(mSourceColumn), cursor
.getString(mInReplyToScreenName)));
} catch (ParseException e) {
Log.w(TAG, "Invalid created at data.");
}
}
@Override
public void refresh() {
getCursor().requery();
}
} | Java |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid.service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* This broadcast receiver is awoken after boot and registers the service that
* checks for new tweets.
*/
public class BootReceiver extends BroadcastReceiver {
private static final String TAG = "BootReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Twitta BootReceiver is receiving.");
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
TwitterService.schedule(context);
}
}
}
| Java |
package com.ch_linghu.fanfoudroid.service;
import java.util.List;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
/**
* Location Service
*
* AndroidManifest.xml <code>
* <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
* </code>
*
* TODO: 使用DDMS对模拟器GPS位置进行更新时, 会造成死机现象
*
*/
public class LocationService implements IService {
private static final String TAG = "LocationService";
private LocationManager mLocationManager;
private LocationListener mLocationListener = new MyLocationListener();
private String mLocationProvider;
private boolean running = false;
public LocationService(Context context) {
initLocationManager(context);
}
private void initLocationManager(Context context) {
// Acquire a reference to the system Location Manager
mLocationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
mLocationProvider = mLocationManager.getBestProvider(new Criteria(),
false);
}
public void startService() {
if (!running) {
Log.v(TAG, "START LOCATION SERVICE, PROVIDER:" + mLocationProvider);
running = true;
mLocationManager.requestLocationUpdates(mLocationProvider, 0, 0,
mLocationListener);
}
}
public void stopService() {
if (running) {
Log.v(TAG, "STOP LOCATION SERVICE");
running = false;
mLocationManager.removeUpdates(mLocationListener);
}
}
/**
* @return the last known location for the provider, or null
*/
public Location getLastKnownLocation() {
return mLocationManager.getLastKnownLocation(mLocationProvider);
}
private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.v(TAG, "LOCATION CHANGED TO: " + location.toString());
}
@Override
public void onProviderDisabled(String provider) {
Log.v(TAG, "PROVIDER DISABLED " + provider);
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
Log.v(TAG, "PROVIDER ENABLED " + provider);
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
Log.v(TAG, "STATUS CHANGED: " + provider + " " + status);
}
}
// Only for debug
public void logAllProviders() {
// List all providers:
List<String> providers = mLocationManager.getAllProviders();
Log.v(TAG, "LIST ALL PROVIDERS:");
for (String provider : providers) {
boolean isEnabled = mLocationManager.isProviderEnabled(provider);
Log.v(TAG, "Provider " + provider + ": " + isEnabled);
}
}
// only for debug
public static LocationService test(Context context) {
LocationService ls = new LocationService(context);
ls.startService();
ls.logAllProviders();
Location local = ls.getLastKnownLocation();
if (local != null) {
Log.v("LDS", ls.getLastKnownLocation().toString());
}
return ls;
}
}
| Java |
package com.ch_linghu.fanfoudroid.service;
public interface IService {
void startService();
void stopService();
}
| Java |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid.service;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import com.ch_linghu.fanfoudroid.DmActivity;
import com.ch_linghu.fanfoudroid.FanfouWidget;
import com.ch_linghu.fanfoudroid.MentionActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Dm;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.fanfou.Weibo;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class TwitterService extends Service {
private static final String TAG = "TwitterService";
private NotificationManager mNotificationManager;
private ArrayList<Tweet> mNewTweets;
private ArrayList<Tweet> mNewMentions;
private ArrayList<Dm> mNewDms;
private GenericTask mRetrieveTask;
public String getUserId() {
return TwitterApplication.getMyselfId();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// fetchMessages();
// handler.postDelayed(mTask, 10000);
Log.d(TAG, "Start Once");
return super.onStartCommand(intent, flags, startId);
}
private TaskListener mRetrieveTaskListener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
SharedPreferences preferences = TwitterApplication.mPref;
boolean needCheck = preferences.getBoolean(
Preferences.CHECK_UPDATES_KEY, false);
boolean timeline_only = preferences.getBoolean(
Preferences.TIMELINE_ONLY_KEY, false);
boolean replies_only = preferences.getBoolean(
Preferences.REPLIES_ONLY_KEY, true);
boolean dm_only = preferences.getBoolean(
Preferences.DM_ONLY_KEY, true);
if (needCheck) {
if (timeline_only) {
processNewTweets();
}
if (replies_only) {
processNewMentions();
}
if (dm_only) {
processNewDms();
}
}
}
try {
Intent intent = new Intent(TwitterService.this,
FanfouWidget.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
PendingIntent pi = PendingIntent.getBroadcast(
TwitterService.this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
pi.send();
} catch (CanceledException e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
stopSelf();
}
@Override
public String getName() {
return "ServiceRetrieveTask";
}
};
private WakeLock mWakeLock;
@Override
public IBinder onBind(Intent intent) {
return null;
}
private TwitterDatabase getDb() {
return TwitterApplication.mDb;
}
private Weibo getApi() {
return TwitterApplication.mApi;
}
@Override
public void onCreate() {
Log.v(TAG, "Server Created");
super.onCreate();
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
mWakeLock.acquire();
boolean needCheck = TwitterApplication.mPref.getBoolean(
Preferences.CHECK_UPDATES_KEY, false);
boolean widgetIsEnabled = TwitterService.widgetIsEnabled;
Log.v(TAG, "Check Updates is " + needCheck + "/wg:" + widgetIsEnabled);
if (!needCheck && !widgetIsEnabled) {
Log.d(TAG, "Check update preference is false.");
stopSelf();
return;
}
if (!getApi().isLoggedIn()) {
Log.d(TAG, "Not logged in.");
stopSelf();
return;
}
schedule(TwitterService.this);
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNewTweets = new ArrayList<Tweet>();
mNewMentions = new ArrayList<Tweet>();
mNewDms = new ArrayList<Dm>();
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mRetrieveTask = new RetrieveTask();
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.execute((TaskParams[]) null);
}
}
private void processNewTweets() {
int count = mNewTweets.size();
if (count <= 0) {
return;
}
Tweet latestTweet = mNewTweets.get(0);
String title;
String text;
if (count == 1) {
title = latestTweet.screenName;
text = TextHelper.getSimpleTweetText(latestTweet.text);
} else {
title = getString(R.string.service_new_twitter_updates);
text = getString(R.string.service_x_new_tweets);
text = MessageFormat.format(text, count);
}
PendingIntent intent = PendingIntent.getActivity(this, 0,
TwitterActivity.createIntent(this), 0);
notify(intent, TWEET_NOTIFICATION_ID, R.drawable.notify_tweet,
TextHelper.getSimpleTweetText(latestTweet.text), title, text);
}
private void processNewMentions() {
int count = mNewMentions.size();
if (count <= 0) {
return;
}
Tweet latestTweet = mNewMentions.get(0);
String title;
String text;
if (count == 1) {
title = latestTweet.screenName;
text = TextHelper.getSimpleTweetText(latestTweet.text);
} else {
title = getString(R.string.service_new_mention_updates);
text = getString(R.string.service_x_new_mentions);
text = MessageFormat.format(text, count);
}
PendingIntent intent = PendingIntent.getActivity(this, 0,
MentionActivity.createIntent(this), 0);
notify(intent, MENTION_NOTIFICATION_ID, R.drawable.notify_mention,
TextHelper.getSimpleTweetText(latestTweet.text), title, text);
}
private static int TWEET_NOTIFICATION_ID = 0;
private static int DM_NOTIFICATION_ID = 1;
private static int MENTION_NOTIFICATION_ID = 2;
private void notify(PendingIntent intent, int notificationId,
int notifyIconId, String tickerText, String title, String text) {
Notification notification = new Notification(notifyIconId, tickerText,
System.currentTimeMillis());
notification.setLatestEventInfo(this, title, text, intent);
notification.flags = Notification.FLAG_AUTO_CANCEL
| Notification.FLAG_ONLY_ALERT_ONCE
| Notification.FLAG_SHOW_LIGHTS;
notification.ledARGB = 0xFF84E4FA;
notification.ledOnMS = 5000;
notification.ledOffMS = 5000;
String ringtoneUri = TwitterApplication.mPref.getString(
Preferences.RINGTONE_KEY, null);
if (ringtoneUri == null) {
notification.defaults |= Notification.DEFAULT_SOUND;
} else {
notification.sound = Uri.parse(ringtoneUri);
}
if (TwitterApplication.mPref.getBoolean(Preferences.VIBRATE_KEY, false)) {
notification.defaults |= Notification.DEFAULT_VIBRATE;
}
mNotificationManager.notify(notificationId, notification);
}
private void processNewDms() {
int count = mNewDms.size();
if (count <= 0) {
return;
}
Dm latest = mNewDms.get(0);
String title;
String text;
if (count == 1) {
title = latest.screenName;
text = TextHelper.getSimpleTweetText(latest.text);
} else {
title = getString(R.string.service_new_direct_message_updates);
text = getString(R.string.service_x_new_direct_messages);
text = MessageFormat.format(text, count);
}
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
DmActivity.createIntent(), 0);
notify(pendingIntent, DM_NOTIFICATION_ID, R.drawable.notify_dm,
TextHelper.getSimpleTweetText(latest.text), title, text);
}
@Override
public void onDestroy() {
Log.d(TAG, "Service Destroy.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
mRetrieveTask.cancel(true);
}
mWakeLock.release();
super.onDestroy();
}
public static void schedule(Context context) {
SharedPreferences preferences = TwitterApplication.mPref;
boolean needCheck = preferences.getBoolean(
Preferences.CHECK_UPDATES_KEY, false);
boolean widgetIsEnabled = TwitterService.widgetIsEnabled;
if (!needCheck && !widgetIsEnabled) {
Log.d(TAG, "Check update preference is false.");
return;
}
String intervalPref = preferences
.getString(
Preferences.CHECK_UPDATE_INTERVAL_KEY,
context.getString(R.string.pref_check_updates_interval_default));
int interval = Integer.parseInt(intervalPref);
// interval = 1; //for debug
Intent intent = new Intent(context, TwitterService.class);
PendingIntent pending = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar c = new GregorianCalendar();
c.add(Calendar.MINUTE, interval);
DateFormat df = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
Log.d(TAG, "Schedule, next run at " + df.format(c.getTime()));
AlarmManager alarm = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pending);
if (needCheck) {
alarm.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pending);
} else {
// only for widget
alarm.set(AlarmManager.RTC, c.getTimeInMillis(), pending);
}
}
public static void unschedule(Context context) {
Intent intent = new Intent(context, TwitterService.class);
PendingIntent pending = PendingIntent.getService(context, 0, intent, 0);
AlarmManager alarm = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Log.d(TAG, "Cancelling alarms.");
alarm.cancel(pending);
}
private static boolean widgetIsEnabled = false;
public static void setWidgetStatus(boolean isEnabled) {
widgetIsEnabled = isEnabled;
}
public static boolean isWidgetEnabled() {
return widgetIsEnabled;
}
private class RetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
SharedPreferences preferences = TwitterApplication.mPref;
boolean timeline_only = preferences.getBoolean(
Preferences.TIMELINE_ONLY_KEY, false);
boolean replies_only = preferences.getBoolean(
Preferences.REPLIES_ONLY_KEY, true);
boolean dm_only = preferences.getBoolean(Preferences.DM_ONLY_KEY,
true);
Log.d(TAG, "Widget Is Enabled? " + TwitterService.widgetIsEnabled);
if (timeline_only || TwitterService.widgetIsEnabled) {
String maxId = getDb()
.fetchMaxTweetId(TwitterApplication.getMyselfId(),
StatusTable.TYPE_HOME);
Log.d(TAG, "Max id is:" + maxId);
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
try {
if (maxId != null) {
statusList = getApi().getFriendsTimeline(
new Paging(maxId));
} else {
statusList = getApi().getFriendsTimeline();
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Tweet tweet;
tweet = Tweet.create(status);
mNewTweets.add(tweet);
Log.d(TAG, mNewTweets.size() + " new tweets.");
int count = getDb().addNewTweetsAndCountUnread(mNewTweets,
TwitterApplication.getMyselfId(),
StatusTable.TYPE_HOME);
if (count <= 0) {
return TaskResult.FAILED;
}
}
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
if (replies_only) {
String maxMentionId = getDb().fetchMaxTweetId(
TwitterApplication.getMyselfId(),
StatusTable.TYPE_MENTION);
Log.d(TAG, "Max mention id is:" + maxMentionId);
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
try {
if (maxMentionId != null) {
statusList = getApi().getMentions(
new Paging(maxMentionId));
} else {
statusList = getApi().getMentions();
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
int unReadMentionsCount = 0;
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Tweet tweet = Tweet.create(status);
mNewMentions.add(tweet);
unReadMentionsCount = getDb().addNewTweetsAndCountUnread(
mNewMentions, TwitterApplication.getMyselfId(),
StatusTable.TYPE_MENTION);
if (unReadMentionsCount <= 0) {
return TaskResult.FAILED;
}
}
Log.v(TAG, "Got mentions " + unReadMentionsCount + "/"
+ mNewMentions.size());
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
if (dm_only) {
String maxId = getDb().fetchMaxDmId(false);
Log.d(TAG, "Max DM id is:" + maxId);
List<com.ch_linghu.fanfoudroid.fanfou.DirectMessage> dmList;
try {
if (maxId != null) {
dmList = getApi().getDirectMessages(new Paging(maxId));
} else {
dmList = getApi().getDirectMessages();
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
for (com.ch_linghu.fanfoudroid.fanfou.DirectMessage directMessage : dmList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Dm dm;
dm = Dm.create(directMessage, false);
mNewDms.add(dm);
Log.d(TAG, mNewDms.size() + " new DMs.");
int count = 0;
TwitterDatabase db = getDb();
if (db.fetchDmCount() > 0) {
count = db.addNewDmsAndCountUnread(mNewDms);
} else {
Log.d(TAG, "No existing DMs. Don't notify.");
db.addDms(mNewDms, false);
}
if (count <= 0) {
return TaskResult.FAILED;
}
}
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
return TaskResult.OK;
}
}
}
| Java |
package com.ch_linghu.fanfoudroid.service;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;
import com.ch_linghu.fanfoudroid.FanfouWidget;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
public class WidgetService extends Service {
protected static final String TAG = "WidgetService";
private int position = 0;
private List<Tweet> tweets;
private TwitterDatabase getDb() {
return TwitterApplication.mDb;
}
public String getUserId() {
return TwitterApplication.getMyselfId();
}
private void fetchMessages() {
if (tweets == null) {
tweets = new ArrayList<Tweet>();
}else{
tweets.clear();
}
Cursor cursor = getDb().fetchAllTweets(getUserId(),
StatusTable.TYPE_HOME);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Tweet tweet = StatusTable.parseCursor(cursor);
tweets.add(tweet);
} while (cursor.moveToNext());
}
}
}
public RemoteViews buildUpdate(Context context) {
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_initial_layout);
updateViews
.setTextViewText(R.id.status_text, tweets.get(position).text);
//updateViews.setOnClickPendingIntent(viewId, pendingIntent)
position++;
return updateViews;
}
private Handler handler = new Handler();
private Runnable mTask = new Runnable() {
@Override
public void run() {
Log.d(TAG, "tweets size="+tweets.size()+" position=" + position);
if (position >= tweets.size()) {
position = 0;
}
ComponentName fanfouWidget = new ComponentName(WidgetService.this,
FanfouWidget.class);
AppWidgetManager manager = AppWidgetManager
.getInstance(getBaseContext());
manager.updateAppWidget(fanfouWidget,
buildUpdate(WidgetService.this));
handler.postDelayed(mTask, 10000);
}
};
public static void schedule(Context context) {
SharedPreferences preferences = TwitterApplication.mPref;
if (!preferences.getBoolean(Preferences.CHECK_UPDATES_KEY, false)) {
Log.d(TAG, "Check update preference is false.");
return;
}
String intervalPref = preferences
.getString(
Preferences.CHECK_UPDATE_INTERVAL_KEY,
context.getString(R.string.pref_check_updates_interval_default));
int interval = Integer.parseInt(intervalPref);
Intent intent = new Intent(context, WidgetService.class);
PendingIntent pending = PendingIntent.getService(context, 0, intent, 0);
Calendar c = new GregorianCalendar();
c.add(Calendar.MINUTE, interval);
DateFormat df = new SimpleDateFormat("h:mm a");
Log.d(TAG, "Scheduling alarm at " + df.format(c.getTime()));
AlarmManager alarm = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pending);
alarm.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pending);
}
/**
* @see android.app.Service#onBind(Intent)
*/
@Override
public IBinder onBind(Intent intent) {
// TODO Put your code here
return null;
}
/**
* @see android.app.Service#onCreate()
*/
@Override
public void onCreate() {
Log.d(TAG, "WidgetService onCreate");
schedule(WidgetService.this);
}
/**
* @see android.app.Service#onStart(Intent,int)
*/
@Override
public void onStart(Intent intent, int startId) {
Log.d(TAG, "WidgetService onStart");
fetchMessages();
handler.removeCallbacks(mTask);
handler.postDelayed(mTask, 10000);
}
@Override
public void onDestroy() {
Log.d(TAG, "WidgetService Stop ");
handler.removeCallbacks(mTask);//当服务结束时,删除线程
super.onDestroy();
}
}
| Java |
package com.ch_linghu.fanfoudroid;
import java.text.MessageFormat;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ListView;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.UserArrayBaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter;
public class FollowersActivity extends UserArrayBaseActivity {
private ListView mUserList;
private UserArrayAdapter mAdapter;
private static final String TAG = "FollowersActivity";
private String userId;
private String userName;
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FOLLOWERS";
private static final String USER_ID = "userId";
private static final String USER_NAME = "userName";
private int currentPage=1;
private int followersCount=0;
private static final double PRE_PAGE_COUNT=100.0;//官方分页为每页100
private int pageCount=0;
private String[] ids;
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
this.userId = extras.getString(USER_ID);
this.userName = extras.getString(USER_NAME);
} else {
// 获取登录用户id
userId=TwitterApplication.getMyselfId();
userName=TwitterApplication.getMyselfName();
}
if (super._onCreate(savedInstanceState)) {
String myself = TwitterApplication.getMyselfId();
if(getUserId()==myself){
mNavbar.setHeaderTitle(MessageFormat.format(
getString(R.string.profile_followers_count_title), "我"));
} else {
mNavbar.setHeaderTitle(MessageFormat.format(
getString(R.string.profile_followers_count_title), userName));
}
return true;
}else{
return false;
}
}
public static Intent createIntent(String userId, String userName) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(USER_ID, userId);
intent.putExtra(USER_NAME, userName);
return intent;
}
@Override
public Paging getNextPage() {
currentPage+=1;
return new Paging(currentPage);
}
@Override
protected String getUserId() {
return this.userId;
}
@Override
public Paging getCurrentPage() {
return new Paging(this.currentPage);
}
@Override
protected List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers(
String userId, Paging page) throws HttpException {
return getApi().getFollowersList(userId, page);
}
}
| Java |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.app.ImageCache;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.http.HttpClient;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.task.TweetCommonTask;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class StatusActivity extends BaseActivity {
private static final String TAG = "StatusActivity";
private static final String SIS_RUNNING_KEY = "running";
private static final String PREFS_NAME = "com.ch_linghu.fanfoudroid";
private static final String EXTRA_TWEET = "tweet";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.STATUS";
static final private int CONTEXT_REFRESH_ID = 0x0001;
static final private int CONTEXT_CLIPBOARD_ID = 0x0002;
static final private int CONTEXT_DELETE_ID = 0x0003;
// Task TODO: tasks
private GenericTask mReplyTask;
private GenericTask mStatusTask;
private GenericTask mPhotoTask; // TODO: 压缩图片,提供获取图片的过程中可取消获取
private GenericTask mFavTask;
private GenericTask mDeleteTask;
private NavBar mNavbar;
private Feedback mFeedback;
private TaskListener mReplyTaskListener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
showReplyStatus(replyTweet);
StatusActivity.this.mFeedback.success("");
}
@Override
public String getName() {
return "GetReply";
}
};
private TaskListener mStatusTaskListener = new TaskAdapter() {
@Override
public void onPreExecute(GenericTask task) {
clean();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
StatusActivity.this.mFeedback.success("");
draw();
}
@Override
public String getName() {
return "GetStatus";
}
};
private TaskListener mPhotoTaskListener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
status_photo.setImageBitmap(mPhotoBitmap);
} else {
status_photo.setVisibility(View.GONE);
}
StatusActivity.this.mFeedback.success("");
}
@Override
public String getName() {
// TODO Auto-generated method stub
return "GetPhoto";
}
};
private TaskListener mFavTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "FavoriteTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
onFavSuccess();
} else if (result == TaskResult.IO_ERROR) {
onFavFailure();
}
}
};
private TaskListener mDeleteTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "DeleteTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
onDeleteSuccess();
} else if (result == TaskResult.IO_ERROR) {
onDeleteFailure();
}
}
};
// View
private TextView tweet_screen_name;
private TextView tweet_text;
private TextView tweet_user_info;
private ImageView profile_image;
private TextView tweet_source;
private TextView tweet_created_at;
private ImageButton btn_person_more;
private ImageView status_photo = null; // if exists
private ViewGroup reply_wrap;
private TextView reply_status_text = null; // if exists
private TextView reply_status_date = null; // if exists
private ImageButton tweet_fav;
private Tweet tweet = null;
private Tweet replyTweet = null; // if exists
private HttpClient mClient;
private Bitmap mPhotoBitmap = ImageCache.mDefaultBitmap; // if exists
public static Intent createIntent(Tweet tweet) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.putExtra(EXTRA_TWEET, tweet);
return intent;
}
private static Pattern PHOTO_PAGE_LINK = Pattern
.compile("http://fanfou.com(/photo/[-a-zA-Z0-9+&@#%?=~_|!:,.;]*[-a-zA-Z0-9+&@#%=~_|])");
private static Pattern PHOTO_SRC_LINK = Pattern
.compile("src=\"(http:\\/\\/photo\\.fanfou\\.com\\/.*?)\"");
/**
* 获得消息中的照片页面链接
*
* @param text
* 消息文本
* @param size
* 照片尺寸
* @return 照片页面的链接,若不存在,则返回null
*/
public static String getPhotoPageLink(String text, String size) {
Matcher m = PHOTO_PAGE_LINK.matcher(text);
if (m.find()) {
String THUMBNAIL = TwitterApplication.mContext
.getString(R.string.pref_photo_preview_type_thumbnail);
String MIDDLE = TwitterApplication.mContext
.getString(R.string.pref_photo_preview_type_middle);
String ORIGINAL = TwitterApplication.mContext
.getString(R.string.pref_photo_preview_type_original);
if (size.equals(THUMBNAIL) || size.equals(MIDDLE)) {
return "http://m.fanfou.com" + m.group(1);
} else if (size.endsWith(ORIGINAL)) {
return m.group(0);
} else {
return null;
}
} else {
return null;
}
}
/**
* 获得照片页面中的照片链接
*
* @param pageHtml
* 照片页面文本
* @return 照片链接,若不存在,则返回null
*/
public static String getPhotoURL(String pageHtml) {
Matcher m = PHOTO_SRC_LINK.matcher(pageHtml);
if (m.find()) {
return m.group(1);
} else {
return null;
}
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)) {
mClient = getApi().getHttpClient();
// Intent & Action & Extras
Intent intent = getIntent();
String action = intent.getAction();
Bundle extras = intent.getExtras();
// Must has extras
if (null == extras) {
Log.e(TAG, this.getClass().getName() + " must has extras.");
finish();
return false;
}
setContentView(R.layout.status);
mNavbar = new NavBar(NavBar.HEADER_STYLE_BACK, this);
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
findView();
bindNavBarListener();
// Set view with intent data
this.tweet = extras.getParcelable(EXTRA_TWEET);
draw();
bindFooterBarListener();
bindReplyViewListener();
return true;
} else {
return false;
}
}
private void findView() {
tweet_screen_name = (TextView) findViewById(R.id.tweet_screen_name);
tweet_user_info = (TextView) findViewById(R.id.tweet_user_info);
tweet_text = (TextView) findViewById(R.id.tweet_text);
tweet_source = (TextView) findViewById(R.id.tweet_source);
profile_image = (ImageView) findViewById(R.id.profile_image);
tweet_created_at = (TextView) findViewById(R.id.tweet_created_at);
btn_person_more = (ImageButton) findViewById(R.id.person_more);
tweet_fav = (ImageButton) findViewById(R.id.tweet_fav);
reply_wrap = (ViewGroup) findViewById(R.id.reply_wrap);
reply_status_text = (TextView) findViewById(R.id.reply_status_text);
reply_status_date = (TextView) findViewById(R.id.reply_tweet_created_at);
status_photo = (ImageView) findViewById(R.id.status_photo);
}
private void bindNavBarListener() {
mNavbar.getRefreshButton().setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
doGetStatus(tweet.id);
}
});
}
private void bindFooterBarListener() {
// person_more
btn_person_more.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = ProfileActivity.createIntent(tweet.userId);
startActivity(intent);
}
});
// Footer bar
TextView footer_btn_share = (TextView) findViewById(R.id.footer_btn_share);
TextView footer_btn_reply = (TextView) findViewById(R.id.footer_btn_reply);
TextView footer_btn_retweet = (TextView) findViewById(R.id.footer_btn_retweet);
TextView footer_btn_fav = (TextView) findViewById(R.id.footer_btn_fav);
TextView footer_btn_more = (TextView) findViewById(R.id.footer_btn_more);
// 分享
footer_btn_share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(
Intent.EXTRA_TEXT,
String.format("@%s %s", tweet.screenName,
TextHelper.getSimpleTweetText(tweet.text)));
startActivity(Intent.createChooser(intent,
getString(R.string.cmenu_share)));
}
});
// 回复
footer_btn_reply.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = WriteActivity.createNewReplyIntent(
tweet.text, tweet.screenName, tweet.id);
startActivity(intent);
}
});
// 转发
footer_btn_retweet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = WriteActivity.createNewRepostIntent(
StatusActivity.this, tweet.text, tweet.screenName,
tweet.id);
startActivity(intent);
}
});
// 收藏/取消收藏
footer_btn_fav.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (tweet.favorited.equals("true")) {
doFavorite("del", tweet.id);
} else {
doFavorite("add", tweet.id);
}
}
});
// TODO: 更多操作
registerForContextMenu(footer_btn_more);
footer_btn_more.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openContextMenu(v);
}
});
}
private void bindReplyViewListener() {
// 点击回复消息打开新的Status界面
OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!TextUtils.isEmpty(tweet.inReplyToStatusId)) {
if (replyTweet == null) {
Log.w(TAG, "Selected item not available.");
} else {
launchActivity(StatusActivity.createIntent(replyTweet));
}
}
}
};
reply_wrap.setOnClickListener(listener);
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause.");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart.");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume.");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart.");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop.");
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mReplyTask != null
&& mReplyTask.getStatus() == GenericTask.Status.RUNNING) {
mReplyTask.cancel(true);
}
if (mPhotoTask != null
&& mPhotoTask.getStatus() == GenericTask.Status.RUNNING) {
mPhotoTask.cancel(true);
}
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
mFavTask.cancel(true);
}
super.onDestroy();
}
private ImageLoaderCallback callback = new ImageLoaderCallback() {
@Override
public void refresh(String url, Bitmap bitmap) {
profile_image.setImageBitmap(bitmap);
}
};
private void clean() {
tweet_screen_name.setText("");
tweet_text.setText("");
tweet_created_at.setText("");
tweet_source.setText("");
tweet_user_info.setText("");
tweet_fav.setEnabled(false);
profile_image.setImageBitmap(ImageCache.mDefaultBitmap);
status_photo.setVisibility(View.GONE);
ViewGroup reply_wrap = (ViewGroup) findViewById(R.id.reply_wrap);
reply_wrap.setVisibility(View.GONE);
}
private void draw() {
Log.d(TAG, "draw");
String PHOTO_PREVIEW_TYPE_NONE = getString(R.string.pref_photo_preview_type_none);
String PHOTO_PREVIEW_TYPE_THUMBNAIL = getString(R.string.pref_photo_preview_type_thumbnail);
String PHOTO_PREVIEW_TYPE_MIDDLE = getString(R.string.pref_photo_preview_type_middle);
String PHOTO_PREVIEW_TYPE_ORIGINAL = getString(R.string.pref_photo_preview_type_original);
SharedPreferences pref = getPreferences();
String photoPreviewSize = pref.getString(Preferences.PHOTO_PREVIEW,
PHOTO_PREVIEW_TYPE_ORIGINAL);
boolean forceShowAllImage = pref.getBoolean(
Preferences.FORCE_SHOW_ALL_IMAGE, false);
tweet_screen_name.setText(tweet.screenName);
TextHelper.setTweetText(tweet_text, tweet.text);
tweet_created_at.setText(DateTimeHelper.getRelativeDate(tweet.createdAt));
tweet_source.setText(getString(R.string.tweet_source_prefix)
+ tweet.source);
tweet_user_info.setText(tweet.userId);
boolean isFav = (tweet.favorited.equals("true")) ? true : false;
tweet_fav.setEnabled(isFav);
// Bitmap mProfileBitmap =
// TwitterApplication.mImageManager.get(tweet.profileImageUrl);
profile_image
.setImageBitmap(TwitterApplication.mImageLoader
.get(tweet.profileImageUrl, callback));
// has photo
if (!photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_NONE)) {
String photoLink;
boolean isPageLink = false;
if (photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_THUMBNAIL)) {
photoLink = tweet.thumbnail_pic;
} else if (photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_MIDDLE)) {
photoLink = tweet.bmiddle_pic;
} else if (photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_ORIGINAL)) {
photoLink = tweet.original_pic;
} else {
Log.e(TAG, "Invalid Photo Preview Size Type");
photoLink = "";
}
// 如果选用了强制显示则再尝试分析图片链接
if (forceShowAllImage) {
photoLink = getPhotoPageLink(tweet.text, photoPreviewSize);
isPageLink = true;
}
if (!TextUtils.isEmpty(photoLink)) {
status_photo.setVisibility(View.VISIBLE);
status_photo.setImageBitmap(mPhotoBitmap);
doGetPhoto(photoLink, isPageLink);
}
} else {
status_photo.setVisibility(View.GONE);
}
// has reply
if (!TextUtils.isEmpty(tweet.inReplyToStatusId)) {
ViewGroup reply_wrap = (ViewGroup) findViewById(R.id.reply_wrap);
reply_wrap.setVisibility(View.VISIBLE);
reply_status_text = (TextView) findViewById(R.id.reply_status_text);
reply_status_date = (TextView) findViewById(R.id.reply_tweet_created_at);
doGetReply(tweet.inReplyToStatusId);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mReplyTask != null
&& mReplyTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
private String fetchWebPage(String url) throws HttpException {
Log.d(TAG, "Fetching WebPage: " + url);
Response res = mClient.get(url);
return res.asString();
}
private Bitmap fetchPhotoBitmap(String url) throws HttpException,
IOException {
Log.d(TAG, "Fetching Photo: " + url);
Response res = mClient.get(url);
//FIXME:这里使用了一个作废的方法,如何修正?
InputStream is = res.asStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
is.close();
return bitmap;
}
private void doGetReply(String status_id) {
Log.d(TAG, "Attempting get status task.");
mFeedback.start("");
if (mReplyTask != null
&& mReplyTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mReplyTask = new GetReplyTask();
mReplyTask.setListener(mReplyTaskListener);
TaskParams params = new TaskParams();
params.put("reply_id", status_id);
mReplyTask.execute(params);
}
}
private class GetReplyTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
TaskParams param = params[0];
com.ch_linghu.fanfoudroid.fanfou.Status status;
try {
String reply_id = param.getString("reply_id");
if (!TextUtils.isEmpty(reply_id)) {
// 首先查看是否在数据库中,如不在再去获取
replyTweet = getDb().queryTweet(reply_id, -1);
if (replyTweet == null) {
status = getApi().showStatus(reply_id);
replyTweet = Tweet.create(status);
}
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
private void doGetStatus(String status_id) {
Log.d(TAG, "Attempting get status task.");
mFeedback.start("");
if (mStatusTask != null
&& mStatusTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mStatusTask = new GetStatusTask();
mStatusTask.setListener(mStatusTaskListener);
TaskParams params = new TaskParams();
params.put("id", status_id);
mStatusTask.execute(params);
}
}
private class GetStatusTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
TaskParams param = params[0];
com.ch_linghu.fanfoudroid.fanfou.Status status;
try {
String id = param.getString("id");
if (!TextUtils.isEmpty(id)) {
status = getApi().showStatus(id);
mFeedback.update(80);
tweet = Tweet.create(status);
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
mFeedback.update(99);
return TaskResult.OK;
}
}
private void doGetPhoto(String photoPageURL, boolean isPageLink) {
mFeedback.start("");
if (mPhotoTask != null
&& mPhotoTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mPhotoTask = new GetPhotoTask();
mPhotoTask.setListener(mPhotoTaskListener);
TaskParams params = new TaskParams();
params.put("photo_url", photoPageURL);
params.put("is_page_link", isPageLink);
mPhotoTask.execute(params);
}
}
private class GetPhotoTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
TaskParams param = params[0];
try {
String photoURL = param.getString("photo_url");
boolean isPageLink = param.getBoolean("is_page_link");
if (!TextUtils.isEmpty(photoURL)) {
if (isPageLink) {
String pageHtml = fetchWebPage(photoURL);
String photoSrcURL = getPhotoURL(pageHtml);
if (photoSrcURL != null) {
mPhotoBitmap = fetchPhotoBitmap(photoSrcURL);
}
} else {
mPhotoBitmap = fetchPhotoBitmap(photoURL);
}
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
private void showReplyStatus(Tweet tweet) {
if (tweet != null) {
String text = tweet.screenName + " : " + tweet.text;
TextHelper.setSimpleTweetText(reply_status_text, text);
reply_status_date.setText(DateTimeHelper.getRelativeDate(tweet.createdAt));
} else {
String msg = MessageFormat.format(
getString(R.string.status_status_reply_cannot_display),
this.tweet.inReplyToScreenName);
reply_status_text.setText(msg);
}
}
public void onDeleteFailure() {
Log.e(TAG, "Delete failed");
}
public void onDeleteSuccess() {
finish();
}
// for HasFavorite interface
public void doFavorite(String action, String id) {
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
if (!TextUtils.isEmpty(id)) {
Log.d(TAG, "doFavorite.");
mFavTask = new TweetCommonTask.FavoriteTask(this);
mFavTask.setListener(mFavTaskListener);
TaskParams param = new TaskParams();
param.put("action", action);
param.put("id", id);
mFavTask.execute(param);
}
}
}
public void onFavSuccess() {
// updateProgress(getString(R.string.refreshing));
if (((TweetCommonTask.FavoriteTask) mFavTask).getType().equals(
TweetCommonTask.FavoriteTask.TYPE_ADD)) {
tweet.favorited = "true";
tweet_fav.setEnabled(true);
} else {
tweet.favorited = "false";
tweet_fav.setEnabled(false);
}
}
public void onFavFailure() {
// updateProgress(getString(R.string.refreshing));
}
private void doDelete(String id) {
if (mDeleteTask != null
&& mDeleteTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mDeleteTask = new TweetCommonTask.DeleteTask(this);
mDeleteTask.setListener(mDeleteTaskListener);
TaskParams params = new TaskParams();
params.put("id", id);
mDeleteTask.execute(params);
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case CONTEXT_REFRESH_ID:
doGetStatus(tweet.id);
return true;
case CONTEXT_CLIPBOARD_ID:
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(TextHelper.getSimpleTweetText(tweet.text));
return true;
case CONTEXT_DELETE_ID:
doDelete(tweet.id);
return true;
}
return super.onContextItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
menu.setHeaderIcon(android.R.drawable.ic_menu_more);
menu.setHeaderTitle(getString(R.string.cmenu_more));
menu.add(0, CONTEXT_REFRESH_ID, 0, R.string.omenu_refresh);
menu.add(0, CONTEXT_CLIPBOARD_ID, 0, R.string.cmenu_clipboard);
if (tweet.userId.equals(TwitterApplication.getMyselfId())) {
menu.add(0, CONTEXT_DELETE_ID, 0, R.string.cmenu_delete);
}
}
} | Java |
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.List;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.fanfou.SavedSearch;
import com.ch_linghu.fanfoudroid.fanfou.Trend;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.util.TextHelper;
import com.commonsware.cwac.merge.MergeAdapter;
public class SearchActivity extends BaseActivity {
private static final String TAG = SearchActivity.class.getSimpleName();
private static final int LOADING = 1;
private static final int NETWORKERROR = 2;
private static final int SUCCESS = 3;
private EditText mSearchEdit;
private ListView mSearchSectionList;
private TextView trendsTitle;
private TextView savedSearchTitle;
private MergeAdapter mSearchSectionAdapter;
private SearchAdapter trendsAdapter;
private SearchAdapter savedSearchesAdapter;
private ArrayList<SearchItem> trends;
private ArrayList<SearchItem> savedSearch;
private String initialQuery;
private NavBar mNavbar;
private Feedback mFeedback;
private GenericTask trendsAndSavedSearchesTask;
private TaskListener trendsAndSavedSearchesTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "trendsAndSavedSearchesTask";
}
@Override
public void onPreExecute(GenericTask task) {
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
refreshSearchSectionList(SearchActivity.SUCCESS);
} else if (result == TaskResult.IO_ERROR) {
refreshSearchSectionList(SearchActivity.NETWORKERROR);
Toast.makeText(
SearchActivity.this,
getResources()
.getString(
R.string.login_status_network_or_connection_error),
Toast.LENGTH_SHORT).show();
}
}
};
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate()...");
if (super._onCreate(savedInstanceState)) {
setContentView(R.layout.search);
mNavbar = new NavBar(NavBar.HEADER_STYLE_SEARCH, this);
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
initView();
initSearchSectionList();
refreshSearchSectionList(SearchActivity.LOADING);
doGetSavedSearches();
return true;
} else {
return false;
}
}
private void initView() {
mSearchEdit = (EditText) findViewById(R.id.search_edit);
mSearchEdit.setOnKeyListener(enterKeyHandler);
trendsTitle = (TextView) getLayoutInflater().inflate(
R.layout.search_section_header, null);
trendsTitle.setText(getResources().getString(R.string.trends_title));
savedSearchTitle = (TextView) getLayoutInflater().inflate(
R.layout.search_section_header, null);
savedSearchTitle.setText(getResources().getString(
R.string.saved_search_title));
mSearchSectionAdapter = new MergeAdapter();
mSearchSectionList = (ListView) findViewById(R.id.search_section_list);
mNavbar.getSearchButton().setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
initialQuery = mSearchEdit.getText().toString();
startSearch();
}
});
}
@Override
protected void onResume() {
Log.d(TAG, "onResume()...");
super.onResume();
}
private void doGetSavedSearches() {
if (trendsAndSavedSearchesTask != null
&& trendsAndSavedSearchesTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
trendsAndSavedSearchesTask = new TrendsAndSavedSearchesTask();
trendsAndSavedSearchesTask
.setListener(trendsAndSavedSearchesTaskListener);
trendsAndSavedSearchesTask.setFeedback(mFeedback);
trendsAndSavedSearchesTask.execute();
}
}
private void initSearchSectionList() {
trends = new ArrayList<SearchItem>();
savedSearch = new ArrayList<SearchItem>();
trendsAdapter = new SearchAdapter(this);
savedSearchesAdapter = new SearchAdapter(this);
mSearchSectionAdapter.addView(savedSearchTitle);
mSearchSectionAdapter.addAdapter(savedSearchesAdapter);
mSearchSectionAdapter.addView(trendsTitle);
mSearchSectionAdapter.addAdapter(trendsAdapter);
mSearchSectionList.setAdapter(mSearchSectionAdapter);
}
/**
* 辅助计算位置的类
*
* @author jmx
*
*/
class PositionHelper {
/**
* 返回指定位置属于哪一个小节
*
* @param position
* 绝对位置
* @return 小节的序号,0是第一小节,1是第二小节, -1为无效位置
*/
public int getSectionIndex(int position) {
int[] contentLength = new int[2];
contentLength[0] = savedSearchesAdapter.getCount();
contentLength[1] = trendsAdapter.getCount();
if (position > 0 && position < contentLength[0] + 1) {
return 0;
} else if (position > contentLength[0] + 1
&& position < (contentLength[0] + contentLength[1] + 1) + 1) {
return 1;
} else {
return -1;
}
}
/**
* 返回指定位置在自己所在小节的相对位置
*
* @param position
* 绝对位置
* @return 所在小节的相对位置,-1为无效位置
*/
public int getRelativePostion(int position) {
int[] contentLength = new int[2];
contentLength[0] = savedSearchesAdapter.getCount();
contentLength[1] = trendsAdapter.getCount();
int sectionIndex = getSectionIndex(position);
int offset = 0;
for (int i = 0; i < sectionIndex; ++i) {
offset += contentLength[i] + 1;
}
return position - offset - 1;
}
}
/**
* flag: loading;network error;success
*/
PositionHelper pos_helper = new PositionHelper();
private void refreshSearchSectionList(int flag) {
AdapterView.OnItemClickListener searchSectionListListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long id) {
MergeAdapter adapter = (MergeAdapter) (adapterView.getAdapter());
SearchAdapter subAdapter = (SearchAdapter) adapter
.getAdapter(position);
// 计算针对subAdapter中的相对位置
int relativePos = pos_helper.getRelativePostion(position);
SearchItem item = (SearchItem) (subAdapter.getItem(relativePos));
initialQuery = item.query;
startSearch();
}
};
if (flag == SearchActivity.LOADING) {
mSearchSectionList.setOnItemClickListener(null);
savedSearch.clear();
trends.clear();
savedSearchesAdapter.refresh(getString(R.string.search_loading));
trendsAdapter.refresh(getString(R.string.search_loading));
} else if (flag == SearchActivity.NETWORKERROR) {
mSearchSectionList.setOnItemClickListener(null);
savedSearch.clear();
trends.clear();
savedSearchesAdapter
.refresh(getString(R.string.login_status_network_or_connection_error));
trendsAdapter
.refresh(getString(R.string.login_status_network_or_connection_error));
} else {
savedSearchesAdapter.refresh(savedSearch);
trendsAdapter.refresh(trends);
}
if (flag == SearchActivity.SUCCESS) {
mSearchSectionList
.setOnItemClickListener(searchSectionListListener);
}
}
protected boolean startSearch() {
if (!TextUtils.isEmpty(initialQuery)) {
// 以下这个方法在7可用,在8就报空指针
// triggerSearch(initialQuery, null);
Intent i = new Intent(this, SearchResultActivity.class);
i.putExtra(SearchManager.QUERY, initialQuery);
startActivity(i);
} else if (TextUtils.isEmpty(initialQuery)) {
Toast.makeText(this,
getResources().getString(R.string.search_box_null),
Toast.LENGTH_SHORT).show();
return false;
}
return false;
}
// 搜索框回车键判断
private View.OnKeyListener enterKeyHandler = new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER
|| keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
if (event.getAction() == KeyEvent.ACTION_UP) {
initialQuery = mSearchEdit.getText().toString();
startSearch();
}
return true;
}
return false;
}
};
private class TrendsAndSavedSearchesTask extends GenericTask {
Trend[] trendsList;
List<SavedSearch> savedSearchsList;
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
trendsList = getApi().getTrends().getTrends();
savedSearchsList = getApi().getSavedSearches();
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
trends.clear();
savedSearch.clear();
for (int i = 0; i < trendsList.length; i++) {
SearchItem item = new SearchItem();
item.name = trendsList[i].getName();
item.query = trendsList[i].getQuery();
trends.add(item);
}
for (int i = 0; i < savedSearchsList.size(); i++) {
SearchItem item = new SearchItem();
item.name = savedSearchsList.get(i).getName();
item.query = savedSearchsList.get(i).getQuery();
savedSearch.add(item);
}
return TaskResult.OK;
}
}
}
class SearchItem {
public String name;
public String query;
}
class SearchAdapter extends BaseAdapter {
protected ArrayList<SearchItem> mSearchList;
private Context mContext;
protected LayoutInflater mInflater;
protected StringBuilder mMetaBuilder;
public SearchAdapter(Context context) {
mSearchList = new ArrayList<SearchItem>();
mContext = context;
mInflater = LayoutInflater.from(mContext);
mMetaBuilder = new StringBuilder();
}
public SearchAdapter(Context context, String prompt) {
this(context);
refresh(prompt);
}
public void refresh(ArrayList<SearchItem> searchList) {
mSearchList = searchList;
notifyDataSetChanged();
}
public void refresh(String prompt) {
SearchItem item = new SearchItem();
item.name = prompt;
item.query = null;
mSearchList.clear();
mSearchList.add(item);
notifyDataSetChanged();
}
@Override
public int getCount() {
return mSearchList.size();
}
@Override
public Object getItem(int position) {
return mSearchList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = mInflater.inflate(R.layout.search_section_view, parent,
false);
TextView text = (TextView) view
.findViewById(R.id.search_section_text);
view.setTag(text);
} else {
view = convertView;
}
TextView text = (TextView) view.getTag();
SearchItem item = mSearchList.get(position);
text.setText(item.name);
return view;
}
}
| Java |
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.fanfou.Query;
import com.ch_linghu.fanfoudroid.fanfou.QueryResult;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.TwitterListBaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.MyListView;
import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback;
import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter;
import com.ch_linghu.fanfoudroid.ui.module.TweetArrayAdapter;
public class SearchResultActivity extends TwitterListBaseActivity implements
MyListView.OnNeedMoreListener {
private static final String TAG = "SearchActivity";
// Views.
private MyListView mTweetList;
// State.
private String mSearchQuery;
private ArrayList<Tweet> mTweets;
private TweetArrayAdapter mAdapter;
private int mNextPage = 1;
private String mLastId = null;
private static class State {
State(SearchResultActivity activity) {
mTweets = activity.mTweets;
mNextPage = activity.mNextPage;
}
public ArrayList<Tweet> mTweets;
public int mNextPage;
}
// Tasks.
private GenericTask mSearchTask;
private TaskListener mSearchTaskListener = new TaskAdapter(){
@Override
public void onPreExecute(GenericTask task) {
if (mNextPage == 1) {
updateProgress(getString(R.string.page_status_refreshing));
} else {
updateProgress(getString(R.string.page_status_refreshing));
}
}
@Override
public void onProgressUpdate(GenericTask task, Object param) {
draw();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
draw();
} else {
// Do nothing.
}
updateProgress("");
}
@Override
public String getName() {
return "SearchTask";
}
};
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState)){
Intent intent = getIntent();
// Assume it's SEARCH.
// String action = intent.getAction();
mSearchQuery = intent.getStringExtra(SearchManager.QUERY);
if (TextUtils.isEmpty(mSearchQuery)) {
mSearchQuery = intent.getData().getLastPathSegment();
}
mNavbar.setHeaderTitle(mSearchQuery);
setTitle(mSearchQuery);
State state = (State) getLastNonConfigurationInstance();
if (state != null) {
mTweets = state.mTweets;
draw();
} else {
doSearch();
}
return true;
}else{
return false;
}
}
@Override
protected int getLayoutId(){
return R.layout.main;
}
@Override
protected void onResume() {
super.onResume();
checkIsLogedIn();
}
@Override
public Object onRetainNonConfigurationInstance() {
return createState();
}
private synchronized State createState() {
return new State(this);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mSearchTask != null
&& mSearchTask.getStatus() == GenericTask.Status.RUNNING) {
mSearchTask.cancel(true);
}
super.onDestroy();
}
// UI helpers.
private void updateProgress(String progress) {
mProgressText.setText(progress);
}
@Override
protected void draw() {
mAdapter.refresh(mTweets);
}
private void doSearch() {
Log.d(TAG, "Attempting search.");
if (mSearchTask != null && mSearchTask.getStatus() == GenericTask.Status.RUNNING){
return;
}else{
mSearchTask = new SearchTask();
mSearchTask.setFeedback(mFeedback);
mSearchTask.setListener(mSearchTaskListener);
mSearchTask.execute();
}
}
private class SearchTask extends GenericTask {
ArrayList<Tweet> mTweets = new ArrayList<Tweet>();
@Override
protected TaskResult _doInBackground(TaskParams...params) {
QueryResult result;
try {
Query query = new Query(mSearchQuery);
if (!TextUtils.isEmpty(mLastId)){
query.setMaxId(mLastId);
}
result = getApi().search(query);//.search(mSearchQuery, mNextPage);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
List<com.ch_linghu.fanfoudroid.fanfou.Status> statuses = result.getStatus();
HashSet<String> imageUrls = new HashSet<String>();
publishProgress(SimpleFeedback.calProgressBySize(40, 20, statuses));
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statuses) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Tweet tweet;
tweet = Tweet.create(status);
mLastId = tweet.id;
mTweets.add(tweet);
imageUrls.add(tweet.profileImageUrl);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
addTweets(mTweets);
// if (isCancelled()) {
// return TaskResult.CANCELLED;
// }
//
// publishProgress();
//
// // TODO: what if orientation change?
// ImageManager imageManager = getImageManager();
// MemoryImageCache imageCache = new MemoryImageCache();
//
// for (String imageUrl : imageUrls) {
// if (!Utils.isEmpty(imageUrl)) {
// // Fetch image to cache.
// try {
// Bitmap bitmap = imageManager.fetchImage(imageUrl);
// imageCache.put(imageUrl, bitmap);
// } catch (IOException e) {
// Log.e(TAG, e.getMessage(), e);
// }
// }
//
// if (isCancelled()) {
// return TaskResult.CANCELLED;
// }
// }
//
// addImages(imageCache);
return TaskResult.OK;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
@Override
public void needMore() {
if (!isLastPage()) {
doSearch();
}
}
public boolean isLastPage() {
return mNextPage == -1;
}
@Override
protected void adapterRefresh() {
mAdapter.refresh(mTweets);
}
private synchronized void addTweets(ArrayList<Tweet> tweets) {
if (tweets.size() == 0) {
mNextPage = -1;
return;
}
mTweets.addAll(tweets);
++mNextPage;
}
@Override
protected String getActivityTitle() {
return mSearchQuery;
}
@Override
protected Tweet getContextItemTweet(int position) {
return (Tweet)mAdapter.getItem(position);
}
@Override
protected TweetAdapter getTweetAdapter() {
return mAdapter;
}
@Override
protected ListView getTweetList() {
return mTweetList;
}
@Override
protected void updateTweet(Tweet tweet) {
// TODO Simple and stupid implementation
for (Tweet t : mTweets){
if (t.id.equals(tweet.id)){
t.favorited = tweet.favorited;
break;
}
}
}
@Override
protected boolean useBasicMenu() {
return true;
}
@Override
protected void setupState() {
mTweets = new ArrayList<Tweet>();
mTweetList = (MyListView) findViewById(R.id.tweet_list);
mAdapter = new TweetArrayAdapter(this);
mTweetList.setAdapter(mAdapter);
mTweetList.setOnNeedMoreListener(this);
}
@Override
public void doRetrieve() {
doSearch();
}
}
| Java |
package com.ch_linghu.fanfoudroid.db;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.util.Log;
import com.ch_linghu.fanfoudroid.data.User;
public final class UserInfoTable implements BaseColumns {
public static final String TAG = "UserInfoTable";
public static final String TABLE_NAME = "userinfo";
public static final String FIELD_USER_NAME = "name";
public static final String FIELD_USER_SCREEN_NAME = "screen_name";
public static final String FIELD_LOCALTION = "location";
public static final String FIELD_DESCRIPTION = "description";
public static final String FIELD_PROFILE_IMAGE_URL = "profile_image_url";
public static final String FIELD_URL = "url";
public static final String FIELD_PROTECTED = "protected";
public static final String FIELD_FOLLOWERS_COUNT = "followers_count";
public static final String FIELD_FRIENDS_COUNT = "friends_count";
public static final String FIELD_FAVORITES_COUNT = "favourites_count";
public static final String FIELD_STATUSES_COUNT = "statuses_count";
public static final String FIELD_LAST_STATUS = "last_status";
public static final String FIELD_CREATED_AT = "created_at";
public static final String FIELD_FOLLOWING = "following";
public static final String FIELD_FOLLOWER_IDS="follower_ids";
public static final String[] TABLE_COLUMNS = new String[] { _ID,
FIELD_USER_NAME, FIELD_USER_SCREEN_NAME,
FIELD_LOCALTION, FIELD_DESCRIPTION,
FIELD_PROFILE_IMAGE_URL, FIELD_URL, FIELD_PROTECTED,
FIELD_FOLLOWERS_COUNT, FIELD_FRIENDS_COUNT,
FIELD_FAVORITES_COUNT, FIELD_STATUSES_COUNT,
FIELD_LAST_STATUS, FIELD_CREATED_AT, FIELD_FOLLOWING};
public static final String CREATE_TABLE = "create table "
+ TABLE_NAME + " ("
+ _ID + " text primary key on conflict replace, "
+ FIELD_USER_NAME + " text not null, "
+ FIELD_USER_SCREEN_NAME + " text, "
+ FIELD_LOCALTION + " text, "
+ FIELD_DESCRIPTION + " text, "
+ FIELD_PROFILE_IMAGE_URL + " text, "
+ FIELD_URL + " text, "
+ FIELD_PROTECTED + " boolean, "
+ FIELD_FOLLOWERS_COUNT + " integer, "
+ FIELD_FRIENDS_COUNT + " integer, "
+ FIELD_FAVORITES_COUNT + " integer, "
+ FIELD_STATUSES_COUNT + " integer, "
+ FIELD_LAST_STATUS + " text, "
+ FIELD_CREATED_AT + " date, "
+ FIELD_FOLLOWING + " boolean "
//+FIELD_FOLLOWER_IDS+" text"
+ ")";
/**
* TODO: 将游标解析为一条用户信息
*
* @param cursor 该方法不会关闭游标
* @return 成功返回User类型的单条数据, 失败返回null
*/
public static User parseCursor(Cursor cursor) {
if (null == cursor || 0 == cursor.getCount()) {
Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty.");
return null;
}
User user = new User();
user.id = cursor.getString(cursor.getColumnIndex(_ID));
user.name = cursor.getString(cursor.getColumnIndex(FIELD_USER_NAME));
user.screenName = cursor.getString(cursor.getColumnIndex(FIELD_USER_SCREEN_NAME));
user.location = cursor.getString(cursor.getColumnIndex(FIELD_LOCALTION));
user.description = cursor.getString(cursor.getColumnIndex(FIELD_DESCRIPTION));
user.profileImageUrl = cursor.getString(cursor.getColumnIndex(FIELD_PROFILE_IMAGE_URL));
user.url = cursor.getString(cursor.getColumnIndex(FIELD_URL));
user.isProtected = (0 == cursor.getInt(cursor.getColumnIndex(FIELD_PROTECTED))) ? false : true;
user.followersCount = cursor.getInt(cursor.getColumnIndex(FIELD_FOLLOWERS_COUNT));
user.lastStatus = cursor.getString(cursor.getColumnIndex(FIELD_LAST_STATUS));
user.friendsCount = cursor.getInt(cursor.getColumnIndex(FIELD_FRIENDS_COUNT));
user.favoritesCount = cursor.getInt(cursor.getColumnIndex(FIELD_FAVORITES_COUNT));
user.statusesCount = cursor.getInt(cursor.getColumnIndex(FIELD_STATUSES_COUNT));
user.isFollowing = (0 == cursor.getInt(cursor.getColumnIndex(FIELD_FOLLOWING))) ? false : true;
//TODO:报空指针异常,待查
// try {
// user.createdAt = StatusDatabase.DB_DATE_FORMATTER.parse(cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_CREATED_AT)));
// } catch (ParseException e) {
// Log.w(TAG, "Invalid created at data.");
// }
return user;
}
} | Java |
package com.ch_linghu.fanfoudroid.db;
import java.text.ParseException;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.util.Log;
import com.ch_linghu.fanfoudroid.data.User;
/**
* Table - Followers
*
*/
public final class FollowTable implements BaseColumns {
public static final String TAG = "FollowTable";
public static final String TABLE_NAME = "followers";
public static final String FIELD_USER_NAME = "name";
public static final String FIELD_USER_SCREEN_NAME = "screen_name";
public static final String FIELD_LOCALTION = "location";
public static final String FIELD_DESCRIPTION = "description";
public static final String FIELD_PROFILE_IMAGE_URL = "profile_image_url";
public static final String FIELD_URL = "url";
public static final String FIELD_PROTECTED = "protected";
public static final String FIELD_FOLLOWERS_COUNT = "followers_count";
public static final String FIELD_FRIENDS_COUNT = "friends_count";
public static final String FIELD_FAVORITES_COUNT = "favourites_count";
public static final String FIELD_STATUSES_COUNT = "statuses_count";
public static final String FIELD_LAST_STATUS = "last_status";
public static final String FIELD_CREATED_AT = "created_at";
public static final String FIELD_FOLLOWING = "following";
public static final String[] TABLE_COLUMNS = new String[] { _ID,
FIELD_USER_NAME, FIELD_USER_SCREEN_NAME,
FIELD_LOCALTION, FIELD_DESCRIPTION,
FIELD_PROFILE_IMAGE_URL, FIELD_URL, FIELD_PROTECTED,
FIELD_FOLLOWERS_COUNT, FIELD_FRIENDS_COUNT,
FIELD_FAVORITES_COUNT, FIELD_STATUSES_COUNT,
FIELD_LAST_STATUS, FIELD_CREATED_AT, FIELD_FOLLOWING};
public static final String CREATE_TABLE = "create table "
+ TABLE_NAME + " ("
+ _ID + " text primary key on conflict replace, "
+ FIELD_USER_NAME + " text not null, "
+ FIELD_USER_SCREEN_NAME + " text, "
+ FIELD_LOCALTION + " text, "
+ FIELD_DESCRIPTION + " text, "
+ FIELD_PROFILE_IMAGE_URL + " text, "
+ FIELD_URL + " text, "
+ FIELD_PROTECTED + " boolean, "
+ FIELD_FOLLOWERS_COUNT + " integer, "
+ FIELD_FRIENDS_COUNT + " integer, "
+ FIELD_FAVORITES_COUNT + " integer, "
+ FIELD_STATUSES_COUNT + " integer, "
+ FIELD_LAST_STATUS + " text, "
+ FIELD_CREATED_AT + " date, "
+ FIELD_FOLLOWING + " boolean "
+ ")";
/**
* TODO: 将游标解析为一条用户信息
*
* @param cursor 该方法不会关闭游标
* @return 成功返回User类型的单条数据, 失败返回null
*/
public static User parseCursor(Cursor cursor) {
if (null == cursor || 0 == cursor.getCount()) {
Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty.");
return null;
}
User user = new User();
user.id = cursor.getString(cursor.getColumnIndex(FollowTable._ID));
user.name = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_USER_NAME));
user.screenName = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_USER_SCREEN_NAME));
user.location = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_LOCALTION));
user.description = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_DESCRIPTION));
user.profileImageUrl = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_PROFILE_IMAGE_URL));
user.url = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_URL));
user.isProtected = (0 == cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_PROTECTED))) ? false : true;
user.followersCount = cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_FOLLOWERS_COUNT));
user.lastStatus = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_LAST_STATUS));;
user.friendsCount = cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_FRIENDS_COUNT));
user.favoritesCount = cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_FAVORITES_COUNT));
user.statusesCount = cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_STATUSES_COUNT));
user.isFollowing = (0 == cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_FOLLOWING))) ? false : true;
try {
user.createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_CREATED_AT)));
} catch (ParseException e) {
Log.w(TAG, "Invalid created at data.");
}
return user;
}
} | Java |
package com.ch_linghu.fanfoudroid.db;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.util.Log;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
/**
* Table - Statuses
* <br /> <br />
* 为节省流量,故此表不保证本地数据库中所有消息具有前后连贯性, 而只确保最新的MAX_ROW_NUM条<br />
* 数据的连贯性, 超出部分则视为垃圾数据, 不再允许读取, 也不保证其是前后连续的.<br />
* <br />
* 因为用户可能中途长时间停止使用本客户端,而换其他客户端(如网页), <br />
* 如果保证本地所有数据的连贯性, 那么就必须自动去下载所有本地缺失的中间数据,<br />
* 而这些数据极有可能是用户通过其他客户端阅读过的无用信息, 浪费了用户流量.<br />
* <br />
* 即认为相对于旧信息而言, 新信息对于用户更为价值, 所以只会新信息进行维护, <br />
* 而旧信息一律视为无用的, 如用户需要查看超过MAX_ROW_NUM的旧数据, 可主动点击, <br />
* 从而请求服务器. 本地只缓存最有价值的MAX条最新信息.<br />
* <br />
* 本地数据库中前MAX_ROW_NUM条的数据模拟一个定长列队, 即在尾部插入N条消息, 就会使得头部<br />
* 的N条消息被标记为垃圾数据(但并不立即收回),只有在认为数据库数据过多时,<br />
* 可手动调用 <code>StatusDatabase.gc(int type)</code> 方法进行垃圾清理.<br />
*
*
*/
public final class StatusTable implements BaseColumns {
public static final String TAG = "StatusTable";
// Status Types
public static final int TYPE_HOME = 1; //首页(我和我的好友)
public static final int TYPE_MENTION = 2; //提到我的
public static final int TYPE_USER = 3; //指定USER的
public static final int TYPE_FAVORITE = 4; //收藏
public static final int TYPE_BROWSE = 5; //随便看看
public static final String TABLE_NAME = "status";
public static final int MAX_ROW_NUM = 20; //单类型数据安全区域
public static final String OWNER_ID = "owner"; //用于标识数据的所有者。以便于处理其他用户的信息(如其他用户的收藏)
public static final String USER_ID = "uid";
public static final String USER_SCREEN_NAME = "screen_name";
public static final String PROFILE_IMAGE_URL = "profile_image_url";
public static final String CREATED_AT = "created_at";
public static final String TEXT = "text";
public static final String SOURCE = "source";
public static final String TRUNCATED = "truncated";
public static final String IN_REPLY_TO_STATUS_ID = "in_reply_to_status_id";
public static final String IN_REPLY_TO_USER_ID = "in_reply_to_user_id";
public static final String IN_REPLY_TO_SCREEN_NAME = "in_reply_to_screen_name";
public static final String FAVORITED = "favorited";
public static final String IS_UNREAD = "is_unread";
public static final String STATUS_TYPE = "status_type";
public static final String PIC_THUMB = "pic_thumbnail";
public static final String PIC_MID = "pic_middle";
public static final String PIC_ORIG = "pic_original";
// private static final String FIELD_PHOTO_URL = "photo_url";
// private double latitude = -1;
// private double longitude = -1;
// private String thumbnail_pic;
// private String bmiddle_pic;
// private String original_pic;
public static final String[] TABLE_COLUMNS = new String[] {_ID, USER_SCREEN_NAME,
TEXT, PROFILE_IMAGE_URL, IS_UNREAD, CREATED_AT,
FAVORITED, IN_REPLY_TO_STATUS_ID, IN_REPLY_TO_USER_ID,
IN_REPLY_TO_SCREEN_NAME, TRUNCATED,
PIC_THUMB, PIC_MID, PIC_ORIG,
SOURCE, USER_ID, STATUS_TYPE, OWNER_ID};
public static final String CREATE_TABLE = "CREATE TABLE "
+ TABLE_NAME + " ("
+ _ID + " text not null,"
+ STATUS_TYPE + " text not null, "
+ OWNER_ID + " text not null, "
+ USER_ID + " text not null, "
+ USER_SCREEN_NAME + " text not null, "
+ TEXT + " text not null, "
+ PROFILE_IMAGE_URL + " text not null, "
+ IS_UNREAD + " boolean not null, "
+ CREATED_AT + " date not null, "
+ SOURCE + " text not null, "
+ FAVORITED + " text, " // TODO : text -> boolean
+ IN_REPLY_TO_STATUS_ID + " text, "
+ IN_REPLY_TO_USER_ID + " text, "
+ IN_REPLY_TO_SCREEN_NAME + " text, "
+ PIC_THUMB + " text, "
+ PIC_MID + " text, "
+ PIC_ORIG + " text, "
+ TRUNCATED + " boolean ,"
+ "PRIMARY KEY (" + _ID + ","+ OWNER_ID + "," + STATUS_TYPE + "))";
/**
* 将游标解析为一条Tweet
*
*
* @param cursor 该方法不会移动或关闭游标
* @return 成功返回 Tweet 类型的单条数据, 失败返回null
*/
public static Tweet parseCursor(Cursor cursor) {
if (null == cursor || 0 == cursor.getCount()) {
Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty.");
return null;
} else if ( -1 == cursor.getPosition() ) {
cursor.moveToFirst();
}
Tweet tweet = new Tweet();
tweet.id = cursor.getString(cursor.getColumnIndex(_ID));
tweet.createdAt = DateTimeHelper.parseDateTimeFromSqlite(cursor.getString(cursor.getColumnIndex(CREATED_AT)));
tweet.favorited = cursor.getString(cursor.getColumnIndex(FAVORITED));
tweet.screenName = cursor.getString(cursor.getColumnIndex(USER_SCREEN_NAME));
tweet.userId = cursor.getString(cursor.getColumnIndex(USER_ID));
tweet.text = cursor.getString(cursor.getColumnIndex(TEXT));
tweet.source = cursor.getString(cursor.getColumnIndex(SOURCE));
tweet.profileImageUrl = cursor.getString(cursor.getColumnIndex(PROFILE_IMAGE_URL));
tweet.inReplyToScreenName = cursor.getString(cursor.getColumnIndex(IN_REPLY_TO_SCREEN_NAME));
tweet.inReplyToStatusId = cursor.getString(cursor.getColumnIndex(IN_REPLY_TO_STATUS_ID));
tweet.inReplyToUserId = cursor.getString(cursor.getColumnIndex(IN_REPLY_TO_USER_ID));
tweet.truncated = cursor.getString(cursor.getColumnIndex(TRUNCATED));
tweet.thumbnail_pic = cursor.getString(cursor.getColumnIndex(PIC_THUMB));
tweet.bmiddle_pic = cursor.getString(cursor.getColumnIndex(PIC_MID));
tweet.original_pic = cursor.getString(cursor.getColumnIndex(PIC_ORIG));
tweet.setStatusType(cursor.getInt(cursor.getColumnIndex(STATUS_TYPE)) );
return tweet;
}
} | Java |
package com.ch_linghu.fanfoudroid.db;
/**
* All information of status table
*
*/
public final class StatusTablesInfo {
} | Java |
package com.ch_linghu.fanfoudroid.db;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.dao.StatusDAO;
import com.ch_linghu.fanfoudroid.data.Dm;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.util.DebugTimer;
/**
* A Database which contains all statuses and direct-messages, use
* getInstane(Context) to get a new instance
*
*/
public class TwitterDatabase {
private static final String TAG = "TwitterDatabase";
private static final String DATABASE_NAME = "status_db";
private static final int DATABASE_VERSION = 1;
private static TwitterDatabase instance = null;
private static DatabaseHelper mOpenHelper = null;
private Context mContext = null;
/**
* SQLiteOpenHelper
*
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
// Construct
public DatabaseHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
public DatabaseHelper(Context context, String name) {
this(context, name, DATABASE_VERSION);
}
public DatabaseHelper(Context context) {
this(context, DATABASE_NAME, DATABASE_VERSION);
}
public DatabaseHelper(Context context, int version) {
this(context, DATABASE_NAME, null, version);
}
public DatabaseHelper(Context context, String name, int version) {
this(context, name, null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "Create Database.");
// Log.d(TAG, StatusTable.STATUS_TABLE_CREATE);
db.execSQL(StatusTable.CREATE_TABLE);
db.execSQL(MessageTable.CREATE_TABLE);
db.execSQL(FollowTable.CREATE_TABLE);
//2011.03.01 add beta
db.execSQL(UserInfoTable.CREATE_TABLE);
}
@Override
public synchronized void close() {
Log.d(TAG, "Close Database.");
super.close();
}
@Override
public void onOpen(SQLiteDatabase db) {
Log.d(TAG, "Open Database.");
super.onOpen(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "Upgrade Database.");
dropAllTables(db);
}
private void dropAllTables(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + StatusTable.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + MessageTable.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + FollowTable.TABLE_NAME);
//2011.03.01 add
db.execSQL("DROP TABLE IF EXISTS "+UserInfoTable.TABLE_NAME);
}
}
private TwitterDatabase(Context context) {
mContext = context;
mOpenHelper = new DatabaseHelper(context);
}
public static synchronized TwitterDatabase getInstance(Context context) {
if (null == instance) {
return new TwitterDatabase(context);
}
return instance;
}
// 测试用
public SQLiteOpenHelper getSQLiteOpenHelper() {
return mOpenHelper;
}
public static SQLiteDatabase getDb(boolean writeable) {
if (writeable) {
return mOpenHelper.getWritableDatabase();
} else {
return mOpenHelper.getReadableDatabase();
}
}
public void close() {
if (null != instance) {
mOpenHelper.close();
instance = null;
}
}
/**
* 清空所有表中数据, 谨慎使用
*
*/
public void clearData() {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
db.execSQL("DELETE FROM " + StatusTable.TABLE_NAME);
db.execSQL("DELETE FROM " + MessageTable.TABLE_NAME);
db.execSQL("DELETE FROM " + FollowTable.TABLE_NAME);
//2011.03.01 add
db.execSQL("DELETE FROM "+UserInfoTable.TABLE_NAME);
}
/**
* 直接删除数据库文件, 调试用
*
* @return true if this file was deleted, false otherwise.
* @deprecated
*/
private boolean deleteDatabase() {
File dbFile = mContext.getDatabasePath(DATABASE_NAME);
return dbFile.delete();
}
/**
* 取出某类型的一条消息
*
* @param tweetId
* @param type of status
* <li>StatusTable.TYPE_HOME</li>
* <li>StatusTable.TYPE_MENTION</li>
* <li>StatusTable.TYPE_USER</li>
* <li>StatusTable.TYPE_FAVORITE</li>
* <li>-1 means all types</li>
* @return 将Cursor转换过的Tweet对象
* @deprecated use StatusDAO#findStatus()
*/
public Tweet queryTweet(String tweetId, int type) {
SQLiteDatabase Db = mOpenHelper.getWritableDatabase();
String selection = StatusTable._ID + "=? ";
if (-1 != type) {
selection += " AND " + StatusTable.STATUS_TYPE + "=" + type;
}
Cursor cursor = Db.query(StatusTable.TABLE_NAME,
StatusTable.TABLE_COLUMNS, selection, new String[] { tweetId },
null, null, null);
Tweet tweet = null;
if (cursor != null) {
cursor.moveToFirst();
if (cursor.getCount() > 0) {
tweet = StatusTable.parseCursor(cursor);
}
}
cursor.close();
return tweet;
}
/**
* 快速检查某条消息是否存在(指定类型)
*
* @param tweetId
* @param type
* <li>StatusTable.TYPE_HOME</li>
* <li>StatusTable.TYPE_MENTION</li>
* <li>StatusTable.TYPE_USER</li>
* <li>StatusTable.TYPE_FAVORITE</li>
* @return is exists
* @deprecated use StatusDAO#isExists()
*/
public boolean isExists(String tweetId, String owner, int type) {
SQLiteDatabase Db = mOpenHelper.getWritableDatabase();
boolean result = false;
Cursor cursor = Db.query(StatusTable.TABLE_NAME,
new String[] { StatusTable._ID }, StatusTable._ID + " =? AND "
+ StatusTable.OWNER_ID + "=? AND "
+ StatusTable.STATUS_TYPE + " = " + type,
new String[] { tweetId, owner }, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
result = true;
}
cursor.close();
return result;
}
/**
* 删除一条消息
*
* @param tweetId
* @param type -1 means all types
* @return the number of rows affected if a whereClause is passed in, 0
* otherwise. To remove all rows and get a count pass "1" as the
* whereClause.
* @deprecated use {@link StatusDAO#deleteStatus(String, String, int)}
*/
public int deleteTweet(String tweetId, String owner, int type) {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
String where = StatusTable._ID + " =? ";
if (!TextUtils.isEmpty(owner)){
where += " AND " + StatusTable.OWNER_ID + " = '" + owner + "' ";
}
if (-1 != type) {
where += " AND " + StatusTable.STATUS_TYPE + " = " + type;
}
return db.delete(StatusTable.TABLE_NAME, where, new String[] { tweetId });
}
/**
* 删除超过MAX_ROW_NUM垃圾数据
*
* @param type
* <li>StatusTable.TYPE_HOME</li>
* <li>StatusTable.TYPE_MENTION</li>
* <li>StatusTable.TYPE_USER</li>
* <li>StatusTable.TYPE_FAVORITE</li>
* <li>-1 means all types</li>
*/
public void gc(String owner, int type) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
String sql = "DELETE FROM " + StatusTable.TABLE_NAME
+ " WHERE " + StatusTable._ID + " NOT IN "
+ " (SELECT " + StatusTable._ID // 子句
+ " FROM " + StatusTable.TABLE_NAME;
boolean first = true;
if (!TextUtils.isEmpty(owner)){
sql += " WHERE " + StatusTable.OWNER_ID + " = '" + owner + "' ";
first = false;
}
if (type != -1){
if (first){
sql += " WHERE ";
}else{
sql += " AND ";
}
sql += StatusTable.STATUS_TYPE + " = " + type + " ";
}
sql += " ORDER BY " + StatusTable.CREATED_AT + " DESC LIMIT "
+ StatusTable.MAX_ROW_NUM + ")";
if (!TextUtils.isEmpty(owner)){
sql += " AND " + StatusTable.OWNER_ID + " = '" + owner + "' ";
}
if (type != -1) {
sql += " AND " + StatusTable.STATUS_TYPE + " = " + type + " ";
}
Log.v(TAG, sql);
mDb.execSQL(sql);
}
public final static DateFormat DB_DATE_FORMATTER = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
private static final int CONFLICT_REPLACE = 0x00000005;
/**
* 向Status表中写入一行数据, 此方法为私有方法, 外部插入数据请使用 putTweets()
*
* @param tweet
* 需要写入的单条消息
* @return the row ID of the newly inserted row, or -1 if an error occurred
* @deprecated use {@link StatusDAO#insertStatus(Status, boolean)}
*/
public long insertTweet(Tweet tweet, String owner, int type, boolean isUnread) {
SQLiteDatabase Db = mOpenHelper.getWritableDatabase();
if (isExists(tweet.id, owner, type)) {
Log.w(TAG, tweet.id + "is exists.");
return -1;
}
ContentValues initialValues = makeTweetValues(tweet, owner, type, isUnread);
long id = Db.insert(StatusTable.TABLE_NAME, null, initialValues);
if (-1 == id) {
Log.e(TAG, "cann't insert the tweet : " + tweet.toString());
} else {
//Log.v(TAG, "Insert a status into database : " + tweet.toString());
}
return id;
}
/**
* 更新一条消息
*
* @param tweetId
* @param values
* ContentValues 需要更新字段的键值对
* @return the number of rows affected
* @deprecated use {@link StatusDAO#updateStatus(String, ContentValues)}
*/
public int updateTweet(String tweetId, ContentValues values) {
Log.v(TAG, "Update Tweet : " + tweetId + " " + values.toString());
SQLiteDatabase Db = mOpenHelper.getWritableDatabase();
return Db.update(StatusTable.TABLE_NAME, values,
StatusTable._ID + "=?", new String[] { tweetId });
}
/** @deprecated */
private ContentValues makeTweetValues(Tweet tweet, String owner, int type, boolean isUnread) {
// 插入一条新消息
ContentValues initialValues = new ContentValues();
initialValues.put(StatusTable.OWNER_ID, owner);
initialValues.put(StatusTable.STATUS_TYPE, type);
initialValues.put(StatusTable._ID, tweet.id);
initialValues.put(StatusTable.TEXT, tweet.text);
initialValues.put(StatusTable.USER_ID, tweet.userId);
initialValues.put(StatusTable.USER_SCREEN_NAME, tweet.screenName);
initialValues.put(StatusTable.PROFILE_IMAGE_URL,
tweet.profileImageUrl);
initialValues.put(StatusTable.PIC_THUMB, tweet.thumbnail_pic);
initialValues.put(StatusTable.PIC_MID, tweet.bmiddle_pic);
initialValues.put(StatusTable.PIC_ORIG, tweet.original_pic);
initialValues.put(StatusTable.FAVORITED, tweet.favorited);
initialValues.put(StatusTable.IN_REPLY_TO_STATUS_ID,
tweet.inReplyToStatusId);
initialValues.put(StatusTable.IN_REPLY_TO_USER_ID,
tweet.inReplyToUserId);
initialValues.put(StatusTable.IN_REPLY_TO_SCREEN_NAME,
tweet.inReplyToScreenName);
// initialValues.put(FIELD_IS_REPLY, tweet.isReply());
initialValues.put(StatusTable.CREATED_AT,
DB_DATE_FORMATTER.format(tweet.createdAt));
initialValues.put(StatusTable.SOURCE, tweet.source);
initialValues.put(StatusTable.IS_UNREAD, isUnread);
initialValues.put(StatusTable.TRUNCATED, tweet.truncated);
// TODO: truncated
return initialValues;
}
/**
* 写入N条消息
*
* @param tweets
* 需要写入的消息List
* @return
* 写入的记录条数
*/
public int putTweets(List<Tweet> tweets, String owner, int type, boolean isUnread) {
if (TwitterApplication.DEBUG){
DebugTimer.betweenStart("Status DB");
}
if (null == tweets || 0 == tweets.size())
{
return 0;
}
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int result = 0;
try {
db.beginTransaction();
for (int i = tweets.size() - 1; i >= 0; i--) {
Tweet tweet = tweets.get(i);
ContentValues initialValues = makeTweetValues(tweet, owner, type, isUnread);
long id = db.insert(StatusTable.TABLE_NAME, null, initialValues);
if (-1 == id) {
Log.e(TAG, "cann't insert the tweet : " + tweet.toString());
} else {
++result;
//Log.v(TAG, String.format("Insert a status into database[%s] : %s", owner, tweet.toString()));
Log.v("TAG", "Insert Status");
}
}
// gc(type); // 保持总量
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
if (TwitterApplication.DEBUG){
DebugTimer.betweenEnd("Status DB");
}
return result;
}
/**
* 取出指定用户的某一类型的所有消息
*
* @param userId
* @param tableName
* @return a cursor
* @deprecated use {@link StatusDAO#findStatuses(String, int)}
*/
public Cursor fetchAllTweets(String owner, int type) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
return mDb.query(StatusTable.TABLE_NAME, StatusTable.TABLE_COLUMNS,
StatusTable.OWNER_ID + " = ? AND " + StatusTable.STATUS_TYPE + " = " + type,
new String[]{owner}, null, null,
StatusTable.CREATED_AT + " DESC ");
//LIMIT " + StatusTable.MAX_ROW_NUM);
}
/**
* 取出自己的某一类型的所有消息
*
* @param tableName
* @return a cursor
*/
public Cursor fetchAllTweets(int type) {
// 获取登录用户id
SharedPreferences preferences = TwitterApplication.mPref;
String myself = preferences.getString(Preferences.CURRENT_USER_ID,
TwitterApplication.mApi.getUserId());
return fetchAllTweets(myself, type);
}
/**
* 清空某类型的所有信息
*
* @param tableName
* @return the number of rows affected if a whereClause is passed in, 0
* otherwise. To remove all rows and get a count pass "1" as the
* whereClause.
*/
public int dropAllTweets(int type) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
return mDb.delete(StatusTable.TABLE_NAME, StatusTable.STATUS_TYPE
+ " = " + type, null);
}
/**
* 取出本地某类型最新消息ID
*
* @param type
* @return The newest Status Id
*/
public String fetchMaxTweetId(String owner, int type) {
return fetchMaxOrMinTweetId(owner, type, true);
}
/**
* 取出本地某类型最旧消息ID
*
* @param tableName
* @return The oldest Status Id
*/
public String fetchMinTweetId(String owner, int type) {
return fetchMaxOrMinTweetId(owner, type, false);
}
private String fetchMaxOrMinTweetId(String owner, int type, boolean isMax) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
String sql = "SELECT " + StatusTable._ID + " FROM "
+ StatusTable.TABLE_NAME + " WHERE "
+ StatusTable.STATUS_TYPE + " = " + type + " AND "
+ StatusTable.OWNER_ID + " = '" + owner + "' "
+ " ORDER BY "
+ StatusTable.CREATED_AT;
if (isMax)
sql += " DESC ";
Cursor mCursor = mDb.rawQuery(sql + " LIMIT 1", null);
String result = null;
if (mCursor == null) {
return result;
}
mCursor.moveToFirst();
if (mCursor.getCount() == 0) {
result = null;
} else {
result = mCursor.getString(0);
}
mCursor.close();
return result;
}
/**
* Count unread tweet
*
* @param tableName
* @return
*/
public int fetchUnreadCount(String owner, int type) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + StatusTable._ID + ")"
+ " FROM " + StatusTable.TABLE_NAME + " WHERE "
+ StatusTable.STATUS_TYPE + " = " + type + " AND "
+ StatusTable.OWNER_ID + " = '" + owner + "' AND "
+ StatusTable.IS_UNREAD + " = 1 ",
// "LIMIT " + StatusTable.MAX_ROW_NUM,
null);
int result = 0;
if (mCursor == null) {
return result;
}
mCursor.moveToFirst();
result = mCursor.getInt(0);
mCursor.close();
return result;
}
public int addNewTweetsAndCountUnread(List<Tweet> tweets, String owner, int type) {
putTweets(tweets, owner, type, true);
return fetchUnreadCount(owner, type);
}
/**
* Set isFavorited
*
* @param tweetId
* @param isFavorited
* @return Is Succeed
* @deprecated use {@link Status#setFavorited(boolean)} and
* {@link StatusDAO#updateStatus(Status)}
*/
public boolean setFavorited(String tweetId, String isFavorited) {
ContentValues values = new ContentValues();
values.put(StatusTable.FAVORITED, isFavorited);
int i = updateTweet(tweetId, values);
return (i > 0) ? true : false;
}
// DM & Follower
/**
* 写入一条私信
*
* @param dm
* @param isUnread
* @return the row ID of the newly inserted row, or -1 if an error occurred,
* 因为主键的原因,此处返回的不是 _ID 的值, 而是一个自增长的 row_id
*/
public long createDm(Dm dm, boolean isUnread) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(MessageTable._ID, dm.id);
initialValues.put(MessageTable.FIELD_USER_SCREEN_NAME, dm.screenName);
initialValues.put(MessageTable.FIELD_TEXT, dm.text);
initialValues.put(MessageTable.FIELD_PROFILE_IMAGE_URL,
dm.profileImageUrl);
initialValues.put(MessageTable.FIELD_IS_UNREAD, isUnread);
initialValues.put(MessageTable.FIELD_IS_SENT, dm.isSent);
initialValues.put(MessageTable.FIELD_CREATED_AT,
DB_DATE_FORMATTER.format(dm.createdAt));
initialValues.put(MessageTable.FIELD_USER_ID, dm.userId);
return mDb.insert(MessageTable.TABLE_NAME, null, initialValues);
}
//
/**
* Create a follower
*
* @param userId
* @return the row ID of the newly inserted row, or -1 if an error occurred
*/
public long createFollower(String userId) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(FollowTable._ID, userId);
long rowId = mDb.insert(FollowTable.TABLE_NAME, null, initialValues);
if (-1 == rowId) {
Log.e(TAG, "Cann't create Follower : " + userId);
} else {
Log.v(TAG, "Success create follower : " + userId);
}
return rowId;
}
/**
* 清空Followers表并添加新内容
*
* @param followers
*/
public void syncFollowers(List<String> followers) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
try {
mDb.beginTransaction();
boolean result = deleteAllFollowers();
Log.v(TAG, "Result of DeleteAllFollowers: " + result);
for (String userId : followers) {
createFollower(userId);
}
mDb.setTransactionSuccessful();
} finally {
mDb.endTransaction();
}
}
/**
* @param type
* <li>MessageTable.TYPE_SENT</li>
* <li>MessageTable.TYPE_GET</li>
* <li>其他任何值都认为取出所有类型</li>
* @return
*/
public Cursor fetchAllDms(int type) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
String selection = null;
if (MessageTable.TYPE_SENT == type) {
selection = MessageTable.FIELD_IS_SENT + " = "
+ MessageTable.TYPE_SENT;
} else if (MessageTable.TYPE_GET == type) {
selection = MessageTable.FIELD_IS_SENT + " = "
+ MessageTable.TYPE_GET;
}
return mDb.query(MessageTable.TABLE_NAME, MessageTable.TABLE_COLUMNS,
selection, null, null, null, MessageTable.FIELD_CREATED_AT
+ " DESC");
}
public Cursor fetchInboxDms() {
return fetchAllDms(MessageTable.TYPE_GET);
}
public Cursor fetchSendboxDms() {
return fetchAllDms(MessageTable.TYPE_SENT);
}
public Cursor fetchAllFollowers() {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
return mDb.query(FollowTable.TABLE_NAME, FollowTable.TABLE_COLUMNS,
null, null, null, null, null);
}
/**
* FIXME:
* @param filter
* @return
*/
public Cursor getFollowerUsernames(String filter) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
String likeFilter = '%' + filter + '%';
// FIXME: 此方法的作用应该是在于在写私信时自动完成联系人的功能,
// 改造数据库后,因为本地tweets表中的数据有限, 所以几乎使得该功能没有实际价值(因为能从数据库中读到的联系人很少)
// 在完成关注者/被关注者两个界面后, 看能不能使得本地有一份
// [互相关注] 的 id/name 缓存(即getFriendsIds和getFollowersIds的交集, 因为客户端只能给他们发私信, 如果按现在
// 只提示followers的列表则很容易造成服务器返回"只能给互相关注的人发私信"的错误信息, 这会造成用户无法理解, 因为此联系人是我们提供给他们选择的,
// 并且将目前的自动完成功能的基础上加一个[选择联系人]按钮, 用于启动一个新的联系人列表页面以显示所有可发送私信的联系人对象, 类似手机写短信时的选择联系人功能
return null;
// FIXME: clean this up. 新数据库中失效, 表名, 列名
// return mDb.rawQuery(
// "SELECT user_id AS _id, user"
// + " FROM (SELECT user_id, user FROM tweets"
// + " INNER JOIN followers on tweets.user_id = followers._id UNION"
// + " SELECT user_id, user FROM dms INNER JOIN followers"
// + " on dms.user_id = followers._id)"
// + " WHERE user LIKE ?"
// + " ORDER BY user COLLATE NOCASE",
// new String[] { likeFilter });
}
/**
* @param userId
* 该用户是否follow Me
* @deprecated 未使用
* @return
*/
public boolean isFollower(String userId) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
Cursor cursor = mDb.query(FollowTable.TABLE_NAME,
FollowTable.TABLE_COLUMNS, FollowTable._ID + "= ?",
new String[] { userId }, null, null, null);
boolean result = false;
if (cursor != null && cursor.moveToFirst()) {
result = true;
}
cursor.close();
return result;
}
public boolean deleteAllFollowers() {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
return mDb.delete(FollowTable.TABLE_NAME, null, null) > 0;
}
public boolean deleteDm(String id) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
return mDb.delete(MessageTable.TABLE_NAME,
String.format("%s = '%s'", MessageTable._ID, id), null) > 0;
}
/**
* @param tableName
* @return the number of rows affected
*/
public int markAllTweetsRead(String owner, int type) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(StatusTable.IS_UNREAD, 0);
return mDb.update(StatusTable.TABLE_NAME, values,
StatusTable.STATUS_TYPE + "=" + type, null);
}
public boolean deleteAllDms() {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
return mDb.delete(MessageTable.TABLE_NAME, null, null) > 0;
}
public int markAllDmsRead() {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(MessageTable.FIELD_IS_UNREAD, 0);
return mDb.update(MessageTable.TABLE_NAME, values, null, null);
}
public String fetchMaxDmId(boolean isSent) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
Cursor mCursor = mDb.rawQuery("SELECT " + MessageTable._ID + " FROM "
+ MessageTable.TABLE_NAME + " WHERE "
+ MessageTable.FIELD_IS_SENT + " = ? " + " ORDER BY "
+ MessageTable.FIELD_CREATED_AT + " DESC LIMIT 1",
new String[] { isSent ? "1" : "0" });
String result = null;
if (mCursor == null) {
return result;
}
mCursor.moveToFirst();
if (mCursor.getCount() == 0) {
result = null;
} else {
result = mCursor.getString(0);
}
mCursor.close();
return result;
}
public int addNewDmsAndCountUnread(List<Dm> dms) {
addDms(dms, true);
return fetchUnreadDmCount();
}
public int fetchDmCount() {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + MessageTable._ID
+ ") FROM " + MessageTable.TABLE_NAME, null);
int result = 0;
if (mCursor == null) {
return result;
}
mCursor.moveToFirst();
result = mCursor.getInt(0);
mCursor.close();
return result;
}
private int fetchUnreadDmCount() {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + MessageTable._ID
+ ") FROM " + MessageTable.TABLE_NAME + " WHERE "
+ MessageTable.FIELD_IS_UNREAD + " = 1", null);
int result = 0;
if (mCursor == null) {
return result;
}
mCursor.moveToFirst();
result = mCursor.getInt(0);
mCursor.close();
return result;
}
public void addDms(List<Dm> dms, boolean isUnread) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
try {
mDb.beginTransaction();
for (Dm dm : dms) {
createDm(dm, isUnread);
}
// limitRows(TABLE_DIRECTMESSAGE, TwitterApi.RETRIEVE_LIMIT);
mDb.setTransactionSuccessful();
} finally {
mDb.endTransaction();
}
}
//2011.03.01 add
//UserInfo操作
public Cursor getAllUserInfo(){
SQLiteDatabase mDb=mOpenHelper.getReadableDatabase();
return mDb.query(UserInfoTable.TABLE_NAME,UserInfoTable.TABLE_COLUMNS, null, null, null, null, null);
}
/**
* 根据id列表获取user数据
* @param userIds
* @return
*/
public Cursor getUserInfoByIds(String[] userIds){
SQLiteDatabase mDb=mOpenHelper.getReadableDatabase();
String userIdStr="";
for(String id:userIds){
userIdStr+="'"+id+"',";
}
if(userIds.length==0){
userIdStr="'',";
}
userIdStr=userIdStr.substring(0, userIdStr.lastIndexOf(","));//删除最后的逗号
return mDb.query(UserInfoTable.TABLE_NAME, UserInfoTable.TABLE_COLUMNS, UserInfoTable._ID+" in ("+userIdStr+")", null, null, null, null);
}
/**
* 新建用户
*
* @param user
* @return the row ID of the newly inserted row, or -1 if an error occurred
*/
public long createUserInfo(com.ch_linghu.fanfoudroid.data.User user) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(UserInfoTable._ID, user.id);
initialValues.put(UserInfoTable.FIELD_USER_NAME, user.name);
initialValues.put(UserInfoTable.FIELD_USER_SCREEN_NAME, user.screenName);
initialValues.put(UserInfoTable.FIELD_LOCALTION, user.location);
initialValues.put(UserInfoTable.FIELD_DESCRIPTION, user.description);
initialValues.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, user.profileImageUrl);
initialValues.put(UserInfoTable.FIELD_URL, user.url);
initialValues.put(UserInfoTable.FIELD_PROTECTED, user.isProtected);
initialValues.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, user.followersCount);
initialValues.put(UserInfoTable.FIELD_LAST_STATUS, user.lastStatus);
initialValues.put(UserInfoTable.FIELD_FRIENDS_COUNT, user.friendsCount);
initialValues.put(UserInfoTable.FIELD_FAVORITES_COUNT, user.favoritesCount);
initialValues.put(UserInfoTable.FIELD_STATUSES_COUNT, user.statusesCount);
initialValues.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing);
//long rowId = mDb.insertWithOnConflict(UserInfoTable.TABLE_NAME, null, initialValues,SQLiteDatabase.CONFLICT_REPLACE);
long rowId = insertWithOnConflict(mDb, UserInfoTable.TABLE_NAME, null, initialValues, CONFLICT_REPLACE);
if (-1 == rowId) {
Log.e(TAG, "Cann't create user : " + user.id);
} else {
Log.v(TAG, "create create user : " + user.id);
}
return rowId;
}
//SQLiteDatabase.insertWithConflict是LEVEL 8(2.2)才引入的新方法
//为了兼容旧版,这里给出一个简化的兼容实现
//要注意的是这个实现和标准的函数行为并不完全一致
private long insertWithOnConflict(SQLiteDatabase db, String tableName,
String nullColumnHack, ContentValues initialValues, int conflictReplace) {
long rowId = db.insert(tableName, nullColumnHack, initialValues);
if(-1 == rowId){
//尝试update
rowId = db.update(tableName, initialValues,
UserInfoTable._ID+"="+initialValues.getAsString(UserInfoTable._ID), null);
}
return rowId;
}
public long createWeiboUserInfo(com.ch_linghu.fanfoudroid.fanfou.User user){
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues args = new ContentValues();
args.put(UserInfoTable._ID, user.getId());
args.put(UserInfoTable.FIELD_USER_NAME, user.getName());
args.put(UserInfoTable.FIELD_USER_SCREEN_NAME,
user.getScreenName());
String location = user.getLocation();
args.put(UserInfoTable.FIELD_LOCALTION, location);
String description = user.getDescription();
args.put(UserInfoTable.FIELD_DESCRIPTION, description);
args.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL,
user.getProfileImageURL().toString());
if (user.getURL() != null) {
args.put(UserInfoTable.FIELD_URL, user.getURL().toString());
}
args.put(UserInfoTable.FIELD_PROTECTED, user.isProtected());
args.put(UserInfoTable.FIELD_FOLLOWERS_COUNT,
user.getFollowersCount());
args.put(UserInfoTable.FIELD_LAST_STATUS, user.getStatusSource());
args.put(UserInfoTable.FIELD_FRIENDS_COUNT,
user.getFriendsCount());
args.put(UserInfoTable.FIELD_FAVORITES_COUNT,
user.getFavouritesCount());
args.put(UserInfoTable.FIELD_STATUSES_COUNT,
user.getStatusesCount());
args.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing());
//long rowId = mDb.insert(UserInfoTable.TABLE_NAME, null, args);
//省去判断existUser,如果存在数据则replace
//long rowId=mDb.insertWithOnConflict(UserInfoTable.TABLE_NAME, null, args, SQLiteDatabase.CONFLICT_REPLACE);
long rowId=insertWithOnConflict(mDb, UserInfoTable.TABLE_NAME, null, args, CONFLICT_REPLACE);
if (-1 == rowId) {
Log.e(TAG, "Cann't createWeiboUserInfo : " + user.getId());
} else {
Log.v(TAG, "create createWeiboUserInfo : " + user.getId());
}
return rowId;
}
/**
* 查看数据是否已保存用户数据
* @param userId
* @return
*/
public boolean existsUser(String userId) {
SQLiteDatabase Db = mOpenHelper.getReadableDatabase();
boolean result = false;
Cursor cursor = Db.query(UserInfoTable.TABLE_NAME,
new String[] { UserInfoTable._ID }, UserInfoTable._ID +"='"+userId+"'",
null, null, null, null);
Log.v("testesetesteste", String.valueOf(cursor.getCount()));
if (cursor != null && cursor.getCount() > 0) {
result = true;
}
cursor.close();
return result;
}
/**
* 根据userid提取信息
* @param userId
* @return
*/
public Cursor getUserInfoById(String userId){
SQLiteDatabase Db = mOpenHelper.getReadableDatabase();
Cursor cursor = Db.query(UserInfoTable.TABLE_NAME,
UserInfoTable.TABLE_COLUMNS, UserInfoTable._ID + " = '" +userId+"'",
null, null, null, null);
return cursor;
}
/**
* 更新用户
* @param uid
* @param args
* @return
*/
public boolean updateUser(String uid,ContentValues args){
SQLiteDatabase Db=mOpenHelper.getWritableDatabase();
return Db.update(UserInfoTable.TABLE_NAME, args, UserInfoTable._ID+"='"+uid+"'", null)>0;
}
/**
* 更新用户信息
*/
public boolean updateUser(com.ch_linghu.fanfoudroid.data.User user){
SQLiteDatabase Db=mOpenHelper.getWritableDatabase();
ContentValues args=new ContentValues();
args.put(UserInfoTable._ID, user.id);
args.put(UserInfoTable.FIELD_USER_NAME, user.name);
args.put(UserInfoTable.FIELD_USER_SCREEN_NAME, user.screenName);
args.put(UserInfoTable.FIELD_LOCALTION, user.location);
args.put(UserInfoTable.FIELD_DESCRIPTION, user.description);
args.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, user.profileImageUrl);
args.put(UserInfoTable.FIELD_URL, user.url);
args.put(UserInfoTable.FIELD_PROTECTED, user.isProtected);
args.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, user.followersCount);
args.put(UserInfoTable.FIELD_LAST_STATUS, user.lastStatus);
args.put(UserInfoTable.FIELD_FRIENDS_COUNT, user.friendsCount);
args.put(UserInfoTable.FIELD_FAVORITES_COUNT, user.favoritesCount);
args.put(UserInfoTable.FIELD_STATUSES_COUNT, user.statusesCount);
args.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing);
return Db.update(UserInfoTable.TABLE_NAME, args, UserInfoTable._ID+"='"+user.id+"'", null)>0;
}
/**
* 减少转换的开销
* @param user
* @return
*/
public boolean updateWeiboUser(com.ch_linghu.fanfoudroid.fanfou.User user){
SQLiteDatabase Db=mOpenHelper.getWritableDatabase();
ContentValues args = new ContentValues();
args.put(UserInfoTable._ID, user.getName());
args.put(UserInfoTable.FIELD_USER_NAME, user.getName());
args.put(UserInfoTable.FIELD_USER_SCREEN_NAME,
user.getScreenName());
String location = user.getLocation();
args.put(UserInfoTable.FIELD_LOCALTION, location);
String description = user.getDescription();
args.put(UserInfoTable.FIELD_DESCRIPTION, description);
args.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL,
user.getProfileImageURL().toString());
if (user.getURL() != null) {
args.put(UserInfoTable.FIELD_URL, user.getURL().toString());
}
args.put(UserInfoTable.FIELD_PROTECTED, user.isProtected());
args.put(UserInfoTable.FIELD_FOLLOWERS_COUNT,
user.getFollowersCount());
args.put(UserInfoTable.FIELD_LAST_STATUS, user.getStatusSource());
args.put(UserInfoTable.FIELD_FRIENDS_COUNT,
user.getFriendsCount());
args.put(UserInfoTable.FIELD_FAVORITES_COUNT,
user.getFavouritesCount());
args.put(UserInfoTable.FIELD_STATUSES_COUNT,
user.getStatusesCount());
args.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing());
return Db.update(UserInfoTable.TABLE_NAME, args, UserInfoTable._ID+"='"+user.getId()+"'", null)>0;
}
/**
* 同步用户,更新已存在的用户,插入未存在的用户
*/
public void syncUsers(List<com.ch_linghu.fanfoudroid.data.User> users){
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
try{
mDb.beginTransaction();
for(com.ch_linghu.fanfoudroid.data.User u:users){
// if(existsUser(u.id)){
// updateUser(u);
// }else{
// createUserInfo(u);
// }
createUserInfo(u);
}
mDb.setTransactionSuccessful();
} finally {
mDb.endTransaction();
}
}
public void syncWeiboUsers(List<com.ch_linghu.fanfoudroid.fanfou.User> users) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
try {
mDb.beginTransaction();
for (com.ch_linghu.fanfoudroid.fanfou.User u : users) {
// if (existsUser(u.getId())) {
// updateWeiboUser(u);
// } else {
// createWeiboUserInfo(u);
// }
createWeiboUserInfo(u);
}
mDb.setTransactionSuccessful();
} finally {
mDb.endTransaction();
}
}
}
| Java |
package com.ch_linghu.fanfoudroid.db;
import java.text.ParseException;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.util.Log;
import com.ch_linghu.fanfoudroid.data.Dm;
/**
* Table - Direct Messages
*
*/
public final class MessageTable implements BaseColumns {
public static final String TAG = "MessageTable";
public static final int TYPE_GET = 0;
public static final int TYPE_SENT = 1;
public static final String TABLE_NAME = "message";
public static final int MAX_ROW_NUM = 20;
public static final String FIELD_USER_ID = "uid";
public static final String FIELD_USER_SCREEN_NAME = "screen_name";
public static final String FIELD_PROFILE_IMAGE_URL = "profile_image_url";
public static final String FIELD_CREATED_AT = "created_at";
public static final String FIELD_TEXT = "text";
public static final String FIELD_IN_REPLY_TO_STATUS_ID = "in_reply_to_status_id";
public static final String FIELD_IN_REPLY_TO_USER_ID = "in_reply_to_user_id";
public static final String FIELD_IN_REPLY_TO_SCREEN_NAME = "in_reply_to_screen_name";
public static final String FIELD_IS_UNREAD = "is_unread";
public static final String FIELD_IS_SENT = "is_send";
public static final String[] TABLE_COLUMNS = new String[] { _ID,
FIELD_USER_SCREEN_NAME, FIELD_TEXT, FIELD_PROFILE_IMAGE_URL,
FIELD_IS_UNREAD, FIELD_IS_SENT, FIELD_CREATED_AT, FIELD_USER_ID };
public static final String CREATE_TABLE = "CREATE TABLE "
+ TABLE_NAME + " ("
+ _ID + " text primary key on conflict replace, "
+ FIELD_USER_SCREEN_NAME + " text not null, "
+ FIELD_TEXT + " text not null, "
+ FIELD_PROFILE_IMAGE_URL + " text not null, "
+ FIELD_IS_UNREAD + " boolean not null, "
+ FIELD_IS_SENT + " boolean not null, "
+ FIELD_CREATED_AT + " date not null, "
+ FIELD_USER_ID + " text)";
/**
* TODO: 将游标解析为一条私信
*
* @param cursor 该方法不会关闭游标
* @return 成功返回Dm类型的单条数据, 失败返回null
*/
public static Dm parseCursor(Cursor cursor) {
if (null == cursor || 0 == cursor.getCount()) {
Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty.");
return null;
}
Dm dm = new Dm();
dm.id = cursor.getString(cursor.getColumnIndex(MessageTable._ID));
dm.screenName = cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_USER_SCREEN_NAME));
dm.text = cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_TEXT));
dm.profileImageUrl = cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_PROFILE_IMAGE_URL));
dm.isSent = (0 == cursor.getInt(cursor.getColumnIndex(MessageTable.FIELD_IS_SENT))) ? false : true ;
try {
dm.createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_CREATED_AT)));
} catch (ParseException e) {
Log.w(TAG, "Invalid created at data.");
}
dm.userId = cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_USER_ID));
return dm;
}
} | Java |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.fanfou.User;
import com.ch_linghu.fanfoudroid.http.HttpAuthException;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskFeedback;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
//登录页面需要个性化的菜单绑定, 不直接继承 BaseActivity
public class LoginActivity extends Activity {
private static final String TAG = "LoginActivity";
private static final String SIS_RUNNING_KEY = "running";
private String mUsername;
private String mPassword;
// Views.
private EditText mUsernameEdit;
private EditText mPasswordEdit;
private TextView mProgressText;
private Button mSigninButton;
private ProgressDialog dialog;
// Preferences.
private SharedPreferences mPreferences;
// Tasks.
private GenericTask mLoginTask;
private User user;
private TaskListener mLoginTaskListener = new TaskAdapter(){
@Override
public void onPreExecute(GenericTask task) {
onLoginBegin();
}
@Override
public void onProgressUpdate(GenericTask task, Object param) {
updateProgress((String)param);
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
onLoginSuccess();
} else {
onLoginFailure(((LoginTask)task).getMsg());
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return "Login";
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);
// No Title bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
requestWindowFeature(Window.FEATURE_PROGRESS);
mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
setContentView(R.layout.login);
// TextView中嵌入HTML链接
TextView registerLink = (TextView) findViewById(R.id.register_link);
registerLink.setMovementMethod(LinkMovementMethod.getInstance());
mUsernameEdit = (EditText) findViewById(R.id.username_edit);
mPasswordEdit = (EditText) findViewById(R.id.password_edit);
// mUsernameEdit.setOnKeyListener(enterKeyHandler);
mPasswordEdit.setOnKeyListener(enterKeyHandler);
mProgressText = (TextView) findViewById(R.id.progress_text);
mProgressText.setFreezesText(true);
mSigninButton = (Button) findViewById(R.id.signin_button);
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(SIS_RUNNING_KEY)) {
if (savedInstanceState.getBoolean(SIS_RUNNING_KEY)) {
Log.d(TAG, "Was previously logging in. Restart action.");
doLogin();
}
}
}
mSigninButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
doLogin();
}
});
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestory");
if (mLoginTask != null && mLoginTask.getStatus() == GenericTask.Status.RUNNING) {
mLoginTask.cancel(true);
}
// dismiss dialog before destroy
// to avoid android.view.WindowLeaked Exception
TaskFeedback.getInstance(TaskFeedback.DIALOG_MODE,
LoginActivity.this).cancel();
super.onDestroy();
}
@Override
protected void onStop() {
Log.d(TAG, "onStop");
// TODO Auto-generated method stub
super.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mLoginTask != null
&& mLoginTask.getStatus() == GenericTask.Status.RUNNING) {
// If the task was running, want to start it anew when the
// Activity restarts.
// This addresses the case where you user changes orientation
// in the middle of execution.
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
// UI helpers.
private void updateProgress(String progress) {
mProgressText.setText(progress);
}
private void enableLogin() {
mUsernameEdit.setEnabled(true);
mPasswordEdit.setEnabled(true);
mSigninButton.setEnabled(true);
}
private void disableLogin() {
mUsernameEdit.setEnabled(false);
mPasswordEdit.setEnabled(false);
mSigninButton.setEnabled(false);
}
// Login task.
private void doLogin() {
mUsername = mUsernameEdit.getText().toString();
mPassword = mPasswordEdit.getText().toString();
if (mLoginTask != null && mLoginTask.getStatus() == GenericTask.Status.RUNNING){
return;
}else{
if (!TextUtils.isEmpty(mUsername) & !TextUtils.isEmpty(mPassword) ) {
mLoginTask = new LoginTask();
mLoginTask.setListener(mLoginTaskListener);
TaskParams params = new TaskParams();
params.put("username", mUsername);
params.put("password", mPassword);
mLoginTask.execute(params);
} else {
updateProgress(getString(R.string.login_status_null_username_or_password));
}
}
}
private void onLoginBegin() {
disableLogin();
TaskFeedback.getInstance(TaskFeedback.DIALOG_MODE,
LoginActivity.this).start(
getString(R.string.login_status_logging_in));
}
private void onLoginSuccess() {
TaskFeedback.getInstance(TaskFeedback.DIALOG_MODE,
LoginActivity.this).success("");
updateProgress("");
mUsernameEdit.setText("");
mPasswordEdit.setText("");
Log.d(TAG, "Storing credentials.");
TwitterApplication.mApi.setCredentials(mUsername, mPassword);
Intent intent = getIntent().getParcelableExtra(Intent.EXTRA_INTENT);
String action = intent.getAction();
if (intent.getAction() == null || !Intent.ACTION_SEND.equals(action)) {
// We only want to reuse the intent if it was photo send.
// Or else default to the main activity.
intent = new Intent(this, TwitterActivity.class);
}
//发送消息给widget
Intent reflogin = new Intent(this.getBaseContext(), FanfouWidget.class);
reflogin.setAction("android.appwidget.action.APPWIDGET_UPDATE");
PendingIntent l = PendingIntent.getBroadcast(this.getBaseContext(), 0, reflogin,
PendingIntent.FLAG_UPDATE_CURRENT);
try {
l.send();
} catch (CanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startActivity(intent);
finish();
}
private void onLoginFailure(String reason) {
TaskFeedback.getInstance(TaskFeedback.DIALOG_MODE,
LoginActivity.this).failed(reason);
enableLogin();
}
private class LoginTask extends GenericTask {
private String msg = getString(R.string.login_status_failure);
public String getMsg(){
return msg;
}
@Override
protected TaskResult _doInBackground(TaskParams...params) {
TaskParams param = params[0];
publishProgress(getString(R.string.login_status_logging_in) + "...");
try {
String username = param.getString("username");
String password = param.getString("password");
user= TwitterApplication.mApi.login(username, password);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
//TODO:确切的应该从HttpException中返回的消息中获取错误信息
//Throwable cause = e.getCause(); // Maybe null
// if (cause instanceof HttpAuthException) {
if (e instanceof HttpAuthException) {
// Invalid userName/password
msg = getString(R.string.login_status_invalid_username_or_password);
} else {
msg = getString(R.string.login_status_network_or_connection_error);
}
publishProgress(msg);
return TaskResult.FAILED;
}
SharedPreferences.Editor editor = mPreferences.edit();
editor.putString(Preferences.USERNAME_KEY, mUsername);
editor.putString(Preferences.PASSWORD_KEY,
encryptPassword(mPassword));
// add 存储当前用户的id
editor.putString(Preferences.CURRENT_USER_ID, user.getId());
editor.commit();
return TaskResult.OK;
}
}
private View.OnKeyListener enterKeyHandler = new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER
|| keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
if (event.getAction() == KeyEvent.ACTION_UP) {
doLogin();
}
return true;
}
return false;
}
};
public static String encryptPassword(String password) {
//return Base64.encodeToString(password.getBytes(), Base64.DEFAULT);
return password;
}
public static String decryptPassword(String password) {
//return new String(Base64.decode(password, Base64.DEFAULT));
return password;
}
} | Java |
package com.ch_linghu.fanfoudroid.task;
import java.util.Observable;
import java.util.Observer;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
public abstract class GenericTask extends
AsyncTask<TaskParams, Object, TaskResult> implements Observer {
private static final String TAG = "TaskManager";
private TaskListener mListener = null;
private Feedback mFeedback = null;
private boolean isCancelable = true;
abstract protected TaskResult _doInBackground(TaskParams... params);
public void setListener(TaskListener taskListener) {
mListener = taskListener;
}
public TaskListener getListener() {
return mListener;
}
public void doPublishProgress(Object... values) {
super.publishProgress(values);
}
@Override
protected void onCancelled() {
super.onCancelled();
if (mListener != null) {
mListener.onCancelled(this);
}
Log.d(TAG, mListener.getName() + " has been Cancelled.");
Toast.makeText(TwitterApplication.mContext, mListener.getName()
+ " has been cancelled", Toast.LENGTH_SHORT);
}
@Override
protected void onPostExecute(TaskResult result) {
super.onPostExecute(result);
if (mListener != null) {
mListener.onPostExecute(this, result);
}
if (mFeedback != null) {
mFeedback.success("");
}
/*
Toast.makeText(TwitterApplication.mContext, mListener.getName()
+ " completed", Toast.LENGTH_SHORT);
*/
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if (mListener != null) {
mListener.onPreExecute(this);
}
if (mFeedback != null) {
mFeedback.start("");
}
}
@Override
protected void onProgressUpdate(Object... values) {
super.onProgressUpdate(values);
if (mListener != null) {
if (values != null && values.length > 0) {
mListener.onProgressUpdate(this, values[0]);
}
}
if (mFeedback != null) {
mFeedback.update(values[0]);
}
}
@Override
protected TaskResult doInBackground(TaskParams... params) {
TaskResult result = _doInBackground(params);
if (mFeedback != null) {
mFeedback.update(99);
}
return result;
}
public void update(Observable o, Object arg) {
if (TaskManager.CANCEL_ALL == (Integer) arg && isCancelable) {
if (getStatus() == GenericTask.Status.RUNNING) {
cancel(true);
}
}
}
public void setCancelable(boolean flag) {
isCancelable = flag;
}
public void setFeedback(Feedback feedback) {
mFeedback = feedback;
}
}
| Java |
package com.ch_linghu.fanfoudroid.task;
import java.util.HashMap;
import org.json.JSONException;
import com.ch_linghu.fanfoudroid.http.HttpException;
/**
* 暂未使用,待观察是否今后需要此类
* @author lds
*
*/
public class TaskParams {
private HashMap<String, Object> params = null;
public TaskParams() {
params = new HashMap<String, Object>();
}
public TaskParams(String key, Object value) {
this();
put(key, value);
}
public void put(String key, Object value) {
params.put(key, value);
}
public Object get(String key) {
return params.get(key);
}
/**
* Get the boolean value associated with a key.
*
* @param key A key string.
* @return The truth.
* @throws HttpException
* if the value is not a Boolean or the String "true" or "false".
*/
public boolean getBoolean(String key) throws HttpException {
Object object = get(key);
if (object.equals(Boolean.FALSE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("true"))) {
return true;
}
throw new HttpException(key + " is not a Boolean.");
}
/**
* Get the double value associated with a key.
* @param key A key string.
* @return The numeric value.
* @throws HttpException if the key is not found or
* if the value is not a Number object and cannot be converted to a number.
*/
public double getDouble(String key) throws HttpException {
Object object = get(key);
try {
return object instanceof Number ?
((Number)object).doubleValue() :
Double.parseDouble((String)object);
} catch (Exception e) {
throw new HttpException(key + " is not a number.");
}
}
/**
* Get the int value associated with a key.
*
* @param key A key string.
* @return The integer value.
* @throws HttpException if the key is not found or if the value cannot
* be converted to an integer.
*/
public int getInt(String key) throws HttpException {
Object object = get(key);
try {
return object instanceof Number ?
((Number)object).intValue() :
Integer.parseInt((String)object);
} catch (Exception e) {
throw new HttpException(key + " is not an int.");
}
}
/**
* Get the string associated with a key.
*
* @param key A key string.
* @return A string which is the value.
* @throws JSONException if the key is not found.
*/
public String getString(String key) throws HttpException {
Object object = get(key);
return object == null ? null : object.toString();
}
/**
* Determine if the JSONObject contains a specific key.
* @param key A key string.
* @return true if the key exists in the JSONObject.
*/
public boolean has(String key) {
return this.params.containsKey(key);
}
}
| Java |
package com.ch_linghu.fanfoudroid.task;
import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.ui.base.WithHeaderActivity;
public abstract class TaskFeedback {
private static TaskFeedback _instance = null;
public static final int DIALOG_MODE = 0x01;
public static final int REFRESH_MODE = 0x02;
public static final int PROGRESS_MODE = 0x03;
public static TaskFeedback getInstance(int type, Context context) {
switch (type) {
case DIALOG_MODE:
_instance = DialogFeedback.getInstance();
break;
case REFRESH_MODE:
_instance = RefreshAnimationFeedback.getInstance();
break;
case PROGRESS_MODE:
_instance = ProgressBarFeedback.getInstance();
}
_instance.setContext(context);
return _instance;
}
protected Context _context;
protected void setContext(Context context) {
_context = context;
}
public Context getContent() {
return _context;
}
// default do nothing
public void start(String prompt) {};
public void cancel() {};
public void success(String prompt) {};
public void success() { success(""); };
public void failed(String prompt) {};
public void showProgress(int progress) {};
}
/**
*
*/
class DialogFeedback extends TaskFeedback {
private static DialogFeedback _instance = null;
public static DialogFeedback getInstance() {
if (_instance == null) {
_instance = new DialogFeedback();
}
return _instance;
}
private ProgressDialog _dialog = null;
@Override
public void cancel() {
if (_dialog != null) {
_dialog.dismiss();
}
}
@Override
public void failed(String prompt) {
if (_dialog != null) {
_dialog.dismiss();
}
Toast toast = Toast.makeText(_context, prompt, Toast.LENGTH_LONG);
toast.show();
}
@Override
public void start(String prompt) {
_dialog = ProgressDialog.show(_context, "", prompt, true);
_dialog.setCancelable(true);
}
@Override
public void success(String prompt) {
if (_dialog != null) {
_dialog.dismiss();
}
}
}
/**
*
*/
class RefreshAnimationFeedback extends TaskFeedback {
private static RefreshAnimationFeedback _instance = null;
public static RefreshAnimationFeedback getInstance() {
if (_instance == null) {
_instance = new RefreshAnimationFeedback();
}
return _instance;
}
private WithHeaderActivity _activity;
@Override
protected void setContext(Context context) {
super.setContext(context);
_activity = (WithHeaderActivity) context;
}
@Override
public void cancel() {
_activity.setRefreshAnimation(false);
}
@Override
public void failed(String prompt) {
_activity.setRefreshAnimation(false);
Toast toast = Toast.makeText(_context, prompt, Toast.LENGTH_LONG);
toast.show();
}
@Override
public void start(String prompt) {
_activity.setRefreshAnimation(true);
}
@Override
public void success(String prompt) {
_activity.setRefreshAnimation(false);
}
}
/**
*
*/
class ProgressBarFeedback extends TaskFeedback {
private static ProgressBarFeedback _instance = null;
public static ProgressBarFeedback getInstance() {
if (_instance == null) {
_instance = new ProgressBarFeedback();
}
return _instance;
}
private WithHeaderActivity _activity;
@Override
protected void setContext(Context context) {
super.setContext(context);
_activity = (WithHeaderActivity) context;
}
@Override
public void cancel() {
_activity.setGlobalProgress(0);
}
@Override
public void failed(String prompt) {
cancel();
Toast toast = Toast.makeText(_context, prompt, Toast.LENGTH_LONG);
toast.show();
}
@Override
public void start(String prompt) {
_activity.setGlobalProgress(10);
}
@Override
public void success(String prompt) {
Log.d("LDS", "ON SUCCESS");
_activity.setGlobalProgress(0);
}
@Override
public void showProgress(int progress) {
_activity.setGlobalProgress(progress);
}
// mProgress.setIndeterminate(true);
}
| Java |
package com.ch_linghu.fanfoudroid.task;
public enum TaskResult {
OK,
FAILED,
CANCELLED,
NOT_FOLLOWED_ERROR,
IO_ERROR,
AUTH_ERROR
} | Java |
package com.ch_linghu.fanfoudroid.task;
public interface TaskListener {
String getName();
void onPreExecute(GenericTask task);
void onPostExecute(GenericTask task, TaskResult result);
void onProgressUpdate(GenericTask task, Object param);
void onCancelled(GenericTask task);
}
| Java |
package com.ch_linghu.fanfoudroid.task;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
public class TweetCommonTask {
public static class DeleteTask extends GenericTask{
public static final String TAG="DeleteTask";
private BaseActivity activity;
public DeleteTask(BaseActivity activity){
this.activity = activity;
}
@Override
protected TaskResult _doInBackground(TaskParams... params) {
TaskParams param = params[0];
try {
String id = param.getString("id");
com.ch_linghu.fanfoudroid.fanfou.Status status = null;
status = activity.getApi().destroyStatus(id);
// 对所有相关表的对应消息都进行删除(如果存在的话)
activity.getDb().deleteTweet(status.getId(), "", -1);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
public static class FavoriteTask extends GenericTask{
private static final String TAG = "FavoriteTask";
private BaseActivity activity;
public static final String TYPE_ADD = "add";
public static final String TYPE_DEL = "del";
private String type;
public String getType(){
return type;
}
public FavoriteTask(BaseActivity activity){
this.activity = activity;
}
@Override
protected TaskResult _doInBackground(TaskParams...params){
TaskParams param = params[0];
try {
String action = param.getString("action");
String id = param.getString("id");
com.ch_linghu.fanfoudroid.fanfou.Status status = null;
if (action.equals(TYPE_ADD)) {
status = activity.getApi().createFavorite(id);
activity.getDb().setFavorited(id, "true");
type = TYPE_ADD;
} else {
status = activity.getApi().destroyFavorite(id);
activity.getDb().setFavorited(id, "false");
type = TYPE_DEL;
}
Tweet tweet = Tweet.create(status);
// if (!Utils.isEmpty(tweet.profileImageUrl)) {
// // Fetch image to cache.
// try {
// activity.getImageManager().put(tweet.profileImageUrl);
// } catch (IOException e) {
// Log.e(TAG, e.getMessage(), e);
// }
// }
if(action.equals(TYPE_DEL)){
activity.getDb().deleteTweet(tweet.id, TwitterApplication.getMyselfId(), StatusTable.TYPE_FAVORITE);
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
// public static class UserTask extends GenericTask{
//
// @Override
// protected TaskResult _doInBackground(TaskParams... params) {
// // TODO Auto-generated method stub
// return null;
// }
//
// }
}
| Java |
package com.ch_linghu.fanfoudroid.task;
public abstract class TaskAdapter implements TaskListener {
public abstract String getName();
public void onPreExecute(GenericTask task) {};
public void onPostExecute(GenericTask task, TaskResult result) {};
public void onProgressUpdate(GenericTask task, Object param) {};
public void onCancelled(GenericTask task) {};
}
| Java |
package com.ch_linghu.fanfoudroid.task;
import java.util.Observable;
import java.util.Observer;
import android.util.Log;
public class TaskManager extends Observable {
private static final String TAG = "TaskManager";
public static final Integer CANCEL_ALL = 1;
public void cancelAll() {
Log.d(TAG, "All task Cancelled.");
setChanged();
notifyObservers(CANCEL_ALL);
}
public void addTask(Observer task) {
super.addObserver(task);
}
} | Java |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity;
public class MentionActivity extends TwitterCursorBaseActivity {
private static final String TAG = "MentionActivity";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.REPLIES";
static final int DIALOG_WRITE_ID = 0;
public static Intent createIntent(Context context) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
return intent;
}
public static Intent createNewTaskIntent(Context context) {
Intent intent = createIntent(context);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState)){
mNavbar.setHeaderTitle("@提到我的");
return true;
}else{
return false;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
@Override
protected Cursor fetchMessages() {
return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_MENTION);
}
@Override
protected void markAllRead() {
getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_MENTION);
}
@Override
protected String getActivityTitle() {
return getResources().getString(R.string.page_title_mentions);
}
// for Retrievable interface
@Override
public String fetchMaxId() {
return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_MENTION);
}
@Override
public List<Status> getMessageSinceId(String maxId) throws HttpException {
if (maxId != null){
return getApi().getMentions(new Paging(maxId));
}else{
return getApi().getMentions();
}
}
@Override
public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) {
return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_MENTION, isUnread);
}
@Override
public String fetchMinId() {
return getDb().fetchMinTweetId(getUserId(), StatusTable.TYPE_MENTION);
}
@Override
public List<Status> getMoreMessageFromId(String minId)
throws HttpException {
Paging paging = new Paging(1, 20);
paging.setMaxId(minId);
return getApi().getMentions(paging);
}
@Override
public int getDatabaseType() {
return StatusTable.TYPE_MENTION;
}
@Override
public String getUserId() {
return TwitterApplication.getMyselfId();
}
} | Java |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.task.TweetCommonTask;
import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity;
public class TwitterActivity extends TwitterCursorBaseActivity {
private static final String TAG = "TwitterActivity";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.TWEETS";
protected GenericTask mDeleteTask;
private TaskListener mDeleteTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "DeleteTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
onDeleteSuccess();
} else if (result == TaskResult.IO_ERROR) {
onDeleteFailure();
}
}
};
static final int DIALOG_WRITE_ID = 0;
public static Intent createIntent(Context context) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
return intent;
}
public static Intent createNewTaskIntent(Context context) {
Intent intent = createIntent(context);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState)) {
mNavbar.setHeaderTitle("饭否fanfou.com");
//仅在这个页面进行schedule的处理
manageUpdateChecks();
return true;
} else {
return false;
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (mDeleteTask != null
&& mDeleteTask.getStatus() == GenericTask.Status.RUNNING) {
mDeleteTask.cancel(true);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mDeleteTask != null
&& mDeleteTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
// Menu.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
private int CONTEXT_DELETE_ID = getLastContextMenuId() + 1;
@Override
protected int getLastContextMenuId() {
return CONTEXT_DELETE_ID;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
Tweet tweet = getContextItemTweet(info.position);
if (null != tweet) {// 当按钮为 刷新/更多的时候为空
if (tweet.userId.equals(TwitterApplication.getMyselfId())) {
menu.add(0, CONTEXT_DELETE_ID, 0, R.string.cmenu_delete);
}
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
Tweet tweet = getContextItemTweet(info.position);
if (tweet == null) {
Log.w(TAG, "Selected item not available.");
return super.onContextItemSelected(item);
}
if (item.getItemId() == CONTEXT_DELETE_ID) {
doDelete(tweet.id);
return true;
} else {
return super.onContextItemSelected(item);
}
}
@SuppressWarnings("deprecation")
@Override
protected Cursor fetchMessages() {
return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_HOME);
}
@Override
protected String getActivityTitle() {
return getResources().getString(R.string.page_title_home);
}
@Override
protected void markAllRead() {
getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_HOME);
}
// hasRetrieveListTask interface
@Override
public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) {
// 获取消息的时候,将status里获取的user也存储到数据库
// ::MARK::
for (Tweet t : tweets) {
getDb().createWeiboUserInfo(t.user);
}
return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_HOME,
isUnread);
}
@Override
public String fetchMaxId() {
return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_HOME);
}
@Override
public List<Status> getMessageSinceId(String maxId) throws HttpException {
if (maxId != null) {
return getApi().getFriendsTimeline(new Paging(maxId));
} else {
return getApi().getFriendsTimeline();
}
}
public void onDeleteFailure() {
Log.e(TAG, "Delete failed");
}
public void onDeleteSuccess() {
mTweetAdapter.refresh();
}
private void doDelete(String id) {
if (mDeleteTask != null
&& mDeleteTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mDeleteTask = new TweetCommonTask.DeleteTask(this);
mDeleteTask.setListener(mDeleteTaskListener);
TaskParams params = new TaskParams();
params.put("id", id);
mDeleteTask.execute(params);
}
}
@Override
public String fetchMinId() {
return getDb().fetchMinTweetId(getUserId(), StatusTable.TYPE_HOME);
}
@Override
public List<Status> getMoreMessageFromId(String minId) throws HttpException {
Paging paging = new Paging(1, 20);
paging.setMaxId(minId);
return getApi().getFriendsTimeline(paging);
}
@Override
public int getDatabaseType() {
return StatusTable.TYPE_HOME;
}
@Override
public String getUserId() {
return TwitterApplication.getMyselfId();
}
} | Java |
package com.ch_linghu.fanfoudroid.data2;
import java.util.Date;
public class Status {
private Date created_at;
private String id;
private String text;
private String source;
private boolean truncated;
private String in_reply_to_status_id;
private String in_reply_to_user_id;
private boolean favorited;
private String in_reply_to_screen_name;
private Photo photo_url;
private User user;
private boolean isUnRead = false;
private int type = -1;
private String owner_id;
public Status() {}
public Date getCreatedAt() {
return created_at;
}
public void setCreatedAt(Date created_at) {
this.created_at = created_at;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public boolean isTruncated() {
return truncated;
}
public void setTruncated(boolean truncated) {
this.truncated = truncated;
}
public String getInReplyToStatusId() {
return in_reply_to_status_id;
}
public void setInReplyToStatusId(String in_reply_to_status_id) {
this.in_reply_to_status_id = in_reply_to_status_id;
}
public String getInReplyToUserId() {
return in_reply_to_user_id;
}
public void setInReplyToUserId(String in_reply_to_user_id) {
this.in_reply_to_user_id = in_reply_to_user_id;
}
public boolean isFavorited() {
return favorited;
}
public void setFavorited(boolean favorited) {
this.favorited = favorited;
}
public String getInReplyToScreenName() {
return in_reply_to_screen_name;
}
public void setInReplyToScreenName(String in_reply_to_screen_name) {
this.in_reply_to_screen_name = in_reply_to_screen_name;
}
public Photo getPhotoUrl() {
return photo_url;
}
public void setPhotoUrl(Photo photo_url) {
this.photo_url = photo_url;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public boolean isUnRead() {
return isUnRead;
}
public void setUnRead(boolean isUnRead) {
this.isUnRead = isUnRead;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getOwnerId() {
return owner_id;
}
public void setOwnerId(String owner_id) {
this.owner_id = owner_id;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Status other = (Status) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (owner_id == null) {
if (other.owner_id != null)
return false;
} else if (!owner_id.equals(other.owner_id))
return false;
if (type != other.type)
return false;
if (user == null) {
if (other.user != null)
return false;
} else if (!user.equals(other.user))
return false;
return true;
}
@Override
public String toString() {
return "Status [created_at=" + created_at + ", id=" + id + ", text="
+ text + ", source=" + source + ", truncated=" + truncated
+ ", in_reply_to_status_id=" + in_reply_to_status_id
+ ", in_reply_to_user_id=" + in_reply_to_user_id
+ ", favorited=" + favorited + ", in_reply_to_screen_name="
+ in_reply_to_screen_name + ", photo_url=" + photo_url
+ ", user=" + user + "]";
}
}
| Java |
package com.ch_linghu.fanfoudroid.data2;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class DataUtils {
static SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
public static Date parseDate(String str, String format) throws ParseException {
if (str == null || "".equals(str)) {
return null;
}
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
return sdf.parse(str);
}
}
| Java |
package com.ch_linghu.fanfoudroid.data2;
import java.util.Date;
public class User {
private String id;
private String name;
private String screen_name;
private String location;
private String desription;
private String profile_image_url;
private String url;
private boolean isProtected;
private int friends_count;
private int followers_count;
private int favourites_count;
private Date created_at;
private boolean following;
private boolean notifications;
private int utc_offset;
private Status status; // null
public User() {}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getScreenName() {
return screen_name;
}
public void setScreenName(String screen_name) {
this.screen_name = screen_name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDesription() {
return desription;
}
public void setDesription(String desription) {
this.desription = desription;
}
public String getProfileImageUrl() {
return profile_image_url;
}
public void setProfileImageUrl(String profile_image_url) {
this.profile_image_url = profile_image_url;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public boolean isProtected() {
return isProtected;
}
public void setProtected(boolean isProtected) {
this.isProtected = isProtected;
}
public int getFriendsCount() {
return friends_count;
}
public void setFriendsCount(int friends_count) {
this.friends_count = friends_count;
}
public int getFollowersCount() {
return followers_count;
}
public void setFollowersCount(int followers_count) {
this.followers_count = followers_count;
}
public int getFavouritesCount() {
return favourites_count;
}
public void setFavouritesCount(int favourites_count) {
this.favourites_count = favourites_count;
}
public Date getCreatedAt() {
return created_at;
}
public void setCreatedAt(Date created_at) {
this.created_at = created_at;
}
public boolean isFollowing() {
return following;
}
public void setFollowing(boolean following) {
this.following = following;
}
public boolean isNotifications() {
return notifications;
}
public void setNotifications(boolean notifications) {
this.notifications = notifications;
}
public int getUtcOffset() {
return utc_offset;
}
public void setUtcOffset(int utc_offset) {
this.utc_offset = utc_offset;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", screen_name="
+ screen_name + ", location=" + location + ", desription="
+ desription + ", profile_image_url=" + profile_image_url
+ ", url=" + url + ", isProtected=" + isProtected
+ ", friends_count=" + friends_count + ", followers_count="
+ followers_count + ", favourites_count=" + favourites_count
+ ", created_at=" + created_at + ", following=" + following
+ ", notifications=" + notifications + ", utc_offset="
+ utc_offset + ", status=" + status + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
| Java |
package com.ch_linghu.fanfoudroid.data2;
public class Photo {
private String thumburl;
private String imageurl;
private String largeurl;
public Photo() {}
public String getThumburl() {
return thumburl;
}
public void setThumburl(String thumburl) {
this.thumburl = thumburl;
}
public String getImageurl() {
return imageurl;
}
public void setImageurl(String imageurl) {
this.imageurl = imageurl;
}
public String getLargeurl() {
return largeurl;
}
public void setLargeurl(String largeurl) {
this.largeurl = largeurl;
}
@Override
public String toString() {
return "Photo [thumburl=" + thumburl + ", imageurl=" + imageurl
+ ", largeurl=" + largeurl + "]";
}
}
| Java |
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.fanfou.User;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.HttpRefusedException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.Refreshable;
import com.ch_linghu.fanfoudroid.ui.base.TwitterListBaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.MyListView;
import com.ch_linghu.fanfoudroid.ui.module.TweetArrayAdapter;
public class UserTimelineActivity extends TwitterListBaseActivity implements
MyListView.OnNeedMoreListener, Refreshable {
private static final String TAG = UserTimelineActivity.class
.getSimpleName();
private Feedback mFeedback;
private static final String EXTRA_USERID = "userID";
private static final String EXTRA_NAME_SHOW = "showName";
private static final String SIS_RUNNING_KEY = "running";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.USERTIMELINE";
public static Intent createIntent(String userID, String showName) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.putExtra(EXTRA_USERID, userID);
intent.putExtra(EXTRA_NAME_SHOW, showName);
return intent;
}
// State.
private User mUser;
private String mUserID;
private String mShowName;
private ArrayList<Tweet> mTweets;
private int mNextPage = 1;
// Views.
private TextView headerView;
private TextView footerView;
private MyListView mTweetList;
// 记录服务器拒绝访问的信息
private String msg;
private static final int LOADINGFLAG = 1;
private static final int SUCCESSFLAG = 2;
private static final int NETWORKERRORFLAG = 3;
private static final int AUTHERRORFLAG = 4;
private TweetArrayAdapter mAdapter;
// Tasks.
private GenericTask mRetrieveTask;
private GenericTask mLoadMoreTask;
private TaskListener mRetrieveTaskListener = new TaskAdapter() {
@Override
public void onPreExecute(GenericTask task) {
onRetrieveBegin();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
mFeedback.failed("登录失败, 请重新登录.");
updateHeader(AUTHERRORFLAG);
return;
} else if (result == TaskResult.OK) {
updateHeader(SUCCESSFLAG);
updateFooter(SUCCESSFLAG);
draw();
goTop();
} else if (result == TaskResult.IO_ERROR) {
mFeedback.failed("更新失败.");
updateHeader(NETWORKERRORFLAG);
}
mFeedback.success("");
}
@Override
public String getName() {
return "UserTimelineRetrieve";
}
};
private TaskListener mLoadMoreTaskListener = new TaskAdapter() {
@Override
public void onPreExecute(GenericTask task) {
onLoadMoreBegin();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
mFeedback.success("");
updateFooter(SUCCESSFLAG);
draw();
}
}
@Override
public String getName() {
return "UserTimelineLoadMoreTask";
}
};
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "_onCreate()...");
if (super._onCreate(savedInstanceState)) {
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
Intent intent = getIntent();
// get user id
mUserID = intent.getStringExtra(EXTRA_USERID);
// show username in title
mShowName = intent.getStringExtra(EXTRA_NAME_SHOW);
// Set header title
mNavbar.setHeaderTitle("@" + mShowName);
boolean wasRunning = isTrue(savedInstanceState, SIS_RUNNING_KEY);
// 此处要求mTweets不为空,最好确保profile页面消息为0时不能进入这个页面
if (!mTweets.isEmpty() && !wasRunning) {
updateHeader(SUCCESSFLAG);
draw();
} else {
doRetrieve();
}
return true;
} else {
return false;
}
}
@Override
protected void onResume() {
super.onResume();
checkIsLogedIn();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
mRetrieveTask.cancel(true);
}
if (mLoadMoreTask != null
&& mLoadMoreTask.getStatus() == GenericTask.Status.RUNNING) {
mLoadMoreTask.cancel(true);
}
super.onDestroy();
}
@Override
protected void draw() {
mAdapter.refresh(mTweets);
}
public void goTop() {
Log.d(TAG, "goTop.");
mTweetList.setSelection(1);
}
public void doRetrieve() {
Log.d(TAG, "Attempting retrieve.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mRetrieveTask = new UserTimelineRetrieveTask();
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.execute();
}
}
private void doLoadMore() {
Log.d(TAG, "Attempting load more.");
if (mLoadMoreTask != null
&& mLoadMoreTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mLoadMoreTask = new UserTimelineLoadMoreTask();
mLoadMoreTask.setListener(mLoadMoreTaskListener);
mLoadMoreTask.execute();
}
}
private void onRetrieveBegin() {
mFeedback.start("");
// 更新查询状态显示
updateHeader(LOADINGFLAG);
updateFooter(LOADINGFLAG);
}
private void onLoadMoreBegin() {
mFeedback.start("");
}
private class UserTimelineRetrieveTask extends GenericTask {
ArrayList<Tweet> mTweets = new ArrayList<Tweet>();
@Override
protected TaskResult _doInBackground(TaskParams... params) {
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
try {
statusList = getApi().getUserTimeline(mUserID,
new Paging(mNextPage));
mUser = getApi().showUser(mUserID);
mFeedback.update(60);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
Throwable cause = e.getCause();
if (cause instanceof HttpRefusedException) {
// AUTH ERROR
msg = ((HttpRefusedException) cause).getError()
.getMessage();
return TaskResult.AUTH_ERROR;
} else {
return TaskResult.IO_ERROR;
}
}
mFeedback.update(100 - (int)Math.floor(statusList.size()*2)); // 60~100
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Tweet tweet;
tweet = Tweet.create(status);
mTweets.add(tweet);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
addTweets(mTweets);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
return TaskResult.OK;
}
}
private class UserTimelineLoadMoreTask extends GenericTask {
ArrayList<Tweet> mTweets = new ArrayList<Tweet>();
@Override
protected TaskResult _doInBackground(TaskParams... params) {
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
try {
statusList = getApi().getUserTimeline(mUserID,
new Paging(mNextPage));
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
Throwable cause = e.getCause();
if (cause instanceof HttpRefusedException) {
// AUTH ERROR
msg = ((HttpRefusedException) cause).getError()
.getMessage();
return TaskResult.AUTH_ERROR;
} else {
return TaskResult.IO_ERROR;
}
}
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Tweet tweet;
tweet = Tweet.create(status);
mTweets.add(tweet);
}
if (isCancelled()) {
return TaskResult.CANCELLED;
}
addTweets(mTweets);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
return TaskResult.OK;
}
}
@Override
public void needMore() {
if (!isLastPage()) {
doLoadMore();
}
}
public boolean isLastPage() {
return mNextPage == -1;
}
private synchronized void addTweets(ArrayList<Tweet> tweets) {
// do more时没有更多时
if (tweets.size() == 0) {
mNextPage = -1;
return;
}
mTweets.addAll(tweets);
++mNextPage;
}
@Override
protected String getActivityTitle() {
return "@" + mShowName;
}
@Override
protected Tweet getContextItemTweet(int position) {
if (position >= 1 && position <= mAdapter.getCount()) {
return (Tweet) mAdapter.getItem(position - 1);
} else {
return null;
}
}
@Override
protected int getLayoutId() {
return R.layout.user_timeline;
}
@Override
protected com.ch_linghu.fanfoudroid.ui.module.TweetAdapter getTweetAdapter() {
return mAdapter;
}
@Override
protected ListView getTweetList() {
return mTweetList;
}
@Override
protected void setupState() {
mTweets = new ArrayList<Tweet>();
mAdapter = new TweetArrayAdapter(this);
mTweetList = (MyListView) findViewById(R.id.tweet_list);
// Add Header to ListView
headerView = (TextView) TextView.inflate(this,
R.layout.user_timeline_header, null);
mTweetList.addHeaderView(headerView);
// Add Footer to ListView
footerView = (TextView) TextView.inflate(this,
R.layout.user_timeline_footer, null);
mTweetList.addFooterView(footerView);
mTweetList.setAdapter(mAdapter);
mTweetList.setOnNeedMoreListener(this);
}
@Override
protected void updateTweet(Tweet tweet) {
// 该方法作用?
}
@Override
protected boolean useBasicMenu() {
return true;
}
private void updateHeader(int flag) {
if (flag == LOADINGFLAG) {
// 重新刷新页面时从第一页开始获取数据 --- phoenix
mNextPage = 1;
mTweets.clear();
mAdapter.refresh(mTweets);
headerView.setText(getResources()
.getString(R.string.search_loading));
}
if (flag == SUCCESSFLAG) {
headerView.setText(getResources().getString(
R.string.user_query_status_success));
}
if (flag == NETWORKERRORFLAG) {
headerView.setText(getResources().getString(
R.string.login_status_network_or_connection_error));
}
if (flag == AUTHERRORFLAG) {
headerView.setText(msg);
}
}
private void updateFooter(int flag) {
if (flag == LOADINGFLAG) {
footerView.setText("该用户总共?条消息");
}
if (flag == SUCCESSFLAG) {
footerView.setText("该用户总共" + mUser.getStatusesCount() + "条消息,当前显示"
+ mTweets.size() + "条。");
}
}
} | Java |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.data.Dm;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.fanfou.DirectMessage;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.ui.module.TweetEdit;
//FIXME: 将WriteDmActivity和WriteActivity进行整合。
/**
* 撰写私信界面
* @author lds
*
*/
public class WriteDmActivity extends BaseActivity {
public static final String NEW_TWEET_ACTION = "com.ch_linghu.fanfoudroid.NEW";
public static final String EXTRA_TEXT = "text";
public static final String REPLY_ID = "reply_id";
private static final String TAG = "WriteActivity";
private static final String SIS_RUNNING_KEY = "running";
private static final String PREFS_NAME = "com.ch_linghu.fanfoudroid";
// View
private TweetEdit mTweetEdit;
private EditText mTweetEditText;
private TextView mProgressText;
private Button mSendButton;
//private AutoCompleteTextView mToEdit;
private TextView mToEdit;
private NavBar mNavbar;
// Task
private GenericTask mSendTask;
private TaskListener mSendTaskListener = new TaskAdapter() {
@Override
public void onPreExecute(GenericTask task) {
disableEntry();
updateProgress(getString(R.string.page_status_updating));
}
@Override
public void onPostExecute(GenericTask task,
TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
mToEdit.setText("");
mTweetEdit.setText("");
updateProgress("");
enableEntry();
// 发送成功就直接关闭界面
finish();
// 关闭软键盘
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mTweetEdit.getEditText().getWindowToken(), 0);
} else if (result == TaskResult.NOT_FOLLOWED_ERROR) {
updateProgress(getString(R.string.direct_meesage_status_the_person_not_following_you));
enableEntry();
} else if (result == TaskResult.IO_ERROR) {
// TODO: 什么情况下会抛出IO_ERROR?需要给用户更为具体的失败原因
updateProgress(getString(R.string.page_status_unable_to_update));
enableEntry();
}
}
@Override
public String getName() {
return "DMSend";
}
};
private FriendsAdapter mFriendsAdapter; // Adapter for To: recipient
// autocomplete.
private static final String EXTRA_USER = "user";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.DMSW";
public static Intent createIntent(String user) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (!TextUtils.isEmpty(user)) {
intent.putExtra(EXTRA_USER, user);
}
return intent;
}
// sub menu
// protected void createInsertPhotoDialog() {
//
// final CharSequence[] items = {
// getString(R.string.write_label_take_a_picture),
// getString(R.string.write_label_choose_a_picture) };
//
// AlertDialog.Builder builder = new AlertDialog.Builder(this);
// builder.setTitle(getString(R.string.write_label_insert_picture));
// builder.setItems(items, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int item) {
// // Toast.makeText(getApplicationContext(), items[item],
// // Toast.LENGTH_SHORT).show();
// switch (item) {
// case 0:
// openImageCaptureMenu();
// break;
// case 1:
// openPhotoLibraryMenu();
// }
// }
// });
// AlertDialog alert = builder.create();
// alert.show();
// }
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)){
// init View
setContentView(R.layout.write_dm);
mNavbar = new NavBar(NavBar.HEADER_STYLE_WRITE, this);
// Intent & Action & Extras
Intent intent = getIntent();
Bundle extras = intent.getExtras();
// View
mProgressText = (TextView) findViewById(R.id.progress_text);
mTweetEditText = (EditText) findViewById(R.id.tweet_edit);
TwitterDatabase db = getDb();
//FIXME: 暂时取消收件人自动完成功能
//FIXME: 可根据目前以后内容重新完成自动完成功能
//mToEdit = (AutoCompleteTextView) findViewById(R.id.to_edit);
//Cursor cursor = db.getFollowerUsernames("");
//// startManagingCursor(cursor);
//mFriendsAdapter = new FriendsAdapter(this, cursor);
//mToEdit.setAdapter(mFriendsAdapter);
mToEdit = (TextView) findViewById(R.id.to_edit);
// Update status
mTweetEdit = new TweetEdit(mTweetEditText,
(TextView) findViewById(R.id.chars_text));
mTweetEdit.setOnKeyListener(editEnterHandler);
mTweetEdit
.addTextChangedListener(new MyTextWatcher(WriteDmActivity.this));
// With extras
if (extras != null) {
String to = extras.getString(EXTRA_USER);
if (!TextUtils.isEmpty(to)) {
mToEdit.setText(to);
mTweetEdit.requestFocus();
}
}
View.OnClickListener sendListenner = new View.OnClickListener() {
public void onClick(View v) {
doSend();
}
};
mSendButton = (Button) findViewById(R.id.send_button);
mSendButton.setOnClickListener(sendListenner);
Button mTopSendButton = (Button) findViewById(R.id.top_send_btn);
mTopSendButton.setOnClickListener(sendListenner);
return true;
}else{
return false;
}
}
@Override
protected void onRestoreInstanceState(Bundle bundle) {
super.onRestoreInstanceState(bundle);
mTweetEdit.updateCharsRemain();
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause.");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart.");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume.");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart.");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop.");
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mSendTask != null
&& mSendTask.getStatus() == GenericTask.Status.RUNNING) {
// Doesn't really cancel execution (we let it continue running).
// See the SendTask code for more details.
mSendTask.cancel(true);
}
// Don't need to cancel FollowersTask (assuming it ends properly).
super.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mSendTask != null
&& mSendTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
public static Intent createNewTweetIntent(String text) {
Intent intent = new Intent(NEW_TWEET_ACTION);
intent.putExtra(EXTRA_TEXT, text);
return intent;
}
private class MyTextWatcher implements TextWatcher {
private WriteDmActivity _activity;
public MyTextWatcher(WriteDmActivity activity) {
_activity = activity;
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
if (s.length() == 0) {
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
}
private void doSend() {
if (mSendTask != null
&& mSendTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
String to = mToEdit.getText().toString();
String status = mTweetEdit.getText().toString();
if (!TextUtils.isEmpty(status) && !TextUtils.isEmpty(to)) {
mSendTask = new DmSendTask();
mSendTask.setListener(mSendTaskListener);
mSendTask.execute();
} else if (TextUtils.isEmpty(status)) {
updateProgress(getString(R.string.direct_meesage_status_texting_is_null));
} else if (TextUtils.isEmpty(to)) {
updateProgress(getString(R.string.direct_meesage_status_user_is_null));
}
}
}
private class DmSendTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
String user = mToEdit.getText().toString();
String text = mTweetEdit.getText().toString();
DirectMessage directMessage = getApi().sendDirectMessage(user,
text);
Dm dm = Dm.create(directMessage, true);
// if (!Utils.isEmpty(dm.profileImageUrl)) {
// // Fetch image to cache.
// try {
// getImageManager().put(dm.profileImageUrl);
// } catch (IOException e) {
// Log.e(TAG, e.getMessage(), e);
// }
// }
getDb().createDm(dm, false);
} catch (HttpException e) {
Log.d(TAG, e.getMessage());
// TODO: check is this is actually the case.
return TaskResult.NOT_FOLLOWED_ERROR;
}
return TaskResult.OK;
}
}
private static class FriendsAdapter extends CursorAdapter {
public FriendsAdapter(Context context, Cursor cursor) {
super(context, cursor);
mInflater = LayoutInflater.from(context);
mUserTextColumn = cursor
.getColumnIndexOrThrow(StatusTable.USER_SCREEN_NAME);
}
private LayoutInflater mInflater;
private int mUserTextColumn;
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = mInflater
.inflate(R.layout.dropdown_item, parent, false);
ViewHolder holder = new ViewHolder();
holder.userText = (TextView) view.findViewById(android.R.id.text1);
view.setTag(holder);
return view;
}
class ViewHolder {
public TextView userText;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = (ViewHolder) view.getTag();
holder.userText.setText(cursor.getString(mUserTextColumn));
}
@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
String filter = constraint == null ? "" : constraint.toString();
return TwitterApplication.mDb.getFollowerUsernames(filter);
}
@Override
public String convertToString(Cursor cursor) {
return cursor.getString(mUserTextColumn);
}
}
private void enableEntry() {
mTweetEdit.setEnabled(true);
mSendButton.setEnabled(true);
}
private void disableEntry() {
mTweetEdit.setEnabled(false);
mSendButton.setEnabled(false);
}
// UI helpers.
private void updateProgress(String progress) {
mProgressText.setText(progress);
}
private View.OnKeyListener editEnterHandler = new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER
|| keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
if (event.getAction() == KeyEvent.ACTION_UP) {
doSend();
}
return true;
}
return false;
}
};
} | Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing search API response
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class QueryResult extends WeiboResponse {
private long sinceId;
private long maxId;
private String refreshUrl;
private int resultsPerPage;
private int total = -1;
private String warning;
private double completedIn;
private int page;
private String query;
private List<Status> tweets;
private static final long serialVersionUID = -9059136565234613286L;
/*package*/ QueryResult(Response res, WeiboSupport weiboSupport) throws HttpException {
super(res);
// 饭否search API直接返回 "[{JSONObejet},{JSONObejet},{JSONObejet}]"的JSONArray
//System.out.println("TAG " + res.asString());
JSONArray array = res.asJSONArray();
try {
tweets = new ArrayList<Status>(array.length());
for (int i = 0; i < array.length(); i++) {
JSONObject tweet = array.getJSONObject(i);
tweets.add(new Status(tweet));
}
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + array.toString(), jsone);
}
}
/*package*/ QueryResult(Query query) throws HttpException {
super();
sinceId = query.getSinceId();
resultsPerPage = query.getRpp();
page = query.getPage();
tweets = new ArrayList<Status>(0);
}
public long getSinceId() {
return sinceId;
}
public long getMaxId() {
return maxId;
}
public String getRefreshUrl() {
return refreshUrl;
}
public int getResultsPerPage() {
return resultsPerPage;
}
/**
* returns the number of hits
* @return number of hits
* @deprecated The Weibo API doesn't return total anymore
* @see <a href="http://yusuke.homeip.net/jira/browse/TFJ-108">TRJ-108 deprecate QueryResult#getTotal()</a>
*/
@Deprecated
public int getTotal() {
return total;
}
public String getWarning() {
return warning;
}
public double getCompletedIn() {
return completedIn;
}
public int getPage() {
return page;
}
public String getQuery() {
return query;
}
public List<Status> getStatus() {
return tweets;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
QueryResult that = (QueryResult) o;
if (Double.compare(that.completedIn, completedIn) != 0) return false;
if (maxId != that.maxId) return false;
if (page != that.page) return false;
if (resultsPerPage != that.resultsPerPage) return false;
if (sinceId != that.sinceId) return false;
if (total != that.total) return false;
if (!query.equals(that.query)) return false;
if (refreshUrl != null ? !refreshUrl.equals(that.refreshUrl) : that.refreshUrl != null)
return false;
if (tweets != null ? !tweets.equals(that.tweets) : that.tweets != null)
return false;
if (warning != null ? !warning.equals(that.warning) : that.warning != null)
return false;
return true;
}
@Override
public int hashCode() {
int result;
long temp;
result = (int) (sinceId ^ (sinceId >>> 32));
result = 31 * result + (int) (maxId ^ (maxId >>> 32));
result = 31 * result + (refreshUrl != null ? refreshUrl.hashCode() : 0);
result = 31 * result + resultsPerPage;
result = 31 * result + total;
result = 31 * result + (warning != null ? warning.hashCode() : 0);
temp = completedIn != +0.0d ? Double.doubleToLongBits(completedIn) : 0L;
result = 31 * result + (int) (temp ^ (temp >>> 32));
result = 31 * result + page;
result = 31 * result + query.hashCode();
result = 31 * result + (tweets != null ? tweets.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "QueryResult{" +
"sinceId=" + sinceId +
", maxId=" + maxId +
", refreshUrl='" + refreshUrl + '\'' +
", resultsPerPage=" + resultsPerPage +
", total=" + total +
", warning='" + warning + '\'' +
", completedIn=" + completedIn +
", page=" + page +
", query='" + query + '\'' +
", tweets=" + tweets +
'}';
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.AccessControlException;
import java.util.Properties;
/**
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class Configuration {
private static Properties defaultProperty;
static {
init();
}
/*package*/ static void init() {
defaultProperty = new Properties();
//defaultProperty.setProperty("fanfoudroid.debug", "false");
defaultProperty.setProperty("fanfoudroid.debug", "true");
defaultProperty.setProperty("fanfoudroid.source", "fanfoudroid");
//defaultProperty.setProperty("fanfoudroid.clientVersion","");
defaultProperty.setProperty("fanfoudroid.clientURL", "http://sandin.tk/fanfoudroid.xml");
defaultProperty.setProperty("fanfoudroid.http.userAgent", "fanfoudroid 1.0");
//defaultProperty.setProperty("fanfoudroid.user","");
//defaultProperty.setProperty("fanfoudroid.password","");
defaultProperty.setProperty("fanfoudroid.http.useSSL", "false");
//defaultProperty.setProperty("fanfoudroid.http.proxyHost","");
defaultProperty.setProperty("fanfoudroid.http.proxyHost.fallback", "http.proxyHost");
//defaultProperty.setProperty("fanfoudroid.http.proxyUser","");
//defaultProperty.setProperty("fanfoudroid.http.proxyPassword","");
//defaultProperty.setProperty("fanfoudroid.http.proxyPort","");
defaultProperty.setProperty("fanfoudroid.http.proxyPort.fallback", "http.proxyPort");
defaultProperty.setProperty("fanfoudroid.http.connectionTimeout", "20000");
defaultProperty.setProperty("fanfoudroid.http.readTimeout", "120000");
defaultProperty.setProperty("fanfoudroid.http.retryCount", "3");
defaultProperty.setProperty("fanfoudroid.http.retryIntervalSecs", "10");
//defaultProperty.setProperty("fanfoudroid.oauth.consumerKey","");
//defaultProperty.setProperty("fanfoudroid.oauth.consumerSecret","");
defaultProperty.setProperty("fanfoudroid.async.numThreads", "1");
defaultProperty.setProperty("fanfoudroid.clientVersion", "1.0");
try {
// Android platform should have dalvik.system.VMRuntime in the classpath.
// @see http://developer.android.com/reference/dalvik/system/VMRuntime.html
Class.forName("dalvik.system.VMRuntime");
defaultProperty.setProperty("fanfoudroid.dalvik", "true");
} catch (ClassNotFoundException cnfe) {
defaultProperty.setProperty("fanfoudroid.dalvik", "false");
}
DALVIK = getBoolean("fanfoudroid.dalvik");
String t4jProps = "fanfoudroid.properties";
boolean loaded = loadProperties(defaultProperty, "." + File.separatorChar + t4jProps) ||
loadProperties(defaultProperty, Configuration.class.getResourceAsStream("/WEB-INF/" + t4jProps)) ||
loadProperties(defaultProperty, Configuration.class.getResourceAsStream("/" + t4jProps));
}
private static boolean loadProperties(Properties props, String path) {
try {
File file = new File(path);
if(file.exists() && file.isFile()){
props.load(new FileInputStream(file));
return true;
}
} catch (Exception ignore) {
}
return false;
}
private static boolean loadProperties(Properties props, InputStream is) {
try {
props.load(is);
return true;
} catch (Exception ignore) {
}
return false;
}
private static boolean DALVIK;
public static boolean isDalvik() {
return DALVIK;
}
public static boolean useSSL() {
return getBoolean("fanfoudroid.http.useSSL");
}
public static String getScheme(){
return useSSL() ? "https://" : "http://";
}
public static String getCilentVersion() {
return getProperty("fanfoudroid.clientVersion");
}
public static String getCilentVersion(String clientVersion) {
return getProperty("fanfoudroid.clientVersion", clientVersion);
}
public static String getSource() {
return getProperty("fanfoudroid.source");
}
public static String getSource(String source) {
return getProperty("fanfoudroid.source", source);
}
public static String getProxyHost() {
return getProperty("fanfoudroid.http.proxyHost");
}
public static String getProxyHost(String proxyHost) {
return getProperty("fanfoudroid.http.proxyHost", proxyHost);
}
public static String getProxyUser() {
return getProperty("fanfoudroid.http.proxyUser");
}
public static String getProxyUser(String user) {
return getProperty("fanfoudroid.http.proxyUser", user);
}
public static String getClientURL() {
return getProperty("fanfoudroid.clientURL");
}
public static String getClientURL(String clientURL) {
return getProperty("fanfoudroid.clientURL", clientURL);
}
public static String getProxyPassword() {
return getProperty("fanfoudroid.http.proxyPassword");
}
public static String getProxyPassword(String password) {
return getProperty("fanfoudroid.http.proxyPassword", password);
}
public static int getProxyPort() {
return getIntProperty("fanfoudroid.http.proxyPort");
}
public static int getProxyPort(int port) {
return getIntProperty("fanfoudroid.http.proxyPort", port);
}
public static int getConnectionTimeout() {
return getIntProperty("fanfoudroid.http.connectionTimeout");
}
public static int getConnectionTimeout(int connectionTimeout) {
return getIntProperty("fanfoudroid.http.connectionTimeout", connectionTimeout);
}
public static int getReadTimeout() {
return getIntProperty("fanfoudroid.http.readTimeout");
}
public static int getReadTimeout(int readTimeout) {
return getIntProperty("fanfoudroid.http.readTimeout", readTimeout);
}
public static int getRetryCount() {
return getIntProperty("fanfoudroid.http.retryCount");
}
public static int getRetryCount(int retryCount) {
return getIntProperty("fanfoudroid.http.retryCount", retryCount);
}
public static int getRetryIntervalSecs() {
return getIntProperty("fanfoudroid.http.retryIntervalSecs");
}
public static int getRetryIntervalSecs(int retryIntervalSecs) {
return getIntProperty("fanfoudroid.http.retryIntervalSecs", retryIntervalSecs);
}
public static String getUser() {
return getProperty("fanfoudroid.user");
}
public static String getUser(String userId) {
return getProperty("fanfoudroid.user", userId);
}
public static String getPassword() {
return getProperty("fanfoudroid.password");
}
public static String getPassword(String password) {
return getProperty("fanfoudroid.password", password);
}
public static String getUserAgent() {
return getProperty("fanfoudroid.http.userAgent");
}
public static String getUserAgent(String userAgent) {
return getProperty("fanfoudroid.http.userAgent", userAgent);
}
public static String getOAuthConsumerKey() {
return getProperty("fanfoudroid.oauth.consumerKey");
}
public static String getOAuthConsumerKey(String consumerKey) {
return getProperty("fanfoudroid.oauth.consumerKey", consumerKey);
}
public static String getOAuthConsumerSecret() {
return getProperty("fanfoudroid.oauth.consumerSecret");
}
public static String getOAuthConsumerSecret(String consumerSecret) {
return getProperty("fanfoudroid.oauth.consumerSecret", consumerSecret);
}
public static boolean getBoolean(String name) {
String value = getProperty(name);
return Boolean.valueOf(value);
}
public static int getIntProperty(String name) {
String value = getProperty(name);
try {
return Integer.parseInt(value);
} catch (NumberFormatException nfe) {
return -1;
}
}
public static int getIntProperty(String name, int fallbackValue) {
String value = getProperty(name, String.valueOf(fallbackValue));
try {
return Integer.parseInt(value);
} catch (NumberFormatException nfe) {
return -1;
}
}
public static long getLongProperty(String name) {
String value = getProperty(name);
try {
return Long.parseLong(value);
} catch (NumberFormatException nfe) {
return -1;
}
}
public static String getProperty(String name) {
return getProperty(name, null);
}
public static String getProperty(String name, String fallbackValue) {
String value;
try {
value = System.getProperty(name, fallbackValue);
if (null == value) {
value = defaultProperty.getProperty(name);
}
if (null == value) {
String fallback = defaultProperty.getProperty(name + ".fallback");
if (null != fallback) {
value = System.getProperty(fallback);
}
}
} catch (AccessControlException ace) {
// Unsigned applet cannot access System properties
value = fallbackValue;
}
return replace(value);
}
private static String replace(String value) {
if (null == value) {
return value;
}
String newValue = value;
int openBrace = 0;
if (-1 != (openBrace = value.indexOf("{", openBrace))) {
int closeBrace = value.indexOf("}", openBrace);
if (closeBrace > (openBrace + 1)) {
String name = value.substring(openBrace + 1, closeBrace);
if (name.length() > 0) {
newValue = value.substring(0, openBrace) + getProperty(name)
+ value.substring(closeBrace + 1);
}
}
}
if (newValue.equals(value)) {
return value;
} else {
return replace(newValue);
}
}
public static int getNumberOfAsyncThreads() {
return getIntProperty("fanfoudroid.async.numThreads");
}
public static boolean getDebug() {
return getBoolean("fanfoudroid.debug");
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing Treands.
*
* @author Yusuke Yamamoto - yusuke at mac.com
* @since Weibo4J 2.0.2
*/
public class Trends extends WeiboResponse implements Comparable<Trends> {
private Date asOf;
private Date trendAt;
private Trend[] trends;
private static final long serialVersionUID = -7151479143843312309L;
public int compareTo(Trends that) {
return this.trendAt.compareTo(that.trendAt);
}
/*package*/ Trends(Response res, Date asOf, Date trendAt, Trend[] trends)
throws HttpException {
super(res);
this.asOf = asOf;
this.trendAt = trendAt;
this.trends = trends;
}
/*package*/
static List<Trends> constructTrendsList(Response res) throws
HttpException {
JSONObject json = res.asJSONObject();
List<Trends> trends;
try {
Date asOf = parseDate(json.getString("as_of"));
JSONObject trendsJson = json.getJSONObject("trends");
trends = new ArrayList<Trends>(trendsJson.length());
Iterator ite = trendsJson.keys();
while (ite.hasNext()) {
String key = (String) ite.next();
JSONArray array = trendsJson.getJSONArray(key);
Trend[] trendsArray = jsonArrayToTrendArray(array);
if (key.length() == 19) {
// current trends
trends.add(new Trends(res, asOf, parseDate(key
, "yyyy-MM-dd HH:mm:ss"), trendsArray));
} else if (key.length() == 16) {
// daily trends
trends.add(new Trends(res, asOf, parseDate(key
, "yyyy-MM-dd HH:mm"), trendsArray));
} else if (key.length() == 10) {
// weekly trends
trends.add(new Trends(res, asOf, parseDate(key
, "yyyy-MM-dd"), trendsArray));
}
}
Collections.sort(trends);
return trends;
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + res.asString(), jsone);
}
}
/*package*/
static Trends constructTrends(Response res) throws HttpException {
JSONObject json = res.asJSONObject();
try {
Date asOf = parseDate(json.getString("as_of"));
JSONArray array = json.getJSONArray("trends");
Trend[] trendsArray = jsonArrayToTrendArray(array);
return new Trends(res, asOf, asOf, trendsArray);
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + res.asString(), jsone);
}
}
private static Date parseDate(String asOfStr) throws HttpException {
Date parsed;
if (asOfStr.length() == 10) {
parsed = new Date(Long.parseLong(asOfStr) * 1000);
} else {
// parsed = WeiboResponse.parseDate(asOfStr, "EEE, d MMM yyyy HH:mm:ss z");
parsed = WeiboResponse.parseDate(asOfStr, "EEE MMM WW HH:mm:ss z yyyy");
}
return parsed;
}
private static Trend[] jsonArrayToTrendArray(JSONArray array) throws JSONException {
Trend[] trends = new Trend[array.length()];
for (int i = 0; i < array.length(); i++) {
JSONObject trend = array.getJSONObject(i);
trends[i] = new Trend(trend);
}
return trends;
}
public Trend[] getTrends() {
return this.trends;
}
public Date getAsOf() {
return asOf;
}
public Date getTrendAt() {
return trendAt;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Trends)) return false;
Trends trends1 = (Trends) o;
if (asOf != null ? !asOf.equals(trends1.asOf) : trends1.asOf != null)
return false;
if (trendAt != null ? !trendAt.equals(trends1.trendAt) : trends1.trendAt != null)
return false;
if (!Arrays.equals(trends, trends1.trends)) return false;
return true;
}
@Override
public int hashCode() {
int result = asOf != null ? asOf.hashCode() : 0;
result = 31 * result + (trendAt != null ? trendAt.hashCode() : 0);
result = 31 * result + (trends != null ? Arrays.hashCode(trends) : 0);
return result;
}
@Override
public String toString() {
return "Trends{" +
"asOf=" + asOf +
", trendAt=" + trendAt +
", trends=" + (trends == null ? null : Arrays.asList(trends)) +
'}';
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONException;
import org.json.JSONObject;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* 模仿JSONObject的XML实现
* @author jmx
*
*/
class XmlObject{
private String str;
public XmlObject(String s){
this.str = s;
}
//FIXME: 这里用的是一个专有的ugly实现
public String getString(String name) throws Exception {
Pattern p = Pattern.compile(String.format("<%s>(.*?)</%s>", name, name));
Matcher m = p.matcher(this.str);
if (m.find()){
return m.group(1);
}else{
throw new Exception(String.format("<%s> value not found", name));
}
}
@Override
public String toString(){
return this.str;
}
}
/**
* 服务器响应的错误信息
*/
public class RefuseError extends WeiboResponse implements java.io.Serializable {
// TODO: get error type
public static final int ERROR_A = 1;
public static final int ERROR_B = 1;
public static final int ERROR_C = 1;
private int mErrorCode = -1;
private String mRequestUrl = "";
private String mResponseError = "";
private static final long serialVersionUID = -2105422180879273058L;
public RefuseError(Response res) throws HttpException {
String error = res.asString();
try{
//先尝试作为json object进行处理
JSONObject json = new JSONObject(error);
init(json);
}catch(Exception e1){
//如果失败,则作为XML再进行处理
try{
XmlObject xml = new XmlObject(error);
init(xml);
}catch(Exception e2){
//再失败就作为普通字符串进行处理,这个处理保证不会出错
init(error);
}
}
}
public void init(JSONObject json) throws HttpException {
try {
mRequestUrl = json.getString("request");
mResponseError = json.getString("error");
parseError(mResponseError);
} catch (JSONException je) {
throw new HttpException(je.getMessage() + ":" + json.toString(), je);
}
}
public void init(XmlObject xml) throws HttpException {
try {
mRequestUrl = xml.getString("request");
mResponseError = xml.getString("error");
parseError(mResponseError);
} catch (Exception e) {
throw new HttpException(e.getMessage() + ":" + xml.toString(), e);
}
}
public void init(String error){
mRequestUrl = "";
mResponseError = error;
parseError(mResponseError);
}
private void parseError(String error) {
if (error.equals("")) {
mErrorCode = ERROR_A;
}
}
public int getErrorCode() {
return mErrorCode;
}
public String getRequestUrl() {
return mRequestUrl;
}
public String getMessage() {
return mResponseError;
}
} | Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import com.ch_linghu.fanfoudroid.http.HttpClient;
/**
* @author Yusuke Yamamoto - yusuke at mac.com
*/
/*protected*/ class WeiboSupport {
protected HttpClient http = null;
protected String source = Configuration.getSource();
protected final boolean USE_SSL;
/*package*/ WeiboSupport(){
USE_SSL = Configuration.useSSL();
http = new HttpClient(); // In case that the user is not logged in
}
/*package*/ WeiboSupport(String userId, String password){
USE_SSL = Configuration.useSSL();
http = new HttpClient(userId, password);
}
/**
* Returns authenticating userid
*
* @return userid
*/
public String getUserId() {
return http.getUserId();
}
/**
* Returns authenticating password
*
* @return password
*/
public String getPassword() {
return http.getPassword();
}
//Low-level interface
public HttpClient getHttpClient(){
return http;
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.Arrays;
import org.json.JSONArray;
import org.json.JSONException;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing array of numeric IDs.
*
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class IDs extends WeiboResponse {
private String[] ids;
private long previousCursor;
private long nextCursor;
private static final long serialVersionUID = -6585026560164704953L;
private static String[] ROOT_NODE_NAMES = {"id_list", "ids"};
/*package*/ IDs(Response res) throws HttpException {
super(res);
Element elem = res.asDocument().getDocumentElement();
ensureRootNodeNameIs(ROOT_NODE_NAMES, elem);
NodeList idlist = elem.getElementsByTagName("id");
ids = new String[idlist.getLength()];
for (int i = 0; i < idlist.getLength(); i++) {
try {
ids[i] = idlist.item(i).getFirstChild().getNodeValue();
} catch (NumberFormatException nfe) {
throw new HttpException("Weibo API returned malformed response(Invalid Number): " + elem, nfe);
} catch (NullPointerException npe) {
throw new HttpException("Weibo API returned malformed response(NULL): " + elem, npe);
}
}
previousCursor = getChildLong("previous_cursor", elem);
nextCursor = getChildLong("next_cursor", elem);
}
/* package */IDs(Response res, Weibo w) throws HttpException {
super(res);
// TODO: 饭否返回的为 JSONArray 类型,
// 例如["ifan","fanfouapi","\u62cd\u62cd","daoru"]
// JSONObject json= res.asJSONObject();
JSONArray jsona = res.asJSONArray();
try {
int size = jsona.length();
ids = new String[size];
for (int i = 0; i < size; i++) {
ids[i] = jsona.getString(i);
}
} catch (JSONException jsone) {
throw new HttpException(jsone);
}
}
public String[] getIDs() {
return ids;
}
/**
*
* @since Weibo4J 2.0.10
*/
public boolean hasPrevious(){
return 0 != previousCursor;
}
/**
*
* @since Weibo4J 2.0.10
*/
public long getPreviousCursor() {
return previousCursor;
}
/**
*
* @since Weibo4J 2.0.10
*/
public boolean hasNext(){
return 0 != nextCursor;
}
/**
*
* @since Weibo4J 2.0.10
*/
public long getNextCursor() {
return nextCursor;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof IDs)) return false;
IDs iDs = (IDs) o;
if (!Arrays.equals(ids, iDs.ids)) return false;
return true;
}
@Override
public int hashCode() {
return ids != null ? Arrays.hashCode(ids) : 0;
}
public int getCount(){
return ids.length;
}
@Override
public String toString() {
return "IDs{" +
"ids=" + ids +
", previousCursor=" + previousCursor +
", nextCursor=" + nextCursor +
'}';
}
} | Java |
/*
* UserObjectWapper.java created on 2010-7-28 上午08:48:35 by bwl (Liu Daoru)
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.io.Serializable;
import java.util.List;
/**
* 对User对象列表进行的包装,以支持cursor相关信息传递
* @author liudaoru - daoru at sina.com.cn
*/
public class UserWapper implements Serializable {
private static final long serialVersionUID = -3119107701303920284L;
/**
* 用户对象列表
*/
private List<User> users;
/**
* 向前翻页的cursor
*/
private long previousCursor;
/**
* 向后翻页的cursor
*/
private long nextCursor;
public UserWapper(List<User> users, long previousCursor, long nextCursor) {
this.users = users;
this.previousCursor = previousCursor;
this.nextCursor = nextCursor;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public long getPreviousCursor() {
return previousCursor;
}
public void setPreviousCursor(long previousCursor) {
this.previousCursor = previousCursor;
}
public long getNextCursor() {
return nextCursor;
}
public void setNextCursor(long nextCursor) {
this.nextCursor = nextCursor;
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
/**
* Controlls pagination
*
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class Paging implements java.io.Serializable {
private int page = -1;
private int count = -1;
private String sinceId = "";
private String maxId = "";
private static final long serialVersionUID = -3285857427993796670L;
public Paging() {
}
public Paging(int page) {
setPage(page);
}
public Paging(String sinceId) {
setSinceId(sinceId);
}
public Paging(int page, int count) {
this(page);
setCount(count);
}
public Paging(int page, String sinceId) {
this(page);
setSinceId(sinceId);
}
public Paging(int page, int count, String sinceId) {
this(page, count);
setSinceId(sinceId);
}
public Paging(int page, int count, String sinceId, String maxId) {
this(page, count, sinceId);
setMaxId(maxId);
}
public int getPage() {
return page;
}
public void setPage(int page) {
if (page < 1) {
throw new IllegalArgumentException("page should be positive integer. passed:" + page);
}
this.page = page;
}
public int getCount() {
return count;
}
public void setCount(int count) {
if (count < 1) {
throw new IllegalArgumentException("count should be positive integer. passed:" + count);
}
this.count = count;
}
public Paging count(int count) {
setCount(count);
return this;
}
public String getSinceId() {
return sinceId;
}
public void setSinceId(String sinceId) {
if (sinceId.length() > 0) {
this.sinceId = sinceId;
} else {
throw new IllegalArgumentException("since_id is null. passed:" + sinceId);
}
}
public Paging sinceId(String sinceId) {
setSinceId(sinceId);
return this;
}
public String getMaxId() {
return maxId;
}
public void setMaxId(String maxId) {
if (maxId.length() == 0) {
throw new IllegalArgumentException("max_id is null. passed:" + maxId);
}
this.maxId = maxId;
}
public Paging maxId(String maxId) {
setMaxId(maxId);
return this;
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import android.text.TextUtils;
import android.util.Log;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.http.HttpClient;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
public class Weibo extends WeiboSupport implements java.io.Serializable {
public static final String TAG = "Weibo_API";
public static final String CONSUMER_KEY = Configuration.getSource();
public static final String CONSUMER_SECRET = "";
private String baseURL = Configuration.getScheme() + "api.fanfou.com/";
private String searchBaseURL = Configuration.getScheme() + "api.fanfou.com/";
private static final long serialVersionUID = -1486360080128882436L;
public Weibo() {
super(); // In case that the user is not logged in
format.setTimeZone(TimeZone.getTimeZone("GMT"));
}
public Weibo(String userId, String password) {
super(userId, password);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
}
public Weibo(String userId, String password, String baseURL) {
this(userId, password);
this.baseURL = baseURL;
}
/**
* 设置HttpClient的Auth,为请求做准备
* @param username
* @param password
*/
public void setCredentials(String username, String password) {
http.setCredentials(username, password);
}
/**
* 仅判断是否为空
* @param username
* @param password
* @return
*/
public static boolean isValidCredentials(String username, String password) {
return !TextUtils.isEmpty(username) && !TextUtils.isEmpty(password);
}
/**
* 在服务器上验证用户名/密码是否正确,成功则返回该用户信息,失败则抛出异常。
* @param username
* @param password
* @return Verified User
* @throws HttpException 验证失败及其他非200响应均抛出异常
*/
public User login(String username, String password) throws HttpException {
Log.d(TAG, "Login attempt for " + username);
http.setCredentials(username, password);
// Verify userName and password on the server.
User user = verifyCredentials();
if (null != user && user.getId().length() > 0) {
}
return user;
}
/**
* Reset HttpClient's Credentials
*/
public void reset() {
http.reset();
}
/**
* Whether Logged-in
* @return
*/
public boolean isLoggedIn() {
// HttpClient的userName&password是由TwitterApplication#onCreate
// 从SharedPreferences中取出的,他们为空则表示尚未登录,因为他们只在验证
// 账户成功后才会被储存,且注销时被清空。
return isValidCredentials(http.getUserId(), http.getPassword());
}
/**
* Sets the base URL
*
* @param baseURL String the base URL
*/
public void setBaseURL(String baseURL) {
this.baseURL = baseURL;
}
/**
* Returns the base URL
*
* @return the base URL
*/
public String getBaseURL() {
return this.baseURL;
}
/**
* Sets the search base URL
*
* @param searchBaseURL the search base URL
* @since fanfoudroid 0.5.0
*/
public void setSearchBaseURL(String searchBaseURL) {
this.searchBaseURL = searchBaseURL;
}
/**
* Returns the search base url
* @return search base url
* @since fanfoudroid 0.5.0
*/
public String getSearchBaseURL(){
return this.searchBaseURL;
}
/**
* Returns authenticating userid
* 注意:此userId不一定等同与饭否用户的user_id参数
* 它可能是任意一种当前用户所使用的ID类型(如邮箱,用户名等),
*
* @return userid
*/
public String getUserId() {
return http.getUserId();
}
/**
* Returns authenticating password
*
* @return password
*/
public String getPassword() {
return http.getPassword();
}
/**
* Issues an HTTP GET request.
*
* @param url the request url
* @param authenticate if true, the request will be sent with BASIC authentication header
* @return the response
* @throws HttpException
*/
protected Response get(String url, boolean authenticate) throws HttpException {
return get(url, null, authenticate);
}
/**
* Issues an HTTP GET request.
*
* @param url the request url
* @param authenticate if true, the request will be sent with BASIC authentication header
* @param name1 the name of the first parameter
* @param value1 the value of the first parameter
* @return the response
* @throws HttpException
*/
protected Response get(String url, String name1, String value1, boolean authenticate) throws HttpException {
ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
params.add( new BasicNameValuePair(name1, HttpClient.encode(value1) ) );
return get(url, params, authenticate);
}
/**
* Issues an HTTP GET request.
*
* @param url the request url
* @param name1 the name of the first parameter
* @param value1 the value of the first parameter
* @param name2 the name of the second parameter
* @param value2 the value of the second parameter
* @param authenticate if true, the request will be sent with BASIC authentication header
* @return the response
* @throws HttpException
*/
protected Response get(String url, String name1, String value1, String name2, String value2, boolean authenticate) throws HttpException {
ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
params.add(new BasicNameValuePair(name1, HttpClient.encode(value1)));
params.add(new BasicNameValuePair(name2, HttpClient.encode(value2)));
return get(url, params, authenticate);
}
/**
* Issues an HTTP GET request.
*
* @param url the request url
* @param params the request parameters
* @param authenticate if true, the request will be sent with BASIC authentication header
* @return the response
* @throws HttpException
*/
protected Response get(String url, ArrayList<BasicNameValuePair> params, boolean authenticated) throws HttpException {
if (url.indexOf("?") == -1) {
url += "?source=" + CONSUMER_KEY;
} else if (url.indexOf("source") == -1) {
url += "&source=" + CONSUMER_KEY;
}
//以HTML格式获得数据,以便进一步处理
url += "&format=html";
if (null != params && params.size() > 0) {
url += "&" + HttpClient.encodeParameters(params);
}
return http.get(url, authenticated);
}
/**
* Issues an HTTP GET request.
*
* @param url the request url
* @param params the request parameters
* @param paging controls pagination
* @param authenticate if true, the request will be sent with BASIC authentication header
* @return the response
* @throws HttpException
*/
protected Response get(String url, ArrayList<BasicNameValuePair> params, Paging paging, boolean authenticate) throws HttpException {
if (null == params) {
params = new ArrayList<BasicNameValuePair>();
}
if (null != paging) {
if ("" != paging.getMaxId()) {
params.add(new BasicNameValuePair("max_id", String.valueOf(paging.getMaxId())));
}
if ("" != paging.getSinceId()) {
params.add(new BasicNameValuePair("since_id", String.valueOf(paging.getSinceId())));
}
if (-1 != paging.getPage()) {
params.add(new BasicNameValuePair("page", String.valueOf(paging.getPage())));
}
if (-1 != paging.getCount()) {
params.add(new BasicNameValuePair("count", String.valueOf(paging.getCount())));
}
return get(url, params, authenticate);
} else {
return get(url, params, authenticate);
}
}
/**
* 生成POST Parameters助手
* @param nameValuePair 参数(一个或多个)
* @return post parameters
*/
public ArrayList<BasicNameValuePair> createParams(BasicNameValuePair... nameValuePair ) {
ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
for (BasicNameValuePair param : nameValuePair) {
params.add(param);
}
return params;
}
/***************** API METHOD START *********************/
/* 搜索相关的方法 */
/**
* Returns tweets that match a specified query.
* <br>This method calls http://api.fanfou.com/users/search.format
* @param query - the search condition
* @return the result
* @throws HttpException
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public QueryResult search(Query query) throws HttpException {
try{
return new QueryResult(get(searchBaseURL + "search/public_timeline.json", query.asPostParameters(), false), this);
}catch(HttpException te){
if(404 == te.getStatusCode()){
return new QueryResult(query);
}else{
throw te;
}
}
}
/**
* Returns the top ten topics that are currently trending on Weibo. The response includes the time of the request, the name of each trend.
* @return the result
* @throws HttpException
* @since fanfoudroid 0.5.0
*/
public Trends getTrends() throws HttpException {
return Trends.constructTrends(get(searchBaseURL + "trends.json", false));
}
private String toDateStr(Date date){
if(null == date){
date = new Date();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(date);
}
/* 消息相关的方法 */
/**
* Returns the 20 most recent statuses from non-protected users who have set a custom user icon.
* <br>This method calls http://api.fanfou.com/statuses/public_timeline.format
*
* @return list of statuses of the Public Timeline
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getPublicTimeline() throws
HttpException {
return Status.constructStatuses(get(getBaseURL() +
"statuses/public_timeline.json", true));
}
public RateLimitStatus getRateLimitStatus()throws
HttpException {
return new RateLimitStatus(get(getBaseURL() +
"account/rate_limit_status.json", true),this);
}
/**
* Returns the 20 most recent statuses, including retweets, posted by the authenticating user and that user's friends. This is the equivalent of /timeline/home on the Web.
* <br>This method calls http://api.fanfou.com/statuses/home_timeline.format
*
* @return list of the home Timeline
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<Status> getHomeTimeline() throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/home_timeline.json", true));
}
/**
* Returns the 20 most recent statuses, including retweets, posted by the authenticating user and that user's friends. This is the equivalent of /timeline/home on the Web.
* <br>This method calls http://api.fanfou.com/statuses/home_timeline.format
*
* @param paging controls pagination
* @return list of the home Timeline
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<Status> getHomeTimeline(Paging paging) throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/home_timeline.json", null, paging, true));
}
/**
* Returns the 20 most recent statuses posted in the last 24 hours from the authenticating1 user and that user's friends.
* It's also possible to request another user's friends_timeline via the id parameter below.
* <br>This method calls http://api.fanfou.com/statuses/friends_timeline.format
*
* @return list of the Friends Timeline
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getFriendsTimeline() throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/friends_timeline.json", true));
}
/**
* Returns the 20 most recent statuses posted in the last 24 hours from the specified userid.
* <br>This method calls http://api.fanfou.com/statuses/friends_timeline.format
*
* @param paging controls pagination
* @return list of the Friends Timeline
* @throws HttpException
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getFriendsTimeline(Paging paging) throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/friends_timeline.json",null, paging, true));
}
/**
* Returns friend time line by page and count.
* <br>This method calls http://api.fanfou.com/statuses/friends_timeline.format
* @param page
* @param count
* @return
* @throws HttpException
*/
public List<Status> getFriendsTimeline(int page, int count) throws
HttpException {
Paging paging = new Paging(page, count);
return Status.constructStatuses(get(getBaseURL() + "statuses/friends_timeline.json",null, paging, true));
}
/**
* Returns the most recent statuses posted in the last 24 hours from the specified userid.
* <br>This method calls http://api.fanfou.com/statuses/user_timeline.format
*
* @param id specifies the ID or screen name of the user for whom to return the user_timeline
* @param paging controls pagenation
* @return list of the user Timeline
* @throws HttpException
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getUserTimeline(String id, Paging paging)
throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/user_timeline/" + id + ".json",
null, paging, http.isAuthenticationEnabled()));
}
/**
* Returns the most recent statuses posted in the last 24 hours from the specified userid.
* <br>This method calls http://api.fanfou.com/statuses/user_timeline.format
*
* @param id specifies the ID or screen name of the user for whom to return the user_timeline
* @return the 20 most recent statuses posted in the last 24 hours from the user
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getUserTimeline(String id) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/user_timeline/" + id + ".json", http.isAuthenticationEnabled()));
}
/**
* Returns the most recent statuses posted in the last 24 hours from the authenticating user.
* <br>This method calls http://api.fanfou.com/statuses/user_timeline.format
*
* @return the 20 most recent statuses posted in the last 24 hours from the user
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getUserTimeline() throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/user_timeline.json"
, true));
}
/**
* Returns the most recent statuses posted in the last 24 hours from the authenticating user.
* <br>This method calls http://api.fanfou.com/statuses/user_timeline.format
*
* @param paging controls pagination
* @return the 20 most recent statuses posted in the last 24 hours from the user
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<Status> getUserTimeline(Paging paging) throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/user_timeline.json"
, null, paging, true));
}
public List<Status> getUserTimeline(int page, int count) throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/user_timeline.json"
, null, new Paging(page, count), true));
}
/**
* Returns the 20 most recent mentions (status containing @username) for the authenticating user.
* <br>This method calls http://api.fanfou.com/statuses/mentions.format
*
* @return the 20 most recent replies
* @throws HttpException
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getMentions() throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/mentions.json",
null, true));
}
// by since_id
public List<Status> getMentions(String since_id) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/mentions.json",
"since_id", String.valueOf(since_id), true));
}
/**
* Returns the 20 most recent mentions (status containing @username) for the authenticating user.
* <br>This method calls http://api.fanfou.com/statuses/mentions.format
*
* @param paging controls pagination
* @return the 20 most recent replies
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getMentions(Paging paging) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/mentions.json",
null, paging, true));
}
/**
* Returns a single status, specified by the id parameter. The status's author will be returned inline.
* <br>This method calls http://api.fanfou.com/statuses/show/id.format
*
* @param id the numerical ID of the status you're trying to retrieve
* @return a single status
* @throws HttpException when Weibo service or network is unavailable. 可能因为“你没有通过这个用户的验证“,返回403
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public Status showStatus(String id) throws HttpException {
return new Status(get(getBaseURL() + "statuses/show/" + id + ".json", true));
}
/**
* Updates the user's status.
* The text will be trimed if the length of the text is exceeding 160 characters.
* <br>This method calls http://api.fanfou.com/statuses/update.format
*
* @param status the text of your status update
* @return the latest status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public Status updateStatus(String status) throws HttpException{
return new Status(http.post(getBaseURL() + "statuses/update.json",
createParams(new BasicNameValuePair("status", status),
new BasicNameValuePair("source", source))));
}
/**
* Updates the user's status.
* The text will be trimed if the length of the text is exceeding 160 characters.
* <br>发布消息 http://api.fanfou.com/statuses/update.[json|xml]
*
* @param status the text of your status update
* @param latitude The location's latitude that this tweet refers to.
* @param longitude The location's longitude that this tweet refers to.
* @return the latest status
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public Status updateStatus(String status, double latitude, double longitude) throws HttpException, JSONException {
return new Status(http.post(getBaseURL() + "statuses/update.json",
createParams(new BasicNameValuePair("status", status),
new BasicNameValuePair("source", source),
new BasicNameValuePair("location", latitude + "," + longitude))));
}
/**
* Updates the user's status.
* 如果要使用inreplyToStatusId参数, 那么该status就必须得是@别人的.
* The text will be trimed if the length of the text is exceeding 160 characters.
* <br>发布消息 http://api.fanfou.com/statuses/update.[json|xml]
*
* @param status the text of your status update
* @param inReplyToStatusId The ID of an existing status that the status to be posted is in reply to. This implicitly sets the in_reply_to_user_id attribute of the resulting status to the user ID of the message being replied to. Invalid/missing status IDs will be ignored.
* @return the latest status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public Status updateStatus(String status, String inReplyToStatusId) throws HttpException {
return new Status(http.post(getBaseURL() + "statuses/update.json",
createParams(new BasicNameValuePair("status", status),
new BasicNameValuePair("source", source),
new BasicNameValuePair("in_reply_to_status_id", inReplyToStatusId))));
}
/**
* Updates the user's status.
* The text will be trimed if the length of the text is exceeding 160 characters.
* <br>发布消息 http://api.fanfou.com/statuses/update.[json|xml]
*
* @param status the text of your status update
* @param inReplyToStatusId The ID of an existing status that the status to be posted is in reply to. This implicitly sets the in_reply_to_user_id attribute of the resulting status to the user ID of the message being replied to. Invalid/missing status IDs will be ignored.
* @param latitude The location's latitude that this tweet refers to.
* @param longitude The location's longitude that this tweet refers to.
* @return the latest status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public Status updateStatus(String status, String inReplyToStatusId
, double latitude, double longitude) throws HttpException {
return new Status(http.post(getBaseURL() + "statuses/update.json",
createParams(new BasicNameValuePair("status", status),
new BasicNameValuePair("source", source),
new BasicNameValuePair("location", latitude + "," + longitude),
new BasicNameValuePair("in_reply_to_status_id", inReplyToStatusId))));
}
/**
* upload the photo.
* The text will be trimed if the length of the text is exceeding 160 characters.
* The image suport.
* <br>上传照片 http://api.fanfou.com/photos/upload.[json|xml]
*
* @param status the text of your status update
* @return the latest status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public Status uploadPhoto(String status, File file) throws HttpException {
return new Status(http.httpRequest(getBaseURL() + "photos/upload.json",
createParams(new BasicNameValuePair("status", status),
new BasicNameValuePair("source", source)),
file, true, HttpPost.METHOD_NAME));
}
public Status updateStatus(String status, File file) throws HttpException {
return uploadPhoto(status, file);
}
/**
* Destroys the status specified by the required ID parameter. The authenticating user must be the author of the specified status.
* <br>删除消息 http://api.fanfou.com/statuses/destroy.[json|xml]
*
* @param statusId The ID of the status to destroy.
* @return the deleted status
* @throws HttpException when Weibo service or network is unavailable
* @since 1.0.5
*/
public Status destroyStatus(String statusId) throws HttpException {
return new Status(http.post(getBaseURL() + "statuses/destroy/" + statusId + ".json",
createParams(), true));
}
/**
* Returns extended information of a given user, specified by ID or screen name as per the required id parameter below. This information includes design settings, so third party developers can theme their widgets according to a given user's preferences.
* <br>This method calls http://api.fanfou.com/users/show.format
*
* @param id (cann't be screenName the ID of the user for whom to request the detail
* @return User
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public User showUser(String id) throws HttpException {
return new User(get(getBaseURL() + "users/show.json",
createParams(new BasicNameValuePair("id", id)), true));
}
/**
* Return a status of repost
* @param to_user_name repost status's user name
* @param repost_status_id repost status id
* @param repost_status_text repost status text
* @param new_status the new status text
* @return a single status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public Status repost(String to_user_name, String repost_status_id,
String repost_status_text, String new_status) throws HttpException {
StringBuilder sb = new StringBuilder();
sb.append(new_status);
sb.append(" ");
sb.append(R.string.pref_rt_prefix_default + ":@");
sb.append(to_user_name);
sb.append(" ");
sb.append(repost_status_text);
sb.append(" ");
String message = sb.toString();
return new Status(http.post(getBaseURL() + "statuses/update.json",
createParams(new BasicNameValuePair("status", message),
new BasicNameValuePair("repost_status_id", repost_status_id)), true));
}
/**
* Return a status of repost
* @param to_user_name repost status's user name
* @param repost_status_id repost status id
* @param repost_status_text repost status text
* @param new_status the new status text
* @return a single status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public Status repost(String new_status, String repost_status_id) throws HttpException
{
return new Status(http.post(getBaseURL() + "statuses/update.json",
createParams(new BasicNameValuePair("status", new_status),
new BasicNameValuePair("source", CONSUMER_KEY),
new BasicNameValuePair("repost_status_id", repost_status_id)), true));
}
/**
* Return a status of repost
* @param repost_status_id repost status id
* @param repost_status_text repost status text
* @return a single status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public Status repost(String repost_status_id, String new_status, boolean tmp) throws HttpException {
Status repost_to = showStatus(repost_status_id);
String to_user_name = repost_to.getUser().getName();
String repost_status_text = repost_to.getText();
return repost(to_user_name, repost_status_id, repost_status_text, new_status);
}
/* User Methods */
/**
* Returns the specified user's friends, each with current status inline.
* <br>This method calls http://api.fanfou.com/statuses/friends.format
*
* @return the list of friends
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<User> getFriendsStatuses() throws HttpException {
return User.constructResult(get(getBaseURL() + "users/friends.json", true));
}
/**
* Returns the specified user's friends, each with current status inline.
* <br>This method calls http://api.fanfou.com/statuses/friends.format
* <br>分页每页显示100条
*
* @param paging controls pagination
* @return the list of friends
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*
*/
public List<User> getFriendsStatuses(Paging paging) throws HttpException {
return User.constructUsers(get(getBaseURL() + "users/friends.json", null,
paging, true));
}
/**
* Returns the user's friends, each with current status inline.
* <br>This method calls http://api.fanfou.com/statuses/friends.format
*
* @param id the ID or screen name of the user for whom to request a list of friends
* @return the list of friends
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<User> getFriendsStatuses(String id) throws HttpException {
return User.constructUsers(get(getBaseURL() + "users/friends.json",
createParams(new BasicNameValuePair("id", id)), false));
}
/**
* Returns the user's friends, each with current status inline.
* <br>This method calls http://api.fanfou.com/statuses/friends.format
*
* @param id the ID or screen name of the user for whom to request a list of friends
* @param paging controls pagination (饭否API 默认返回 100 条/页)
* @return the list of friends
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<User> getFriendsStatuses(String id, Paging paging) throws HttpException {
return User.constructUsers(get(getBaseURL() + "users/friends.json",
createParams(new BasicNameValuePair("id", id)), paging, false));
}
/**
* Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Weibo (this is going to be changed).
* <br>This method calls http://api.fanfou.com/statuses/followers.format
*
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<User> getFollowersStatuses() throws HttpException {
return User.constructResult(get(getBaseURL() + "statuses/followers.json", true));
}
/**
* Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Weibo (this is going to be changed).
* <br>This method calls http://api.fanfou.com/statuses/followers.format
*
* @param paging controls pagination
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<User> getFollowersStatuses(Paging paging) throws HttpException {
return User.constructUsers(get(getBaseURL() + "statuses/followers.json", null
, paging, true));
}
/**
* Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Weibo (this is going to be changed).
* <br>This method calls http://api.fanfou.com/statuses/followers.format
*
* @param id The ID (not screen name) of the user for whom to request a list of followers.
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<User> getFollowersStatuses(String id) throws HttpException {
return User.constructUsers(get(getBaseURL() + "statuses/followers/" + id + ".json", true));
}
/**
* Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Weibo (this is going to be changed).
* <br>This method calls http://api.fanfou.com/statuses/followers.format
*
* @param id The ID or screen name of the user for whom to request a list of followers.
* @param paging controls pagination
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<User> getFollowersStatuses(String id, Paging paging) throws HttpException {
return User.constructUsers(get(getBaseURL() + "statuses/followers/" + id +
".json", null, paging, true));
}
/* 私信功能 */
/**
* Sends a new direct message to the specified user from the authenticating user. Requires both the user and text parameters below.
* The text will be trimed if the length of the text is exceeding 140 characters.
* <br>This method calls http://api.fanfou.com/direct_messages/new.format
* <br>通过客户端只能给互相关注的人发私信
*
* @param id the ID of the user to whom send the direct message
* @param text String
* @return DirectMessage
* @throws HttpException when Weibo service or network is unavailable
@see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public DirectMessage sendDirectMessage(String id, String text) throws HttpException {
return new DirectMessage(http.post(getBaseURL() + "direct_messages/new.json",
createParams(new BasicNameValuePair("user", id),
new BasicNameValuePair("text", text))).asJSONObject());
}
//TODO: need be unit tested by in_reply_to_id.
/**
* Sends a new direct message to the specified user from the authenticating user. Requires both the user and text parameters below.
* The text will be trimed if the length of the text is exceeding 140 characters.
* <br>通过客户端只能给互相关注的人发私信
*
* @param id
* @param text
* @param in_reply_to_id
* @return
* @throws HttpException
*/
public DirectMessage sendDirectMessage(String id, String text, String in_reply_to_id)
throws HttpException {
return new DirectMessage(http.post(getBaseURL() + "direct_messages/new.json",
createParams(new BasicNameValuePair("user", id),
new BasicNameValuePair("text", text),
new BasicNameValuePair("is_reply_to_id", in_reply_to_id))).asJSONObject());
}
/**
* Destroys the direct message specified in the required ID parameter. The authenticating user must be the recipient of the specified direct message.
* <br>This method calls http://api.fanfou.com/direct_messages/destroy/id.format
*
* @param id the ID of the direct message to destroy
* @return the deleted direct message
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public DirectMessage destroyDirectMessage(String id) throws
HttpException {
return new DirectMessage(http.post(getBaseURL() +
"direct_messages/destroy/" + id + ".json", true).asJSONObject());
}
/**
* Returns a list of the direct messages sent to the authenticating user.
* <br>This method calls http://api.fanfou.com/direct_messages.format
*
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<DirectMessage> getDirectMessages() throws HttpException {
return DirectMessage.constructDirectMessages(get(getBaseURL() + "direct_messages.json", true));
}
/**
* Returns a list of the direct messages sent to the authenticating user.
* <br>This method calls http://api.fanfou.com/direct_messages.format
*
* @param paging controls pagination
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<DirectMessage> getDirectMessages(Paging paging) throws HttpException {
return DirectMessage.constructDirectMessages(get(getBaseURL()
+ "direct_messages.json", null, paging, true));
}
/**
* Returns a list of the direct messages sent by the authenticating user.
* <br>This method calls http://api.fanfou.com/direct_messages/sent.format
*
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<DirectMessage> getSentDirectMessages() throws
HttpException {
return DirectMessage.constructDirectMessages(get(getBaseURL() +
"direct_messages/sent.json", null, true));
}
/**
* Returns a list of the direct messages sent by the authenticating user.
* <br>This method calls http://api.fanfou.com/direct_messages/sent.format
*
* @param paging controls pagination
* @return List 默认返回20条, 一次最多返回60条
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<DirectMessage> getSentDirectMessages(Paging paging) throws
HttpException {
return DirectMessage.constructDirectMessages(get(getBaseURL() +
"direct_messages/sent.json", null, paging, true));
}
/* 收藏功能 */
/**
* Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format.
* @return List<Status>
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<Status> getFavorites() throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "favorites.json", createParams(), true));
}
public List<Status> getFavorites(Paging paging) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "favorites.json", createParams(), paging, true));
}
/**
* Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format.
*
* @param page the number of page
* @return List<Status>
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<Status> getFavorites(int page) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "favorites.json", "page", String.valueOf(page), true));
}
/**
* Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format.
*
* @param id the ID or screen name of the user for whom to request a list of favorite statuses
* @return List<Status>
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<Status> getFavorites(String id) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "favorites/" + id + ".json", createParams(), true));
}
/**
* Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format.
*
* @param id the ID or screen name of the user for whom to request a list of favorite statuses
* @param page the number of page
* @return List<Status>
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getFavorites(String id, int page) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "favorites/" + id + ".json", "page", String.valueOf(page), true));
}
public List<Status> getFavorites(String id, Paging paging) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "favorites/" + id + ".json", null, paging, true));
}
/**
* Favorites the status specified in the ID parameter as the authenticating user. Returns the favorite status when successful.
*
* @param id the ID of the status to favorite
* @return Status
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public Status createFavorite(String id) throws HttpException {
return new Status(http.post(getBaseURL() + "favorites/create/" + id + ".json", true));
}
/**
* Un-favorites the status specified in the ID parameter as the authenticating user. Returns the un-favorited status in the requested format when successful.
*
* @param id the ID of the status to un-favorite
* @return Status
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public Status destroyFavorite(String id) throws HttpException {
return new Status(http.post(getBaseURL() + "favorites/destroy/" + id + ".json", true));
}
/**
* Enables notifications for updates from the specified user to the authenticating user. Returns the specified user when successful.
* @param id String
* @return User
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @deprecated 饭否该功能暂时关闭, 等待该功能开放.
*/
public User enableNotification(String id) throws HttpException {
return new User(http.post(getBaseURL() + "notifications/follow/" + id + ".json", true).asJSONObject());
}
/**
* Disables notifications for updates from the specified user to the authenticating user. Returns the specified user when successful.
* @param id String
* @return User
* @throws HttpException when Weibo service or network is unavailable
* @deprecated 饭否该功能暂时关闭, 等待该功能开放.
* @since fanfoudroid 0.5.0
*/
public User disableNotification(String id) throws HttpException {
return new User(http.post(getBaseURL() + "notifications/leave/" + id + ".json", true).asJSONObject());
}
/* 黑名单 */
/**
* Blocks the user specified in the ID parameter as the authenticating user. Returns the blocked user in the requested format when successful.
* @param id the ID or screen_name of the user to block
* @return the blocked user
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public User createBlock(String id) throws HttpException {
return new User(http.post(getBaseURL() + "blocks/create/" + id + ".json", true).asJSONObject());
}
/**
* Un-blocks the user specified in the ID parameter as the authenticating user. Returns the un-blocked user in the requested format when successful.
* @param id the ID or screen_name of the user to block
* @return the unblocked user
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public User destroyBlock(String id) throws HttpException {
return new User(http.post(getBaseURL() + "blocks/destroy/" + id + ".json", true).asJSONObject());
}
/**
* Tests if a friendship exists between two users.
* @param id The ID or screen_name of the potentially blocked user.
* @return if the authenticating user is blocking a target user
* @throws HttpException when Weibo service or network is unavailable
* @deprecated 饭否暂无此功能, 期待此功能
* @since fanfoudroid 0.5.0
*/
public boolean existsBlock(String id) throws HttpException {
try{
return -1 == get(getBaseURL() + "blocks/exists/" + id + ".json", true).
asString().indexOf("<error>You are not blocking this user.</error>");
}catch(HttpException te){
if(te.getStatusCode() == 404){
return false;
}
throw te;
}
}
/**
* Returns a list of user objects that the authenticating user is blocking.
* @return a list of user objects that the authenticating user
* @throws HttpException when Weibo service or network is unavailable
* @deprecated 饭否暂无此功能, 期待此功能
* @since fanfoudroid 0.5.0
*/
public List<User> getBlockingUsers() throws
HttpException {
return User.constructUsers(get(getBaseURL() +
"blocks/blocking.json", true));
}
/**
* Returns a list of user objects that the authenticating user is blocking.
* @param page the number of page
* @return a list of user objects that the authenticating user
* @throws HttpException when Weibo service or network is unavailable
* @deprecated 饭否暂无此功能, 期待此功能
* @since fanfoudroid 0.5.0
*/
public List<User> getBlockingUsers(int page) throws
HttpException {
return User.constructUsers(get(getBaseURL() +
"blocks/blocking.json?page=" + page, true));
}
/**
* Returns an array of numeric user ids the authenticating user is blocking.
* @return Returns an array of numeric user ids the authenticating user is blocking.
* @throws HttpException when Weibo service or network is unavailable
* @deprecated 饭否暂无此功能, 期待此功能
* @since fanfoudroid 0.5.0
*/
public IDs getBlockingUsersIDs() throws HttpException {
return new IDs(get(getBaseURL() + "blocks/blocking/ids.json", true),this);
}
/* 好友关系方法 */
/**
* Tests if a friendship exists between two users.
*
* @param userA The ID or screen_name of the first user to test friendship for.
* @param userB The ID or screen_name of the second user to test friendship for.
* @return if a friendship exists between two users.
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public boolean existsFriendship(String userA, String userB) throws HttpException {
return -1 != get(getBaseURL() + "friendships/exists.json", "user_a", userA, "user_b", userB, true).
asString().indexOf("true");
}
/**
* Discontinues friendship with the user specified in the ID parameter as the authenticating user. Returns the un-friended user in the requested format when successful. Returns a string describing the failure condition when unsuccessful.
*
* @param id the ID or screen name of the user for whom to request a list of friends
* @return User
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public User destroyFriendship(String id) throws HttpException {
return new User(http.post(getBaseURL() + "friendships/destroy/" + id + ".json", createParams(), true).asJSONObject());
}
/**
* Befriends the user specified in the ID parameter as the authenticating user. Returns the befriended user in the requested format when successful. Returns a string describing the failure condition when unsuccessful.
*
* @param id the ID or screen name of the user to be befriended
* @return the befriended user
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public User createFriendship(String id) throws HttpException {
return new User(http.post(getBaseURL() + "friendships/create/" + id + ".json", createParams(), true).asJSONObject());
}
/**
* Returns an array of numeric IDs for every user the specified user is followed by.
* @param userId Specifies the ID of the user for whom to return the followers list.
* @param cursor Specifies the page number of the results beginning at 1. A single page contains 5000 ids. This is recommended for users with large ID lists. If not provided all ids are returned.
* @return The ID or screen_name of the user to retrieve the friends ID list for.
* @throws HttpException when Weibo service or network is unavailable
* @since Weibo4J 2.0.10
* @see <a href="http://open.t.sina.com.cn/wiki/index.php/Followers/ids">followers/ids </a>
*/
public IDs getFollowersIDs(String userId) throws HttpException {
return new IDs(get(getBaseURL() + "followers/ids.json?user_id=" + userId, true), this);
}
/**
* Returns an array of numeric IDs for every user the specified user is followed by.
* @param cursor Specifies the page number of the results beginning at 1. A single page contains 5000 ids. This is recommended for users with large ID lists. If not provided all ids are returned.
* @return The ID or screen_name of the user to retrieve the friends ID list for.
* @throws HttpException when Weibo service or network is unavailable
* @since Weibo4J 2.0.10
* @see <a href="http://open.t.sina.com.cn/wiki/index.php/Followers/ids">followers/ids </a>
*/
public IDs getFollowersIDs() throws HttpException {
return new IDs(get(getBaseURL() + "followers/ids.json", true), this);
}
public List<com.ch_linghu.fanfoudroid.fanfou.User> getFollowersList(String userId,Paging paging) throws HttpException{
return User.constructUsers(get(getBaseURL() + "users/followers.json",
createParams(new BasicNameValuePair("id", userId)),paging, false));
}
public List<com.ch_linghu.fanfoudroid.fanfou.User> getFollowersList(String userId) throws HttpException{
return User.constructUsers(get(getBaseURL() + "users/followers.json",
createParams(new BasicNameValuePair("id", userId)), false));
}
/**
* Returns an array of numeric IDs for every user the authenticating user is following.
* @return an array of numeric IDs for every user the authenticating user is following
* @throws HttpException when Weibo service or network is unavailable
* @since androidroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public IDs getFriendsIDs() throws HttpException {
return getFriendsIDs(-1l);
}
/**
* Returns an array of numeric IDs for every user the authenticating user is following.
* <br/>饭否无cursor参数
*
* @param cursor Specifies the page number of the results beginning at 1. A single page contains 5000 ids. This is recommended for users with large ID lists. If not provided all ids are returned.
* @return an array of numeric IDs for every user the authenticating user is following
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public IDs getFriendsIDs(long cursor) throws HttpException {
return new IDs(get(getBaseURL() + "friends/ids.json?cursor=" + cursor, true), this);
}
/**
* 获取关注者id列表
* @param userId
* @return
* @throws HttpException
*/
public IDs getFriendsIDs(String userId) throws HttpException{
return new IDs(get(getBaseURL() + "friends/ids.json?id=" +userId , true), this);
}
/* 账户方法 */
/**
* Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful; returns a 401 status code and an error message if not. Use this method to test if supplied user credentials are valid.
* 注意: 如果使用 错误的用户名/密码 多次登录后,饭否会锁IP
* 返回提示为“尝试次数过多,请去 http://fandou.com 登录“,且需输入验证码
*
* 登录成功返回 200 code
* 登录失败返回 401 code
* 使用HttpException的getStatusCode取得code
*
* @return user
* @since androidroid 0.5.0
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public User verifyCredentials() throws HttpException {
return new User(get(getBaseURL() + "account/verify_credentials.json"
, true).asJSONObject());
}
/* Saved Searches Methods */
/**
* Returns the authenticated user's saved search queries.
* @return Returns an array of numeric user ids the authenticating user is blocking.
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public List<SavedSearch> getSavedSearches() throws HttpException {
return SavedSearch.constructSavedSearches(get(getBaseURL() + "saved_searches.json", true));
}
/**
* Retrieve the data for a saved search owned by the authenticating user specified by the given id.
* @param id The id of the saved search to be retrieved.
* @return the data for a saved search
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public SavedSearch showSavedSearch(int id) throws HttpException {
return new SavedSearch(get(getBaseURL() + "saved_searches/show/" + id
+ ".json", true));
}
/**
* Retrieve the data for a saved search owned by the authenticating user specified by the given id.
* @return the data for a created saved search
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public SavedSearch createSavedSearch(String query) throws HttpException {
return new SavedSearch(http.post(getBaseURL() + "saved_searches/create.json",
createParams(new BasicNameValuePair("query", query)), true));
}
/**
* Destroys a saved search for the authenticated user. The search specified by id must be owned by the authenticating user.
* @param id The id of the saved search to be deleted.
* @return the data for a destroyed saved search
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public SavedSearch destroySavedSearch(int id) throws HttpException {
return new SavedSearch(http.post(getBaseURL() + "saved_searches/destroy/" + id
+ ".json", true));
}
/* Help Methods */
/**
* Returns the string "ok" in the requested format with a 200 OK HTTP status code.
* @return true if the API is working
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public boolean test() throws HttpException {
return -1 != get(getBaseURL() + "help/test.json", false).
asString().indexOf("ok");
}
/***************** API METHOD END *********************/
private SimpleDateFormat format = new SimpleDateFormat(
"EEE, d MMM yyyy HH:mm:ss z", Locale.US);
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Weibo weibo = (Weibo) o;
if (!baseURL.equals(weibo.baseURL)) return false;
if (!format.equals(weibo.format)) return false;
if (!http.equals(weibo.http)) return false;
if (!searchBaseURL.equals(weibo.searchBaseURL)) return false;
if (!source.equals(weibo.source)) return false;
return true;
}
@Override
public int hashCode() {
int result = http.hashCode();
result = 31 * result + baseURL.hashCode();
result = 31 * result + searchBaseURL.hashCode();
result = 31 * result + source.hashCode();
result = 31 * result + format.hashCode();
return result;
}
@Override
public String toString() {
return "Weibo{" +
"http=" + http +
", baseURL='" + baseURL + '\'' +
", searchBaseURL='" + searchBaseURL + '\'' +
", source='" + source + '\'' +
", format=" + format +
'}';
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing one single status of a user.
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class Status extends WeiboResponse implements java.io.Serializable {
private static final long serialVersionUID = 1608000492860584608L;
private Date createdAt;
private String id;
private String text;
private String source;
private boolean isTruncated;
private String inReplyToStatusId;
private String inReplyToUserId;
private boolean isFavorited;
private String inReplyToScreenName;
private double latitude = -1;
private double longitude = -1;
private String thumbnail_pic;
private String bmiddle_pic;
private String original_pic;
private String photo_url;
private RetweetDetails retweetDetails;
private User user = null;
/*package*/Status(Response res, Weibo weibo) throws HttpException {
super(res);
Element elem = res.asDocument().getDocumentElement();
init(res, elem, weibo);
}
/*package*/Status(Response res, Element elem, Weibo weibo) throws
HttpException {
super(res);
init(res, elem, weibo);
}
Status(Response res)throws HttpException{
super(res);
JSONObject json=res.asJSONObject();
try {
id = json.getString("id");
text = json.getString("text");
source = json.getString("source");
createdAt = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
inReplyToStatusId = getString("in_reply_to_status_id", json);
inReplyToUserId = getString("in_reply_to_user_id", json);
isFavorited = getBoolean("favorited", json);
// System.out.println("json photo" + json.getJSONObject("photo"));
if(!json.isNull("photo")) {
// System.out.println("not null" + json.getJSONObject("photo"));
Photo photo = new Photo(json.getJSONObject("photo"));
thumbnail_pic = photo.getThumbnail_pic();
bmiddle_pic = photo.getBmiddle_pic();
original_pic = photo.getOriginal_pic();
} else {
// System.out.println("Null");
thumbnail_pic = "";
bmiddle_pic = "";
original_pic = "";
}
if(!json.isNull("user"))
user = new User(json.getJSONObject("user"));
inReplyToScreenName=json.getString("in_reply_to_screen_name");
if(!json.isNull("retweetDetails")){
retweetDetails = new RetweetDetails(json.getJSONObject("retweetDetails"));
}
} catch (JSONException je) {
throw new HttpException(je.getMessage() + ":" + json.toString(), je);
}
}
/* modify by sycheng add some field*/
public Status(JSONObject json)throws HttpException, JSONException{
id = json.getString("id");
text = json.getString("text");
source = json.getString("source");
createdAt = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
isFavorited = getBoolean("favorited", json);
isTruncated=getBoolean("truncated", json);
inReplyToStatusId = getString("in_reply_to_status_id", json);
inReplyToUserId = getString("in_reply_to_user_id", json);
inReplyToScreenName=json.getString("in_reply_to_screen_name");
if(!json.isNull("photo")) {
Photo photo = new Photo(json.getJSONObject("photo"));
thumbnail_pic = photo.getThumbnail_pic();
bmiddle_pic = photo.getBmiddle_pic();
original_pic = photo.getOriginal_pic();
} else {
thumbnail_pic = "";
bmiddle_pic = "";
original_pic = "";
}
user = new User(json.getJSONObject("user"));
}
public Status(String str) throws HttpException, JSONException {
// StatusStream uses this constructor
super();
JSONObject json = new JSONObject(str);
id = json.getString("id");
text = json.getString("text");
source = json.getString("source");
createdAt = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
inReplyToStatusId = getString("in_reply_to_status_id", json);
inReplyToUserId = getString("in_reply_to_user_id", json);
isFavorited = getBoolean("favorited", json);
if(!json.isNull("photo")) {
Photo photo = new Photo(json.getJSONObject("photo"));
thumbnail_pic = photo.getThumbnail_pic();
bmiddle_pic = photo.getBmiddle_pic();
original_pic = photo.getOriginal_pic();
} else {
thumbnail_pic = "";
bmiddle_pic = "";
original_pic = "";
}
user = new User(json.getJSONObject("user"));
}
private void init(Response res, Element elem, Weibo weibo) throws
HttpException {
ensureRootNodeNameIs("status", elem);
user = new User(res, (Element) elem.getElementsByTagName("user").item(0)
, weibo);
id = getChildString("id", elem);
text = getChildText("text", elem);
source = getChildText("source", elem);
createdAt = getChildDate("created_at", elem);
isTruncated = getChildBoolean("truncated", elem);
inReplyToStatusId = getChildString("in_reply_to_status_id", elem);
inReplyToUserId = getChildString("in_reply_to_user_id", elem);
isFavorited = getChildBoolean("favorited", elem);
inReplyToScreenName = getChildText("in_reply_to_screen_name", elem);
NodeList georssPoint = elem.getElementsByTagName("georss:point");
if(1 == georssPoint.getLength()){
String[] point = georssPoint.item(0).getFirstChild().getNodeValue().split(" ");
if(!"null".equals(point[0]))
latitude = Double.parseDouble(point[0]);
if(!"null".equals(point[1]))
longitude = Double.parseDouble(point[1]);
}
NodeList retweetDetailsNode = elem.getElementsByTagName("retweet_details");
if(1 == retweetDetailsNode.getLength()){
retweetDetails = new RetweetDetails(res,(Element)retweetDetailsNode.item(0),weibo);
}
}
/**
* Return the created_at
*
* @return created_at
* @since Weibo4J 1.1.0
*/
public Date getCreatedAt() {
return this.createdAt;
}
/**
* Returns the id of the status
*
* @return the id
*/
public String getId() {
return this.id;
}
/**
* Returns the text of the status
*
* @return the text
*/
public String getText() {
return this.text;
}
/**
* Returns the source
*
* @return the source
* @since Weibo4J 1.0.4
*/
public String getSource() {
return this.source;
}
/**
* Test if the status is truncated
*
* @return true if truncated
* @since Weibo4J 1.0.4
*/
public boolean isTruncated() {
return isTruncated;
}
/**
* Returns the in_reply_tostatus_id
*
* @return the in_reply_tostatus_id
* @since Weibo4J 1.0.4
*/
public String getInReplyToStatusId() {
return inReplyToStatusId;
}
/**
* Returns the in_reply_user_id
*
* @return the in_reply_tostatus_id
* @since Weibo4J 1.0.4
*/
public String getInReplyToUserId() {
return inReplyToUserId;
}
/**
* Returns the in_reply_to_screen_name
*
* @return the in_in_reply_to_screen_name
* @since Weibo4J 2.0.4
*/
public String getInReplyToScreenName() {
return inReplyToScreenName;
}
/**
* returns The location's latitude that this tweet refers to.
*
* @since Weibo4J 2.0.10
*/
public double getLatitude() {
return latitude;
}
/**
* returns The location's longitude that this tweet refers to.
*
* @since Weibo4J 2.0.10
*/
public double getLongitude() {
return longitude;
}
/**
* Test if the status is favorited
*
* @return true if favorited
* @since Weibo4J 1.0.4
*/
public boolean isFavorited() {
return isFavorited;
}
public String getThumbnail_pic() {
return thumbnail_pic;
}
public String getBmiddle_pic() {
return bmiddle_pic;
}
public String getOriginal_pic() {
return original_pic;
}
/**
* Return the user
*
* @return the user
*/
public User getUser() {
return user;
}
// TODO: 等合并Tweet, Status
public int getType() {
return -1111111;
}
/**
*
* @since Weibo4J 2.0.10
*/
public boolean isRetweet(){
return null != retweetDetails;
}
/**
*
* @since Weibo4J 2.0.10
*/
public RetweetDetails getRetweetDetails() {
return retweetDetails;
}
/*package*/
static List<Status> constructStatuses(Response res,
Weibo weibo) throws HttpException {
Document doc = res.asDocument();
if (isRootNodeNilClasses(doc)) {
return new ArrayList<Status>(0);
} else {
try {
ensureRootNodeNameIs("statuses", doc);
NodeList list = doc.getDocumentElement().getElementsByTagName(
"status");
int size = list.getLength();
List<Status> statuses = new ArrayList<Status>(size);
for (int i = 0; i < size; i++) {
Element status = (Element) list.item(i);
statuses.add(new Status(res, status, weibo));
}
return statuses;
} catch (HttpException te) {
ensureRootNodeNameIs("nil-classes", doc);
return new ArrayList<Status>(0);
}
}
}
/* modify by sycheng add json call method */
/* package */
static List<Status> constructStatuses(Response res) throws HttpException {
try {
JSONArray list = res.asJSONArray();
int size = list.length();
List<Status> statuses = new ArrayList<Status>(size);
for (int i = 0; i < size; i++) {
statuses.add(new Status(list.getJSONObject(i)));
}
return statuses;
} catch (JSONException jsone) {
throw new HttpException(jsone);
} catch (HttpException te) {
throw te;
}
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public boolean equals(Object obj) {
if (null == obj) {
return false;
}
if (this == obj) {
return true;
}
// return obj instanceof Status && ((Status) obj).id == this.id;
return obj instanceof Status && this.id.equals(((Status) obj).id);
}
@Override
public String toString() {
return "Status{" +
"createdAt=" + createdAt +
", id=" + id +
", text='" + text + '\'' +
", source='" + source + '\'' +
", isTruncated=" + isTruncated +
", inReplyToStatusId=" + inReplyToStatusId +
", inReplyToUserId=" + inReplyToUserId +
", isFavorited=" + isFavorited +
", thumbnail_pic=" + thumbnail_pic +
", bmiddle_pic=" + bmiddle_pic +
", original_pic=" + original_pic +
", inReplyToScreenName='" + inReplyToScreenName + '\'' +
", latitude=" + latitude +
", longitude=" + longitude +
", retweetDetails=" + retweetDetails +
", user=" + user +
'}';
}
public boolean isEmpty() {
return (null == id);
}
}
| Java |
package com.ch_linghu.fanfoudroid.fanfou;
/**
* An exception class that will be thrown when WeiboAPI calls are failed.<br>
* In case the Fanfou server returned HTTP error code, you can get the HTTP status code using getStatusCode() method.
*/
public class WeiboException extends Exception {
private int statusCode = -1;
private static final long serialVersionUID = -2623309261327598087L;
public WeiboException(String msg) {
super(msg);
}
public WeiboException(Exception cause) {
super(cause);
}
public WeiboException(String msg, int statusCode) {
super(msg);
this.statusCode = statusCode;
}
public WeiboException(String msg, Exception cause) {
super(msg, cause);
}
public WeiboException(String msg, Exception cause, int statusCode) {
super(msg, cause);
this.statusCode = statusCode;
}
public int getStatusCode() {
return this.statusCode;
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing a Saved Search
*
* @author Yusuke Yamamoto - yusuke at mac.com
* @since Weibo4J 2.0.8
*/
public class SavedSearch extends WeiboResponse {
private Date createdAt;
private String query;
private int position;
private String name;
private int id;
private static final long serialVersionUID = 3083819860391598212L;
/*package*/ SavedSearch(Response res) throws HttpException {
super(res);
init(res.asJSONObject());
}
/*package*/ SavedSearch(Response res, JSONObject json) throws HttpException {
super(res);
init(json);
}
/*package*/ SavedSearch(JSONObject savedSearch) throws HttpException {
init(savedSearch);
}
/*package*/ static List<SavedSearch> constructSavedSearches(Response res) throws HttpException {
JSONArray json = res.asJSONArray();
List<SavedSearch> savedSearches;
try {
savedSearches = new ArrayList<SavedSearch>(json.length());
for(int i=0;i<json.length();i++){
savedSearches.add(new SavedSearch(res,json.getJSONObject(i)));
}
return savedSearches;
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + res.asString(), jsone);
}
}
private void init(JSONObject savedSearch) throws HttpException {
try {
createdAt = parseDate(savedSearch.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
query = getString("query", savedSearch, true);
name = getString("name", savedSearch, true);
id = getInt("id", savedSearch);
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + savedSearch.toString(), jsone);
}
}
public Date getCreatedAt() {
return createdAt;
}
public String getQuery() {
return query;
}
public int getPosition() {
return position;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof SavedSearch)) return false;
SavedSearch that = (SavedSearch) o;
if (id != that.id) return false;
if (position != that.position) return false;
if (!createdAt.equals(that.createdAt)) return false;
if (!name.equals(that.name)) return false;
if (!query.equals(that.query)) return false;
return true;
}
@Override
public int hashCode() {
int result = createdAt.hashCode();
result = 31 * result + query.hashCode();
result = 31 * result + position;
result = 31 * result + name.hashCode();
result = 31 * result + id;
return result;
}
@Override
public String toString() {
return "SavedSearch{" +
"createdAt=" + createdAt +
", query='" + query + '\'' +
", position=" + position +
", name='" + name + '\'' +
", id=" + id +
'}';
}
}
| Java |
/*
Copyright (c) 2007-2009
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import org.apache.http.message.BasicNameValuePair;
/**
* A data class represents search query.
*/
public class Query {
private String query = null;
private String lang = null;
private int rpp = -1;
private int page = -1;
private long sinceId = -1;
private String maxId = null;
private String geocode = null;
public Query(){
}
public Query(String query){
this.query = query;
}
public String getQuery() {
return query;
}
/**
* Sets the query string
* @param query - the query string
*/
public void setQuery(String query) {
this.query = query;
}
public String getLang() {
return lang;
}
/**
* restricts tweets to the given language, given by an <a href="http://en.wikipedia.org/wiki/ISO_639-1">ISO 639-1 code</a>
* @param lang an <a href="http://en.wikipedia.org/wiki/ISO_639-1">ISO 639-1 code</a>
*/
public void setLang(String lang) {
this.lang = lang;
}
public int getRpp() {
return rpp;
}
/**
* sets the number of tweets to return per page, up to a max of 100
* @param rpp the number of tweets to return per page
*/
public void setRpp(int rpp) {
this.rpp = rpp;
}
public int getPage() {
return page;
}
/**
* sets the page number (starting at 1) to return, up to a max of roughly 1500 results
* @param page - the page number (starting at 1) to return
*/
public void setPage(int page) {
this.page = page;
}
public long getSinceId() {
return sinceId;
}
/**
* returns tweets with status ids greater than the given id.
* @param sinceId - returns tweets with status ids greater than the given id
*/
public void setSinceId(long sinceId) {
this.sinceId = sinceId;
}
public String getMaxId() {
return maxId;
}
/**
* returns tweets with status ids less than the given id.
* @param maxId - returns tweets with status ids less than the given id
*/
public void setMaxId(String maxId) {
this.maxId = maxId;
}
public String getGeocode() {
return geocode;
}
public static final String MILES = "mi";
public static final String KILOMETERS = "km";
/**
* returns tweets by users located within a given radius of the given latitude/longitude, where the user's location is taken from their Weibo profile
* @param latitude latitude
* @param longtitude longtitude
* @param radius radius
* @param unit Query.MILES or Query.KILOMETERS
*/
public void setGeoCode(double latitude, double longtitude, double radius
, String unit) {
this.geocode = latitude + "," + longtitude + "," + radius + unit;
}
public ArrayList<BasicNameValuePair> asPostParameters(){
ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
appendParameter("q", query, params);
appendParameter("lang", lang, params);
appendParameter("page", page, params);
appendParameter("since_id",sinceId , params);
appendParameter("max_id", maxId, params);
appendParameter("geocode", geocode, params);
return params;
}
private void appendParameter(String name, String value, ArrayList<BasicNameValuePair> params) {
if (null != value) {
params.add(new BasicNameValuePair(name, value));
}
}
private void appendParameter(String name, long value, ArrayList<BasicNameValuePair> params) {
if (0 <= value) {
params.add(new BasicNameValuePair(name, value + ""));
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Query query1 = (Query) o;
if (page != query1.page) return false;
if (rpp != query1.rpp) return false;
if (sinceId != query1.sinceId) return false;
if (geocode != null ? !geocode.equals(query1.geocode) : query1.geocode != null)
return false;
if (lang != null ? !lang.equals(query1.lang) : query1.lang != null)
return false;
if (query != null ? !query.equals(query1.query) : query1.query != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = query != null ? query.hashCode() : 0;
result = 31 * result + (lang != null ? lang.hashCode() : 0);
result = 31 * result + rpp;
result = 31 * result + page;
result = 31 * result + (int) (sinceId ^ (sinceId >>> 32));
result = 31 * result + (geocode != null ? geocode.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Query{" +
"query='" + query + '\'' +
", lang='" + lang + '\'' +
", rpp=" + rpp +
", page=" + page +
", sinceId=" + sinceId +
", geocode='" + geocode + '\'' +
'}';
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.ch_linghu.fanfoudroid.http.HTMLEntity;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* Super class of Weibo Response objects.
*
* @see weibo4j.DirectMessage
* @see weibo4j.Status
* @see weibo4j.User
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class WeiboResponse implements java.io.Serializable {
private static Map<String,SimpleDateFormat> formatMap = new HashMap<String,SimpleDateFormat>();
private static final long serialVersionUID = 3519962197957449562L;
private transient int rateLimitLimit = -1;
private transient int rateLimitRemaining = -1;
private transient long rateLimitReset = -1;
public WeiboResponse() {
}
public WeiboResponse(Response res) {
}
protected static void ensureRootNodeNameIs(String rootName, Element elem) throws HttpException {
if (!rootName.equals(elem.getNodeName())) {
throw new HttpException("Unexpected root node name:" + elem.getNodeName() + ". Expected:" + rootName + ". Check the availability of the Weibo API at http://open.t.sina.com.cn/.");
}
}
protected static void ensureRootNodeNameIs(String[] rootNames, Element elem) throws HttpException {
String actualRootName = elem.getNodeName();
for (String rootName : rootNames) {
if (rootName.equals(actualRootName)) {
return;
}
}
String expected = "";
for (int i = 0; i < rootNames.length; i++) {
if (i != 0) {
expected += " or ";
}
expected += rootNames[i];
}
throw new HttpException("Unexpected root node name:" + elem.getNodeName() + ". Expected:" + expected + ". Check the availability of the Weibo API at http://open.t.sina.com.cn/.");
}
protected static void ensureRootNodeNameIs(String rootName, Document doc) throws HttpException {
Element elem = doc.getDocumentElement();
if (!rootName.equals(elem.getNodeName())) {
throw new HttpException("Unexpected root node name:" + elem.getNodeName() + ". Expected:" + rootName + ". Check the availability of the Weibo API at http://open.t.sina.com.cn/");
}
}
protected static boolean isRootNodeNilClasses(Document doc) {
String root = doc.getDocumentElement().getNodeName();
return "nil-classes".equals(root) || "nilclasses".equals(root);
}
protected static String getChildText( String str, Element elem ) {
return HTMLEntity.unescape(getTextContent(str,elem));
}
protected static String getTextContent(String str, Element elem){
NodeList nodelist = elem.getElementsByTagName(str);
if (nodelist.getLength() > 0) {
Node node = nodelist.item(0).getFirstChild();
if (null != node) {
String nodeValue = node.getNodeValue();
return null != nodeValue ? nodeValue : "";
}
}
return "";
}
/*modify by sycheng add "".equals(str) */
protected static int getChildInt(String str, Element elem) {
String str2 = getTextContent(str, elem);
if (null == str2 || "".equals(str2)||"null".equals(str)) {
return -1;
} else {
return Integer.valueOf(str2);
}
}
/*modify by sycheng add "".equals(str) */
protected static String getChildString(String str, Element elem) {
String str2 = getTextContent(str, elem);
if (null == str2 || "".equals(str2)||"null".equals(str)) {
return "";
} else {
return String.valueOf(str2);
}
}
protected static long getChildLong(String str, Element elem) {
String str2 = getTextContent(str, elem);
if (null == str2 || "".equals(str2)||"null".equals(str)) {
return -1;
} else {
return Long.valueOf(str2);
}
}
protected static String getString(String name, JSONObject json, boolean decode) {
String returnValue = null;
try {
returnValue = json.getString(name);
if (decode) {
try {
returnValue = URLDecoder.decode(returnValue, "UTF-8");
} catch (UnsupportedEncodingException ignore) {
}
}
} catch (JSONException ignore) {
// refresh_url could be missing
}
return returnValue;
}
protected static boolean getChildBoolean(String str, Element elem) {
String value = getTextContent(str, elem);
return Boolean.valueOf(value);
}
protected static Date getChildDate(String str, Element elem) throws HttpException {
return getChildDate(str, elem, "EEE MMM d HH:mm:ss z yyyy");
}
protected static Date getChildDate(String str, Element elem, String format) throws HttpException {
return parseDate(getChildText(str, elem),format);
}
protected static Date parseDate(String str, String format) throws HttpException{
if(str==null||"".equals(str)){
return null;
}
SimpleDateFormat sdf = formatMap.get(format);
if (null == sdf) {
sdf = new SimpleDateFormat(format, Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
formatMap.put(format, sdf);
}
try {
synchronized(sdf){
// SimpleDateFormat is not thread safe
return sdf.parse(str);
}
} catch (ParseException pe) {
throw new HttpException("Unexpected format(" + str + ") returned from sina.com.cn");
}
}
protected static int getInt(String key, JSONObject json) throws JSONException {
String str = json.getString(key);
if(null == str || "".equals(str)||"null".equals(str)){
return -1;
}
return Integer.parseInt(str);
}
protected static String getString(String key, JSONObject json) throws JSONException {
String str = json.getString(key);
if(null == str || "".equals(str)||"null".equals(str)){
return "";
}
return String.valueOf(str);
}
protected static long getLong(String key, JSONObject json) throws JSONException {
String str = json.getString(key);
if(null == str || "".equals(str)||"null".equals(str)){
return -1;
}
return Long.parseLong(str);
}
protected static boolean getBoolean(String key, JSONObject json) throws JSONException {
String str = json.getString(key);
if(null == str || "".equals(str)||"null".equals(str)){
return false;
}
return Boolean.valueOf(str);
}
public int getRateLimitLimit() {
return rateLimitLimit;
}
public int getRateLimitRemaining() {
return rateLimitRemaining;
}
public long getRateLimitReset() {
return rateLimitReset;
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.database.Cursor;
import android.util.Log;
import com.ch_linghu.fanfoudroid.db.MessageTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.db.UserInfoTable;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing Basic user information element
*/
public class User extends WeiboResponse implements java.io.Serializable {
static final String[] POSSIBLE_ROOT_NAMES = new String[]{"user", "sender", "recipient", "retweeting_user"};
private Weibo weibo;
private String id;
private String name;
private String screenName;
private String location;
private String description;
private String birthday;
private String gender;
private String profileImageUrl;
private String url;
private boolean isProtected;
private int followersCount;
private Date statusCreatedAt;
private String statusId = "";
private String statusText = null;
private String statusSource = null;
private boolean statusTruncated = false;
private String statusInReplyToStatusId = "";
private String statusInReplyToUserId = "";
private boolean statusFavorited = false;
private String statusInReplyToScreenName = null;
private String profileBackgroundColor;
private String profileTextColor;
private String profileLinkColor;
private String profileSidebarFillColor;
private String profileSidebarBorderColor;
private int friendsCount;
private Date createdAt;
private int favouritesCount;
private int utcOffset;
private String timeZone;
private String profileBackgroundImageUrl;
private String profileBackgroundTile;
private boolean following;
private boolean notificationEnabled;
private int statusesCount;
private boolean geoEnabled;
private boolean verified;
private static final long serialVersionUID = -6345893237975349030L;
/*package*/User(Response res, Weibo weibo) throws HttpException {
super(res);
Element elem = res.asDocument().getDocumentElement();
init(elem, weibo);
}
/*package*/public User(Response res, Element elem, Weibo weibo) throws HttpException {
super(res);
init(elem, weibo);
}
/*package*/public User(JSONObject json) throws HttpException {
super();
init(json);
}
/*package*/User(Response res) throws HttpException {
super();
init(res.asJSONObject());
}
User(){
}
private void init(JSONObject json) throws HttpException {
try {
id = json.getString("id");
name = json.getString("name");
screenName = json.getString("screen_name");
location = json.getString("location");
gender = json.getString("gender");
birthday = json.getString("birthday");
description = json.getString("description");
profileImageUrl = json.getString("profile_image_url");
url = json.getString("url");
isProtected = json.getBoolean("protected");
followersCount = json.getInt("followers_count");
profileBackgroundColor = json.getString("profile_background_color");
profileTextColor = json.getString("profile_text_color");
profileLinkColor = json.getString("profile_link_color");
profileSidebarFillColor = json.getString("profile_sidebar_fill_color");
profileSidebarBorderColor = json.getString("profile_sidebar_border_color");
friendsCount = json.getInt("friends_count");
createdAt = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
favouritesCount = json.getInt("favourites_count");
utcOffset = getInt("utc_offset", json);
// timeZone = json.getString("time_zone");
profileBackgroundImageUrl = json.getString("profile_background_image_url");
profileBackgroundTile = json.getString("profile_background_tile");
following = getBoolean("following", json);
notificationEnabled = getBoolean("notifications", json);
statusesCount = json.getInt("statuses_count");
if (!json.isNull("status")) {
JSONObject status = json.getJSONObject("status");
statusCreatedAt = parseDate(status.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
statusId = status.getString("id");
statusText = status.getString("text");
statusSource = status.getString("source");
statusTruncated = status.getBoolean("truncated");
// statusInReplyToStatusId = status.getString("in_reply_to_status_id");
statusInReplyToStatusId = status.getString("in_reply_to_lastmsg_id"); // 饭否不知为什么把这个参数的名称改了
statusInReplyToUserId = status.getString("in_reply_to_user_id");
statusFavorited = status.getBoolean("favorited");
statusInReplyToScreenName = status.getString("in_reply_to_screen_name");
}
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + json.toString(), jsone);
}
}
private void init(Element elem, Weibo weibo) throws HttpException {
this.weibo = weibo;
ensureRootNodeNameIs(POSSIBLE_ROOT_NAMES, elem);
id = getChildString("id", elem);
name = getChildText("name", elem);
screenName = getChildText("screen_name", elem);
location = getChildText("location", elem);
description = getChildText("description", elem);
profileImageUrl = getChildText("profile_image_url", elem);
url = getChildText("url", elem);
isProtected = getChildBoolean("protected", elem);
followersCount = getChildInt("followers_count", elem);
profileBackgroundColor = getChildText("profile_background_color", elem);
profileTextColor = getChildText("profile_text_color", elem);
profileLinkColor = getChildText("profile_link_color", elem);
profileSidebarFillColor = getChildText("profile_sidebar_fill_color", elem);
profileSidebarBorderColor = getChildText("profile_sidebar_border_color", elem);
friendsCount = getChildInt("friends_count", elem);
createdAt = getChildDate("created_at", elem);
favouritesCount = getChildInt("favourites_count", elem);
utcOffset = getChildInt("utc_offset", elem);
// timeZone = getChildText("time_zone", elem);
profileBackgroundImageUrl = getChildText("profile_background_image_url", elem);
profileBackgroundTile = getChildText("profile_background_tile", elem);
following = getChildBoolean("following", elem);
notificationEnabled = getChildBoolean("notifications", elem);
statusesCount = getChildInt("statuses_count", elem);
geoEnabled = getChildBoolean("geo_enabled", elem);
verified = getChildBoolean("verified", elem);
NodeList statuses = elem.getElementsByTagName("status");
if (statuses.getLength() != 0) {
Element status = (Element) statuses.item(0);
statusCreatedAt = getChildDate("created_at", status);
statusId = getChildString("id", status);
statusText = getChildText("text", status);
statusSource = getChildText("source", status);
statusTruncated = getChildBoolean("truncated", status);
statusInReplyToStatusId = getChildString("in_reply_to_status_id", status);
statusInReplyToUserId = getChildString("in_reply_to_user_id", status);
statusFavorited = getChildBoolean("favorited", status);
statusInReplyToScreenName = getChildText("in_reply_to_screen_name", status);
}
}
/**
* Returns the id of the user
*
* @return the id of the user
*/
public String getId() {
return id;
}
/**
* Returns the name of the user
*
* @return the name of the user
*/
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public String getBirthday() {
return birthday;
}
/**
* Returns the screen name of the user
*
* @return the screen name of the user
*/
public String getScreenName() {
return screenName;
}
/**
* Returns the location of the user
*
* @return the location of the user
*/
public String getLocation() {
return location;
}
/**
* Returns the description of the user
*
* @return the description of the user
*/
public String getDescription() {
return description;
}
/**
* Returns the profile image url of the user
*
* @return the profile image url of the user
*/
public URL getProfileImageURL() {
try {
return new URL(profileImageUrl);
} catch (MalformedURLException ex) {
return null;
}
}
/**
* Returns the url of the user
*
* @return the url of the user
*/
public URL getURL() {
try {
return new URL(url);
} catch (MalformedURLException ex) {
return null;
}
}
/**
* Test if the user status is protected
*
* @return true if the user status is protected
*/
public boolean isProtected() {
return isProtected;
}
/**
* Returns the number of followers
*
* @return the number of followers
* @since Weibo4J 1.0.4
*/
public int getFollowersCount() {
return followersCount;
}
//TODO: uncomment
// public DirectMessage sendDirectMessage(String text) throws WeiboException {
// return weibo.sendDirectMessage(this.getName(), text);
// }
public static List<User> constructUsers(Response res, Weibo weibo) throws HttpException {
Document doc = res.asDocument();
if (isRootNodeNilClasses(doc)) {
return new ArrayList<User>(0);
} else {
try {
ensureRootNodeNameIs("users", doc);
// NodeList list = doc.getDocumentElement().getElementsByTagName(
// "user");
// int size = list.getLength();
// List<User> users = new ArrayList<User>(size);
// for (int i = 0; i < size; i++) {
// users.add(new User(res, (Element) list.item(i), weibo));
// }
//去除掉嵌套的bug
NodeList list=doc.getDocumentElement().getChildNodes();
List<User> users = new ArrayList<User>(list.getLength());
Node node;
for(int i=0;i<list.getLength();i++){
node=list.item(i);
if(node.getNodeName().equals("user")){
users.add(new User(res, (Element) node, weibo));
}
}
return users;
} catch (HttpException te) {
if (isRootNodeNilClasses(doc)) {
return new ArrayList<User>(0);
} else {
throw te;
}
}
}
}
public static UserWapper constructWapperUsers(Response res, Weibo weibo) throws HttpException {
Document doc = res.asDocument();
if (isRootNodeNilClasses(doc)) {
return new UserWapper(new ArrayList<User>(0), 0, 0);
} else {
try {
ensureRootNodeNameIs("users_list", doc);
Element root = doc.getDocumentElement();
NodeList user = root.getElementsByTagName("users");
int length = user.getLength();
if (length == 0) {
return new UserWapper(new ArrayList<User>(0), 0, 0);
}
//
Element listsRoot = (Element) user.item(0);
NodeList list=listsRoot.getChildNodes();
List<User> users = new ArrayList<User>(list.getLength());
Node node;
for(int i=0;i<list.getLength();i++){
node=list.item(i);
if(node.getNodeName().equals("user")){
users.add(new User(res, (Element) node, weibo));
}
}
//
long previousCursor = getChildLong("previous_curosr", root);
long nextCursor = getChildLong("next_curosr", root);
if (nextCursor == -1) { // 兼容不同标签名称
nextCursor = getChildLong("nextCurosr", root);
}
return new UserWapper(users, previousCursor, nextCursor);
} catch (HttpException te) {
if (isRootNodeNilClasses(doc)) {
return new UserWapper(new ArrayList<User>(0), 0, 0);
} else {
throw te;
}
}
}
}
public static List<User> constructUsers(Response res) throws HttpException {
try {
JSONArray list = res.asJSONArray();
int size = list.length();
List<User> users = new ArrayList<User>(size);
for (int i = 0; i < size; i++) {
users.add(new User(list.getJSONObject(i)));
}
return users;
} catch (JSONException jsone) {
throw new HttpException(jsone);
} catch (HttpException te) {
throw te;
}
}
/**
*
* @param res
* @return
* @throws HttpException
*/
public static UserWapper constructWapperUsers(Response res) throws HttpException {
JSONObject jsonUsers = res.asJSONObject(); //asJSONArray();
try {
JSONArray user = jsonUsers.getJSONArray("users");
int size = user.length();
List<User> users = new ArrayList<User>(size);
for (int i = 0; i < size; i++) {
users.add(new User(user.getJSONObject(i)));
}
long previousCursor = jsonUsers.getLong("previous_curosr");
long nextCursor = jsonUsers.getLong("next_cursor");
if (nextCursor == -1) { // 兼容不同标签名称
nextCursor = jsonUsers.getLong("nextCursor");
}
return new UserWapper(users, previousCursor, nextCursor);
} catch (JSONException jsone) {
throw new HttpException(jsone);
}
}
/**
* @param res
* @return
* @throws HttpException
*/
static List<User> constructResult(Response res) throws HttpException {
JSONArray list = res.asJSONArray();
try {
int size = list.length();
List<User> users = new ArrayList<User>(size);
for (int i = 0; i < size; i++) {
users.add(new User(list.getJSONObject(i)));
}
return users;
} catch (JSONException e) {
}
return null;
}
/**
* @return created_at or null if the user is protected
* @since Weibo4J 1.1.0
*/
public Date getStatusCreatedAt() {
return statusCreatedAt;
}
/**
*
* @return status id or -1 if the user is protected
*/
public String getStatusId() {
return statusId;
}
/**
*
* @return status text or null if the user is protected
*/
public String getStatusText() {
return statusText;
}
/**
*
* @return source or null if the user is protected
* @since 1.1.4
*/
public String getStatusSource() {
return statusSource;
}
/**
*
* @return truncated or false if the user is protected
* @since 1.1.4
*/
public boolean isStatusTruncated() {
return statusTruncated;
}
/**
*
* @return in_reply_to_status_id or -1 if the user is protected
* @since 1.1.4
*/
public String getStatusInReplyToStatusId() {
return statusInReplyToStatusId;
}
/**
*
* @return in_reply_to_user_id or -1 if the user is protected
* @since 1.1.4
*/
public String getStatusInReplyToUserId() {
return statusInReplyToUserId;
}
/**
*
* @return favorited or false if the user is protected
* @since 1.1.4
*/
public boolean isStatusFavorited() {
return statusFavorited;
}
/**
*
* @return in_reply_to_screen_name or null if the user is protected
* @since 1.1.4
*/
public String getStatusInReplyToScreenName() {
return "" != statusInReplyToUserId ? statusInReplyToScreenName : null;
}
public String getProfileBackgroundColor() {
return profileBackgroundColor;
}
public String getProfileTextColor() {
return profileTextColor;
}
public String getProfileLinkColor() {
return profileLinkColor;
}
public String getProfileSidebarFillColor() {
return profileSidebarFillColor;
}
public String getProfileSidebarBorderColor() {
return profileSidebarBorderColor;
}
public int getFriendsCount() {
return friendsCount;
}
public Date getCreatedAt() {
return createdAt;
}
public int getFavouritesCount() {
return favouritesCount;
}
public int getUtcOffset() {
return utcOffset;
}
public String getTimeZone() {
return timeZone;
}
public String getProfileBackgroundImageUrl() {
return profileBackgroundImageUrl;
}
public String getProfileBackgroundTile() {
return profileBackgroundTile;
}
/**
*
*/
public boolean isFollowing() {
return following;
}
/**
* @deprecated use isNotificationsEnabled() instead
*/
public boolean isNotifications() {
return notificationEnabled;
}
/**
*
* @since Weibo4J 2.0.1
*/
public boolean isNotificationEnabled() {
return notificationEnabled;
}
public int getStatusesCount() {
return statusesCount;
}
/**
* @return the user is enabling geo location
* @since Weibo4J 2.0.10
*/
public boolean isGeoEnabled() {
return geoEnabled;
}
/**
* @return returns true if the user is a verified celebrity
* @since Weibo4J 2.0.10
*/
public boolean isVerified() {
return verified;
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public boolean equals(Object obj) {
if (null == obj) {
return false;
}
if (this == obj) {
return true;
}
return obj instanceof User && ((User) obj).id.equals(this.id);
}
@Override
public String toString() {
return "User{" +
"weibo=" + weibo +
", id=" + id +
", name='" + name + '\'' +
", screenName='" + screenName + '\'' +
", location='" + location + '\'' +
", description='" + description + '\'' +
", profileImageUrl='" + profileImageUrl + '\'' +
", url='" + url + '\'' +
", isProtected=" + isProtected +
", followersCount=" + followersCount +
", statusCreatedAt=" + statusCreatedAt +
", statusId=" + statusId +
", statusText='" + statusText + '\'' +
", statusSource='" + statusSource + '\'' +
", statusTruncated=" + statusTruncated +
", statusInReplyToStatusId=" + statusInReplyToStatusId +
", statusInReplyToUserId=" + statusInReplyToUserId +
", statusFavorited=" + statusFavorited +
", statusInReplyToScreenName='" + statusInReplyToScreenName + '\'' +
", profileBackgroundColor='" + profileBackgroundColor + '\'' +
", profileTextColor='" + profileTextColor + '\'' +
", profileLinkColor='" + profileLinkColor + '\'' +
", profileSidebarFillColor='" + profileSidebarFillColor + '\'' +
", profileSidebarBorderColor='" + profileSidebarBorderColor + '\'' +
", friendsCount=" + friendsCount +
", createdAt=" + createdAt +
", favouritesCount=" + favouritesCount +
", utcOffset=" + utcOffset +
// ", timeZone='" + timeZone + '\'' +
", profileBackgroundImageUrl='" + profileBackgroundImageUrl + '\'' +
", profileBackgroundTile='" + profileBackgroundTile + '\'' +
", following=" + following +
", notificationEnabled=" + notificationEnabled +
", statusesCount=" + statusesCount +
", geoEnabled=" + geoEnabled +
", verified=" + verified +
'}';
}
//TODO:增加从游标解析User的方法,用于和data里User转换一条数据
public static User parseUser(Cursor cursor){
if (null == cursor || 0 == cursor.getCount()||cursor.getCount()>1) {
Log.w("User.ParseUser", "Cann't parse Cursor, bacause cursor is null or empty.");
}
cursor.moveToFirst();
User u=new User();
u.id = cursor.getString(cursor.getColumnIndex(UserInfoTable._ID));
u.name = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_USER_NAME));
u.screenName = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_USER_SCREEN_NAME));
u.location = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_LOCALTION));
u.description = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_DESCRIPTION));
u.profileImageUrl = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_PROFILE_IMAGE_URL));
u.url = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_URL));
u.isProtected = (0 == cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_PROTECTED))) ? false : true;
u.followersCount = cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_FOLLOWERS_COUNT));
u.friendsCount = cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_FRIENDS_COUNT));
u.favouritesCount = cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_FAVORITES_COUNT));
u.statusesCount = cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_STATUSES_COUNT));
u.following = (0 == cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_FOLLOWING))) ? false : true;
try {
String createAtStr=cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_CREATED_AT));
if(createAtStr!=null){
u.createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(createAtStr);
}
} catch (ParseException e) {
Log.w("User", "Invalid created at data.");
}
return u;
}
public com.ch_linghu.fanfoudroid.data.User parseUser(){
com.ch_linghu.fanfoudroid.data.User user=new com.ch_linghu.fanfoudroid.data.User();
user.id=this.id;
user.name=this.name;
user.screenName=this.screenName;
user.location=this.location;
user.description=this.description;
user.profileImageUrl=this.profileImageUrl;
user.url=this.url;
user.isProtected=this.isProtected;
user.followersCount=this.followersCount;
user.friendsCount=this.friendsCount;
user.favoritesCount=this.favouritesCount;
user.statusesCount=this.statusesCount;
user.isFollowing=this.following;
user.createdAt = this.createdAt;
return user;
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import org.json.JSONException;
import org.json.JSONObject;
/**
* A data class representing Treand.
*
* @author Yusuke Yamamoto - yusuke at mac.com
* @since Weibo4J 2.0.2
*/
public class Trend implements java.io.Serializable{
private String name;
private String url = null;
private String query = null;
private static final long serialVersionUID = 1925956704460743946L;
public Trend(JSONObject json) throws JSONException {
this.name = json.getString("name");
if (!json.isNull("url")) {
this.url = json.getString("url");
}
if (!json.isNull("query")) {
this.query = json.getString("query");
}
}
public String getName() {
return name;
}
public String getUrl() {
return url;
}
public String getQuery() {
return query;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Trend)) return false;
Trend trend = (Trend) o;
if (!name.equals(trend.name)) return false;
if (query != null ? !query.equals(trend.query) : trend.query != null)
return false;
if (url != null ? !url.equals(trend.url) : trend.url != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + (url != null ? url.hashCode() : 0);
result = 31 * result + (query != null ? query.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Trend{" +
"name='" + name + '\'' +
", url='" + url + '\'' +
", query='" + query + '\'' +
'}';
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing one single retweet details.
*
* @author Yusuke Yamamoto - yusuke at mac.com
* @since Weibo4J 2.0.10
*/
public class RetweetDetails extends WeiboResponse implements
java.io.Serializable {
private long retweetId;
private Date retweetedAt;
private User retweetingUser;
static final long serialVersionUID = 1957982268696560598L;
public RetweetDetails(Response res, Weibo weibo) throws HttpException {
super(res);
Element elem = res.asDocument().getDocumentElement();
init(res, elem, weibo);
}
public RetweetDetails(JSONObject json) throws HttpException {
super();
init(json);
}
private void init(JSONObject json) throws HttpException{
try {
retweetId = json.getInt("retweetId");
retweetedAt = parseDate(json.getString("retweetedAt"), "EEE MMM dd HH:mm:ss z yyyy");
retweetingUser=new User(json.getJSONObject("retweetingUser"));
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + json.toString(), jsone);
}
}
/*package*/public RetweetDetails(Response res, Element elem, Weibo weibo) throws
HttpException {
super(res);
init(res, elem, weibo);
}
private void init(Response res, Element elem, Weibo weibo) throws
HttpException {
ensureRootNodeNameIs("retweet_details", elem);
retweetId = getChildLong("retweet_id", elem);
retweetedAt = getChildDate("retweeted_at", elem);
retweetingUser = new User(res, (Element) elem.getElementsByTagName("retweeting_user").item(0)
, weibo);
}
public long getRetweetId() {
return retweetId;
}
public Date getRetweetedAt() {
return retweetedAt;
}
public User getRetweetingUser() {
return retweetingUser;
}
/*modify by sycheng add json*/
/*package*/
static List<RetweetDetails> createRetweetDetails(Response res) throws HttpException {
try {
JSONArray list = res.asJSONArray();
int size = list.length();
List<RetweetDetails> retweets = new ArrayList<RetweetDetails>(size);
for (int i = 0; i < size; i++) {
retweets.add(new RetweetDetails(list.getJSONObject(i)));
}
return retweets;
} catch (JSONException jsone) {
throw new HttpException(jsone);
} catch (HttpException te) {
throw te;
}
}
/*package*/
static List<RetweetDetails> createRetweetDetails(Response res,
Weibo weibo) throws HttpException {
Document doc = res.asDocument();
if (isRootNodeNilClasses(doc)) {
return new ArrayList<RetweetDetails>(0);
} else {
try {
ensureRootNodeNameIs("retweets", doc);
NodeList list = doc.getDocumentElement().getElementsByTagName(
"retweet_details");
int size = list.getLength();
List<RetweetDetails> statuses = new ArrayList<RetweetDetails>(size);
for (int i = 0; i < size; i++) {
Element status = (Element) list.item(i);
statuses.add(new RetweetDetails(res, status, weibo));
}
return statuses;
} catch (HttpException te) {
ensureRootNodeNameIs("nil-classes", doc);
return new ArrayList<RetweetDetails>(0);
}
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof RetweetDetails)) return false;
RetweetDetails that = (RetweetDetails) o;
return retweetId == that.retweetId;
}
@Override
public int hashCode() {
int result = (int) (retweetId ^ (retweetId >>> 32));
result = 31 * result + retweetedAt.hashCode();
result = 31 * result + retweetingUser.hashCode();
return result;
}
@Override
public String toString() {
return "RetweetDetails{" +
"retweetId=" + retweetId +
", retweetedAt=" + retweetedAt +
", retweetingUser=" + retweetingUser +
'}';
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing sent/received direct message.
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class DirectMessage extends WeiboResponse implements java.io.Serializable {
private String id;
private String text;
private String sender_id;
private String recipient_id;
private Date created_at;
private String sender_screen_name;
private String recipient_screen_name;
private static final long serialVersionUID = -3253021825891789737L;
/*package*/DirectMessage(Response res, Weibo weibo) throws HttpException {
super(res);
init(res, res.asDocument().getDocumentElement(), weibo);
}
/*package*/DirectMessage(Response res, Element elem, Weibo weibo) throws HttpException {
super(res);
init(res, elem, weibo);
}
/*modify by sycheng add json call*/
/*package*/DirectMessage(JSONObject json) throws HttpException {
try {
id = json.getString("id");
text = json.getString("text");
sender_id = json.getString("sender_id");
recipient_id = json.getString("recipient_id");
created_at = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
sender_screen_name = json.getString("sender_screen_name");
recipient_screen_name = json.getString("recipient_screen_name");
if(!json.isNull("sender"))
sender = new User(json.getJSONObject("sender"));
if(!json.isNull("recipient"))
recipient = new User(json.getJSONObject("recipient"));
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + json.toString(), jsone);
}
}
private void init(Response res, Element elem, Weibo weibo) throws HttpException{
ensureRootNodeNameIs("direct_message", elem);
sender = new User(res, (Element) elem.getElementsByTagName("sender").item(0),
weibo);
recipient = new User(res, (Element) elem.getElementsByTagName("recipient").item(0),
weibo);
id = getChildString("id", elem);
text = getChildText("text", elem);
sender_id = getChildString("sender_id", elem);
recipient_id = getChildString("recipient_id", elem);
created_at = getChildDate("created_at", elem);
sender_screen_name = getChildText("sender_screen_name", elem);
recipient_screen_name = getChildText("recipient_screen_name", elem);
}
public String getId() {
return id;
}
public String getText() {
return text;
}
public String getSenderId() {
return sender_id;
}
public String getRecipientId() {
return recipient_id;
}
/**
* @return created_at
* @since Weibo4J 1.1.0
*/
public Date getCreatedAt() {
return created_at;
}
public String getSenderScreenName() {
return sender_screen_name;
}
public String getRecipientScreenName() {
return recipient_screen_name;
}
private User sender;
public User getSender() {
return sender;
}
private User recipient;
public User getRecipient() {
return recipient;
}
/*package*/
static List<DirectMessage> constructDirectMessages(Response res,
Weibo weibo) throws HttpException {
Document doc = res.asDocument();
if (isRootNodeNilClasses(doc)) {
return new ArrayList<DirectMessage>(0);
} else {
try {
ensureRootNodeNameIs("direct-messages", doc);
NodeList list = doc.getDocumentElement().getElementsByTagName(
"direct_message");
int size = list.getLength();
List<DirectMessage> messages = new ArrayList<DirectMessage>(size);
for (int i = 0; i < size; i++) {
Element status = (Element) list.item(i);
messages.add(new DirectMessage(res, status, weibo));
}
return messages;
} catch (HttpException te) {
if (isRootNodeNilClasses(doc)) {
return new ArrayList<DirectMessage>(0);
} else {
throw te;
}
}
}
}
/*package*/
static List<DirectMessage> constructDirectMessages(Response res
) throws HttpException {
JSONArray list= res.asJSONArray();
try {
int size = list.length();
List<DirectMessage> messages = new ArrayList<DirectMessage>(size);
for (int i = 0; i < size; i++) {
messages.add(new DirectMessage(list.getJSONObject(i)));
}
return messages;
} catch (JSONException jsone) {
throw new HttpException(jsone);
}
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public boolean equals(Object obj) {
if (null == obj) {
return false;
}
if (this == obj) {
return true;
}
return obj instanceof DirectMessage && ((DirectMessage) obj).id.equals(this.id);
}
@Override
public String toString() {
return "DirectMessage{" +
"id=" + id +
", text='" + text + '\'' +
", sender_id=" + sender_id +
", recipient_id=" + recipient_id +
", created_at=" + created_at +
", sender_screen_name='" + sender_screen_name + '\'' +
", recipient_screen_name='" + recipient_screen_name + '\'' +
", sender=" + sender +
", recipient=" + recipient +
'}';
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import org.json.JSONException;
import org.json.JSONObject;
import com.ch_linghu.fanfoudroid.http.HttpException;
/**
* A data class representing Basic user information element
*/
public class Photo extends WeiboResponse implements java.io.Serializable {
private Weibo weibo;
private String thumbnail_pic;
private String bmiddle_pic;
private String original_pic;
private boolean verified;
private static final long serialVersionUID = -6345893237975349030L;
public Photo(JSONObject json) throws HttpException {
super();
init(json);
}
private void init(JSONObject json) throws HttpException {
try {
//System.out.println(json);
thumbnail_pic = json.getString("thumburl");
bmiddle_pic = json.getString("imageurl");
original_pic = json.getString("largeurl");
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + json.toString(), jsone);
}
}
public String getThumbnail_pic() {
return thumbnail_pic;
}
public void setThumbnail_pic(String thumbnail_pic) {
this.thumbnail_pic = thumbnail_pic;
}
public String getBmiddle_pic() {
return bmiddle_pic;
}
public void setBmiddle_pic(String bmiddle_pic) {
this.bmiddle_pic = bmiddle_pic;
}
public String getOriginal_pic() {
return original_pic;
}
public void setOriginal_pic(String original_pic) {
this.original_pic = original_pic;
}
@Override
public String toString() {
return "Photo [thumbnail_pic=" + thumbnail_pic + ", bmiddle_pic="
+ bmiddle_pic + ", original_pic=" + original_pic + "]";
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Element;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing Weibo rate limit status
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class RateLimitStatus extends WeiboResponse {
private int remainingHits;
private int hourlyLimit;
private int resetTimeInSeconds;
private Date resetTime;
private static final long serialVersionUID = 933996804168952707L;
/* package */ RateLimitStatus(Response res) throws HttpException {
super(res);
Element elem = res.asDocument().getDocumentElement();
remainingHits = getChildInt("remaining-hits", elem);
hourlyLimit = getChildInt("hourly-limit", elem);
resetTimeInSeconds = getChildInt("reset-time-in-seconds", elem);
resetTime = getChildDate("reset-time", elem, "EEE MMM d HH:mm:ss z yyyy");
}
/*modify by sycheng add json call*/
/* package */ RateLimitStatus(Response res,Weibo w) throws HttpException {
super(res);
JSONObject json= res.asJSONObject();
try {
remainingHits = json.getInt("remaining_hits");
hourlyLimit = json.getInt("hourly_limit");
resetTimeInSeconds = json.getInt("reset_time_in_seconds");
resetTime = parseDate(json.getString("reset_time"), "EEE MMM dd HH:mm:ss z yyyy");
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + json.toString(), jsone);
}
}
public int getRemainingHits() {
return remainingHits;
}
public int getHourlyLimit() {
return hourlyLimit;
}
public int getResetTimeInSeconds() {
return resetTimeInSeconds;
}
/**
*
* @deprecated use getResetTime() instead
*/
@Deprecated
public Date getDateTime() {
return resetTime;
}
/**
* @since Weibo4J 2.0.9
*/
public Date getResetTime() {
return resetTime;
}
@Override
public String toString() {
StringBuilder sb=new StringBuilder();
sb.append("RateLimitStatus{remainingHits:");
sb.append(remainingHits);
sb.append(";hourlyLimit:");
sb.append(hourlyLimit);
sb.append(";resetTimeInSeconds:");
sb.append(resetTimeInSeconds);
sb.append(";resetTime:");
sb.append(resetTime);
sb.append("}");
return sb.toString();
}
}
| Java |
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.List;
import android.database.Cursor;
import android.os.Bundle;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity;
/**
* 随便看看
*
* @author jmx
*
*/
public class BrowseActivity extends TwitterCursorBaseActivity {
private static final String TAG = "BrowseActivity";
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState)) {
mNavbar.setHeaderTitle(getActivityTitle());
getTweetList().removeFooterView(mListFooter); // 随便看看没有获取更多功能
return true;
} else {
return false;
}
}
@Override
protected String getActivityTitle() {
return getResources().getString(R.string.page_title_browse);
}
@Override
public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) {
return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_BROWSE,
isUnread);
}
@Override
public String fetchMaxId() {
return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_BROWSE);
}
@Override
protected Cursor fetchMessages() {
return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_BROWSE);
}
@Override
public List<Status> getMessageSinceId(String maxId) throws HttpException {
return getApi().getPublicTimeline();
}
@Override
protected void markAllRead() {
getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_BROWSE);
}
@Override
public String fetchMinId() {
// 随便看看没有获取更多的功能
return null;
}
@Override
public List<Status> getMoreMessageFromId(String minId) throws HttpException {
// 随便看看没有获取更多的功能
return null;
}
@Override
public int getDatabaseType() {
return StatusTable.TYPE_BROWSE;
}
@Override
public String getUserId() {
return TwitterApplication.getMyselfId();
}
}
| Java |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.app.ImageManager;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.http.HttpClient;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.ui.module.TweetEdit;
import com.ch_linghu.fanfoudroid.util.FileHelper;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class WriteActivity extends BaseActivity {
// FIXME: for debug, delete me
private long startTime = -1;
private long endTime = -1;
public static final String NEW_TWEET_ACTION = "com.ch_linghu.fanfoudroid.NEW";
public static final String REPLY_TWEET_ACTION = "com.ch_linghu.fanfoudroid.REPLY";
public static final String REPOST_TWEET_ACTION = "com.ch_linghu.fanfoudroid.REPOST";
public static final String EXTRA_REPLY_TO_NAME = "reply_to_name";
public static final String EXTRA_REPLY_ID = "reply_id";
public static final String EXTRA_REPOST_ID = "repost_status_id";
private static final String TAG = "WriteActivity";
private static final String SIS_RUNNING_KEY = "running";
private static final String PREFS_NAME = "com.ch_linghu.fanfoudroid";
private static final int REQUEST_IMAGE_CAPTURE = 2;
private static final int REQUEST_PHOTO_LIBRARY = 3;
// View
private TweetEdit mTweetEdit;
private EditText mTweetEditText;
private TextView mProgressText;
private ImageButton mLocationButton;
private ImageButton chooseImagesButton;
private ImageButton mCameraButton;
private ProgressDialog dialog;
private NavBar mNavbar;
// Picture
private boolean withPic=false ;
private File mFile;
private ImageView mPreview;
private ImageView imageDelete;
private static final int MAX_BITMAP_SIZE = 400;
private File mImageFile;
private Uri mImageUri;
// Task
private GenericTask mSendTask;
private TaskListener mSendTaskListener = new TaskAdapter() {
@Override
public void onPreExecute(GenericTask task) {
onSendBegin();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
endTime = System.currentTimeMillis();
Log.d("LDS", "Sended a status in " + (endTime - startTime));
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
onSendSuccess();
} else if (result == TaskResult.IO_ERROR) {
onSendFailure();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return "SendTask";
}
};
private String _reply_id;
private String _repost_id;
private String _reply_to_name;
// sub menu
protected void openImageCaptureMenu() {
try {
// TODO: API < 1.6, images size too small
mImageFile = new File(FileHelper.getBasePath(), "upload.jpg");
mImageUri = Uri.fromFile(mImageFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
protected void openPhotoLibraryMenu() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_PHOTO_LIBRARY);
}
/**
* @deprecated 已废弃, 分解成两个按钮
*/
protected void createInsertPhotoDialog() {
final CharSequence[] items = {
getString(R.string.write_label_take_a_picture),
getString(R.string.write_label_choose_a_picture) };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.write_label_insert_picture));
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch (item) {
case 0:
openImageCaptureMenu();
break;
case 1:
openPhotoLibraryMenu();
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaColumns.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void getPic(Intent intent, Uri uri) {
// layout for picture mode
changeStyleWithPic();
withPic = true;
mFile = null;
mImageUri = uri;
if (uri.getScheme().equals("content")) {
mFile = new File(getRealPathFromURI(mImageUri));
} else {
mFile = new File(mImageUri.getPath());
}
// TODO:想将图片放在EditText左边
mPreview.setImageBitmap(createThumbnailBitmap(mImageUri,
MAX_BITMAP_SIZE));
if (mFile == null) {
updateProgress("Could not locate picture file. Sorry!");
disableEntry();
}
}
private File bitmapToFile(Bitmap bitmap) {
try {
File file = new File(FileHelper.getBasePath(), "upload.jpg");
FileOutputStream out = new FileOutputStream(file);
if (bitmap.compress(Bitmap.CompressFormat.JPEG,
ImageManager.DEFAULT_COMPRESS_QUALITY, out)) {
out.flush();
out.close();
}
return file;
} catch (FileNotFoundException e) {
Log.e(TAG, "Sorry, the file can not be created. " + e.getMessage());
return null;
} catch (IOException e) {
Log.e(TAG,
"IOException occurred when save upload file. "
+ e.getMessage());
return null;
}
}
private void changeStyleWithPic() {
// 修改布局 ,以前 图片居中,现在在左边
// mPreview.setLayoutParams(
// new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,
// LayoutParams.FILL_PARENT)
// );
mPreview.setVisibility(View.VISIBLE);
imageDelete.setVisibility(View.VISIBLE);
mTweetEditText.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 2f));
}
/**
* 制作微缩图
*
* @param uri
* @param size
* @return
*/
private Bitmap createThumbnailBitmap(Uri uri, int size) {
InputStream input = null;
try {
input = getContentResolver().openInputStream(uri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(input, null, options);
input.close();
// Compute the scale.
int scale = 1;
while ((options.outWidth / scale > size)
|| (options.outHeight / scale > size)) {
scale *= 2;
}
options.inJustDecodeBounds = false;
options.inSampleSize = scale;
input = getContentResolver().openInputStream(uri);
return BitmapFactory.decodeStream(input, null, options);
} catch (IOException e) {
Log.w(TAG, e);
return null;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
Log.w(TAG, e);
}
}
}
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)) {
// init View
setContentView(R.layout.write);
mNavbar = new NavBar(NavBar.HEADER_STYLE_WRITE, this);
// Intent & Action & Extras
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
Bundle extras = intent.getExtras();
String text = null;
Uri uri = null;
if (extras != null) {
String subject = extras.getString(Intent.EXTRA_SUBJECT);
text = extras.getString(Intent.EXTRA_TEXT);
uri = (Uri) (extras.get(Intent.EXTRA_STREAM));
if (!TextUtils.isEmpty(subject)) {
text = subject + " " + text;
}
if ((type != null && type.startsWith("text")) && uri != null) {
text = text + " " + uri.toString();
uri = null;
}
}
_reply_id = null;
_repost_id = null;
_reply_to_name = null;
// View
mProgressText = (TextView) findViewById(R.id.progress_text);
mTweetEditText = (EditText) findViewById(R.id.tweet_edit);
// TODO: @某人-- 类似饭否自动补全
ImageButton mAddUserButton = (ImageButton) findViewById(R.id.add_user);
mAddUserButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int start = mTweetEditText.getSelectionStart();
int end = mTweetEditText.getSelectionEnd();
mTweetEditText.getText().replace(Math.min(start, end),
Math.max(start, end), "@");
}
});
// 插入图片
chooseImagesButton = (ImageButton) findViewById(R.id.choose_images_button);
chooseImagesButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "chooseImagesButton onClick");
openPhotoLibraryMenu();
}
});
// 打开相机
mCameraButton = (ImageButton) findViewById(R.id.camera_button);
mCameraButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "mCameraButton onClick");
openImageCaptureMenu();
}
});
// With picture
imageDelete = (ImageView) findViewById(R.id.image_delete);
imageDelete.setOnClickListener(deleteListener);
mPreview = (ImageView) findViewById(R.id.preview);
if (Intent.ACTION_SEND.equals(intent.getAction()) && uri != null) {
getPic(intent, uri);
}
// Update status
mTweetEdit = new TweetEdit(mTweetEditText,
(TextView) findViewById(R.id.chars_text));
if (TwitterApplication.mPref.getBoolean(Preferences.USE_ENTER_SEND, false)){
mTweetEdit.setOnKeyListener(tweetEnterHandler);
}
mTweetEdit.addTextChangedListener(new MyTextWatcher(
WriteActivity.this));
if (NEW_TWEET_ACTION.equals(action) || Intent.ACTION_SEND.equals(action)){
if (!TextUtils.isEmpty(text)){
//始终将光标置于最末尾,以方便回复消息时保持@用户在最前面
EditText inputField = mTweetEdit.getEditText();
inputField.setTextKeepState(text);
Editable etext = inputField.getText();
int position = etext.length();
Selection.setSelection(etext, position);
}
}else if (REPLY_TWEET_ACTION.equals(action)) {
_reply_id = intent.getStringExtra(EXTRA_REPLY_ID);
_reply_to_name = intent.getStringExtra(EXTRA_REPLY_TO_NAME);
if (!TextUtils.isEmpty(text)){
String reply_to_name = "@"+_reply_to_name + " ";
String other_replies = "";
for (String mention : TextHelper.getMentions(text)){
//获取名字时不包括自己和回复对象
if (!mention.equals(TwitterApplication.getMyselfName()) &&
!mention.equals(_reply_to_name)){
other_replies += "@"+mention+" ";
}
}
EditText inputField = mTweetEdit.getEditText();
inputField.setTextKeepState(reply_to_name + other_replies);
//将除了reply_to_name的其他名字默认选中
Editable etext = inputField.getText();
int start = reply_to_name.length();
int stop = etext.length();
Selection.setSelection(etext, start, stop);
}
}else if (REPOST_TWEET_ACTION.equals(action)) {
if (!TextUtils.isEmpty(text)){
// 如果是转发消息,则根据用户习惯,将光标放置在转发消息的头部或尾部
SharedPreferences prefereces = getPreferences();
boolean isAppendToTheBeginning = prefereces.getBoolean(
Preferences.RT_INSERT_APPEND, true);
EditText inputField = mTweetEdit.getEditText();
inputField.setTextKeepState(text);
Editable etext = inputField.getText();
int position = (isAppendToTheBeginning) ? 0 : etext.length();
Selection.setSelection(etext, position);
}
}
mLocationButton = (ImageButton) findViewById(R.id.location_button);
mLocationButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(WriteActivity.this, "LBS地理定位功能开发中, 敬请期待",
Toast.LENGTH_SHORT).show();
}
});
Button mTopSendButton = (Button) findViewById(R.id.top_send_btn);
mTopSendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
doSend();
}
});
return true;
} else {
return false;
}
}
private View.OnClickListener deleteListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = getIntent();
intent.setAction(null);
withPic = false;
mPreview.setVisibility(View.INVISIBLE);
imageDelete.setVisibility(View.INVISIBLE);
}
};
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause.");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart.");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume.");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart.");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop.");
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mSendTask != null
&& mSendTask.getStatus() == GenericTask.Status.RUNNING) {
// Doesn't really cancel execution (we let it continue running).
// See the SendTask code for more details.
mSendTask.cancel(true);
}
// Don't need to cancel FollowersTask (assuming it ends properly).
if (dialog != null) {
dialog.dismiss();
}
super.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mSendTask != null
&& mSendTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
public static Intent createNewTweetIntent(String text) {
Intent intent = new Intent(NEW_TWEET_ACTION);
intent.putExtra(Intent.EXTRA_TEXT, text);
intent.putExtra(Intent.EXTRA_SUBJECT, "");
return intent;
}
public static Intent createNewReplyIntent(String tweetText, String screenName, String replyId) {
Intent intent = new Intent(WriteActivity.REPLY_TWEET_ACTION);
intent.putExtra(Intent.EXTRA_SUBJECT, "");
intent.putExtra(Intent.EXTRA_TEXT, TextHelper.getSimpleTweetText(tweetText));
intent.putExtra(WriteActivity.EXTRA_REPLY_TO_NAME, screenName);
intent.putExtra(WriteActivity.EXTRA_REPLY_ID, replyId);
return intent;
}
public static Intent createNewRepostIntent(Context content,
String tweetText, String screenName, String repostId) {
SharedPreferences mPreferences = PreferenceManager
.getDefaultSharedPreferences(content);
String prefix = mPreferences.getString(Preferences.RT_PREFIX_KEY,
content.getString(R.string.pref_rt_prefix_default));
String retweet = " " + prefix + " @" + screenName + " "
+ TextHelper.getSimpleTweetText(tweetText);
Intent intent = new Intent(WriteActivity.REPOST_TWEET_ACTION);
intent.putExtra(Intent.EXTRA_SUBJECT, "");
intent.putExtra(Intent.EXTRA_TEXT, retweet);
intent.putExtra(WriteActivity.EXTRA_REPOST_ID, repostId);
return intent;
}
public static Intent createImageIntent(Activity activity, Uri uri) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, uri);
try {
WriteActivity writeActivity = (WriteActivity) activity;
intent.putExtra(Intent.EXTRA_TEXT,
writeActivity.mTweetEdit.getText());
intent.putExtra(WriteActivity.EXTRA_REPLY_TO_NAME,
writeActivity._reply_to_name);
intent.putExtra(WriteActivity.EXTRA_REPLY_ID,
writeActivity._reply_id);
intent.putExtra(WriteActivity.EXTRA_REPOST_ID,
writeActivity._repost_id);
} catch (ClassCastException e) {
// do nothing
}
return intent;
}
private class MyTextWatcher implements TextWatcher {
private WriteActivity _activity;
public MyTextWatcher(WriteActivity activity) {
_activity = activity;
}
@Override
public void afterTextChanged(Editable s) {
if (s.length() == 0) {
_activity._reply_id = null;
_activity._reply_to_name = null;
_activity._repost_id = null;
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
}
private View.OnKeyListener tweetEnterHandler = new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER
|| keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
if (event.getAction() == KeyEvent.ACTION_UP) {
WriteActivity t = (WriteActivity) (v.getContext());
doSend();
}
return true;
}
return false;
}
};
private void doSend() {
Log.d(TAG, "dosend "+withPic);
startTime = System.currentTimeMillis();
Log.d(TAG, String.format("doSend, reply_id=%s", _reply_id));
if (mSendTask != null
&& mSendTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
String status = mTweetEdit.getText().toString();
if (!TextUtils.isEmpty(status) || withPic) {
int mode = SendTask.TYPE_NORMAL;
if (withPic) {
mode = SendTask.TYPE_PHOTO;
} else if (null != _reply_id) {
mode = SendTask.TYPE_REPLY;
} else if (null != _repost_id) {
mode = SendTask.TYPE_REPOST;
}
mSendTask = new SendTask();
mSendTask.setListener(mSendTaskListener);
TaskParams params = new TaskParams();
params.put("mode", mode);
mSendTask.execute(params);
} else {
updateProgress(getString(R.string.page_text_is_null));
}
}
}
private class SendTask extends GenericTask {
public static final int TYPE_NORMAL = 0;
public static final int TYPE_REPLY = 1;
public static final int TYPE_REPOST = 2;
public static final int TYPE_PHOTO = 3;
@Override
protected TaskResult _doInBackground(TaskParams... params) {
TaskParams param = params[0];
try {
String status = mTweetEdit.getText().toString();
int mode = param.getInt("mode");
Log.d(TAG, "Send Status. Mode : " + mode);
// Send status in different way
switch (mode) {
case TYPE_REPLY:
// 增加容错性,即使reply_id为空依然允许发送
if (null == WriteActivity.this._reply_id) {
Log.e(TAG,
"Cann't send status in REPLY mode, reply_id is null");
}
getApi().updateStatus(status, WriteActivity.this._reply_id);
break;
case TYPE_REPOST:
// 增加容错性,即使repost_id为空依然允许发送
if (null == WriteActivity.this._repost_id) {
Log.e(TAG,
"Cann't send status in REPOST mode, repost_id is null");
}
getApi().repost(status, WriteActivity.this._repost_id);
break;
case TYPE_PHOTO:
if (null != mFile) {
// Compress image
try {
mFile = getImageManager().compressImage(mFile, 100);
//ImageManager.DEFAULT_COMPRESS_QUALITY);
} catch (IOException ioe) {
Log.e(TAG, "Cann't compress images.");
}
getApi().updateStatus(status, mFile);
} else {
Log.e(TAG,
"Cann't send status in PICTURE mode, photo is null");
}
break;
case TYPE_NORMAL:
default:
getApi().updateStatus(status); // just send a status
break;
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
if (e.getStatusCode() == HttpClient.NOT_AUTHORIZED) {
return TaskResult.AUTH_ERROR;
}
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
private ImageManager getImageManager() {
return TwitterApplication.mImageLoader.getImageManager();
}
}
private void onSendBegin() {
disableEntry();
dialog = ProgressDialog.show(WriteActivity.this, "",
getString(R.string.page_status_updating), true);
if (dialog != null) {
dialog.setCancelable(false);
}
updateProgress(getString(R.string.page_status_updating));
}
private void onSendSuccess() {
if (dialog != null) {
dialog.setMessage(getString(R.string.page_status_update_success));
dialog.dismiss();
}
_reply_id = null;
_repost_id = null;
updateProgress(getString(R.string.page_status_update_success));
enableEntry();
// FIXME: 不理解这段代码的含义,暂时注释掉
// try {
// Thread.currentThread();
// Thread.sleep(500);
// updateProgress("");
// } catch (InterruptedException e) {
// Log.d(TAG, e.getMessage());
// }
updateProgress("");
// 发送成功就自动关闭界面
finish();
// 关闭软键盘
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mTweetEdit.getEditText().getWindowToken(),
0);
}
private void onSendFailure() {
dialog.setMessage(getString(R.string.page_status_unable_to_update));
dialog.dismiss();
updateProgress(getString(R.string.page_status_unable_to_update));
enableEntry();
}
private void enableEntry() {
mTweetEdit.setEnabled(true);
mLocationButton.setEnabled(true);
chooseImagesButton.setEnabled(true);
}
private void disableEntry() {
mTweetEdit.setEnabled(false);
mLocationButton.setEnabled(false);
chooseImagesButton.setEnabled(false);
}
// UI helpers.
private void updateProgress(String progress) {
mProgressText.setText(progress);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Intent intent = WriteActivity.createImageIntent(this, mImageUri);
//照相完后不重新起一个WriteActivity
getPic(intent, mImageUri);
/*intent.setClass(this, WriteActivity.class);
startActivity(intent);
// 打开发送图片界面后将自身关闭
finish();*/
} else if (requestCode == REQUEST_PHOTO_LIBRARY
&& resultCode == RESULT_OK) {
mImageUri = data.getData();
Intent intent = WriteActivity.createImageIntent(this, mImageUri);
//选图片后不重新起一个WriteActivity
getPic(intent, mImageUri);
/*intent.setClass(this, WriteActivity.class);
startActivity(intent);
// 打开发送图片界面后将自身关闭
finish();*/
}
}
} | Java |
package com.ch_linghu.fanfoudroid;
import com.ch_linghu.fanfoudroid.app.Preferences;
import android.app.Activity;
import android.content.ComponentName;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AboutActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
if (TwitterApplication.mPref.getBoolean(
Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
//set real version
ComponentName comp = new ComponentName(this, getClass());
PackageInfo pinfo = null;
try {
pinfo = getPackageManager().getPackageInfo(comp.getPackageName(), 0);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TextView version = (TextView)findViewById(R.id.version);
version.setText(String.format("v %s", pinfo.versionName));
//bind button click event
Button okBtn = (Button)findViewById(R.id.ok_btn);
okBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
| Java |
package com.ch_linghu.fanfoudroid;
import java.util.HashSet;
//import org.acra.ReportingInteractionMode;
//import org.acra.annotation.ReportsCrashes;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.preference.PreferenceManager;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.fanfou.Configuration;
import com.ch_linghu.fanfoudroid.fanfou.User;
import com.ch_linghu.fanfoudroid.fanfou.Weibo;
import com.ch_linghu.fanfoudroid.http.HttpException;
//@ReportsCrashes(formKey="dHowMk5LMXQweVJkWGthb1E1T1NUUHc6MQ",
// mode = ReportingInteractionMode.NOTIFICATION,
// resNotifTickerText = R.string.crash_notif_ticker_text,
// resNotifTitle = R.string.crash_notif_title,
// resNotifText = R.string.crash_notif_text,
// resNotifIcon = android.R.drawable.stat_notify_error, // optional. default is a warning sign
// resDialogText = R.string.crash_dialog_text,
// resDialogIcon = android.R.drawable.ic_dialog_info, //optional. default is a warning sign
// resDialogTitle = R.string.crash_dialog_title, // optional. default is your application name
// resDialogCommentPrompt = R.string.crash_dialog_comment_prompt, // optional. when defined, adds a user text field input with this text resource as a label
// resDialogOkToast = R.string.crash_dialog_ok_toast // optional. displays a Toast message when the user accepts to send a report.
//)
public class TwitterApplication extends Application {
public static final String TAG = "TwitterApplication";
// public static ImageManager mImageManager;
public static LazyImageLoader mImageLoader;
public static TwitterDatabase mDb;
public static Weibo mApi; // new API
public static Context mContext;
public static SharedPreferences mPref;
public static int networkType = 0;
public final static boolean DEBUG = Configuration.getDebug();
// FIXME:获取登录用户id, 据肉眼观察,刚注册的用户系统分配id都是~开头的,因为不知道
// 用户何时去修改这个ID,目前只有把所有以~开头的ID在每次需要UserId时都去服务器
// 取一次数据,看看新的ID是否已经设定,判断依据是是否以~开头。这么判断会把有些用户
// 就是把自己ID设置的以~开头的造成,每次都需要去服务器取数。
// 只是简单处理了mPref没有CURRENT_USER_ID的情况,因为用户在登陆时,肯定会记一个CURRENT_USER_ID
// 到mPref.
private static void fetchMyselfInfo() {
User myself;
try {
myself = TwitterApplication.mApi.showUser(TwitterApplication.mApi.getUserId());
TwitterApplication.mPref.edit().putString(
Preferences.CURRENT_USER_ID, myself.getId()).commit();
TwitterApplication.mPref.edit().putString(
Preferences.CURRENT_USER_SCREEN_NAME, myself.getScreenName()).commit();
} catch (HttpException e) {
e.printStackTrace();
}
}
public static String getMyselfId() {
if (!mPref.contains(Preferences.CURRENT_USER_ID)
|| mPref.getString(Preferences.CURRENT_USER_ID, "~")
.startsWith("~")) {
fetchMyselfInfo();
}
return mPref.getString(Preferences.CURRENT_USER_ID, "~");
}
public static String getMyselfName() {
if (!mPref.contains(Preferences.CURRENT_USER_ID)
|| !mPref.contains(Preferences.CURRENT_USER_SCREEN_NAME)
|| mPref.getString(Preferences.CURRENT_USER_ID, "~")
.startsWith("~")) {
fetchMyselfInfo();
}
return mPref.getString(Preferences.CURRENT_USER_SCREEN_NAME, "");
}
@Override
public void onCreate() {
// FIXME: StrictMode类在1.6以下的版本中没有,会导致类加载失败。
// 因此将这些代码设成关闭状态,仅在做性能调试时才打开。
// //NOTE: StrictMode模式需要2.3+ API支持。
// if (DEBUG){
// StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
// .detectAll()
// .penaltyLog()
// .build());
// StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
// .detectAll()
// .penaltyLog()
// .build());
// }
super.onCreate();
mContext = this.getApplicationContext();
// mImageManager = new ImageManager(this);
mImageLoader = new LazyImageLoader();
mApi = new Weibo();
mDb = TwitterDatabase.getInstance(this);
mPref = PreferenceManager.getDefaultSharedPreferences(this);
String username = mPref.getString(Preferences.USERNAME_KEY, "");
String password = mPref.getString(Preferences.PASSWORD_KEY, "");
password = LoginActivity.decryptPassword(password);
if (Weibo.isValidCredentials(username, password)) {
mApi.setCredentials(username, password); // Setup API and HttpClient
}
// 为cmwap用户设置代理上网
String type = getNetworkType();
if (null != type && type.equalsIgnoreCase("cmwap")) {
Toast.makeText(this, "您当前正在使用cmwap网络上网.", Toast.LENGTH_SHORT);
mApi.getHttpClient().setProxy("10.0.0.172", 80, "http");
}
}
public String getNetworkType() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
//NetworkInfo mobNetInfo = connectivityManager
// .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (activeNetInfo != null){
return activeNetInfo.getExtraInfo(); // 接入点名称: 此名称可被用户任意更改 如: cmwap, cmnet,
// internet ...
}else{
return null;
}
}
@Override
public void onTerminate() {
//FIXME: 根据android文档,onTerminate不会在真实机器上被执行到
//因此这些清理动作需要再找合适的地方放置,以确保执行。
cleanupImages();
mDb.close();
Toast.makeText(this, "exit app", Toast.LENGTH_LONG);
super.onTerminate();
}
private void cleanupImages() {
HashSet<String> keepers = new HashSet<String>();
Cursor cursor = mDb.fetchAllTweets(StatusTable.TYPE_HOME);
if (cursor.moveToFirst()) {
int imageIndex = cursor
.getColumnIndexOrThrow(StatusTable.PROFILE_IMAGE_URL);
do {
keepers.add(cursor.getString(imageIndex));
} while (cursor.moveToNext());
}
cursor.close();
cursor = mDb.fetchAllDms(-1);
if (cursor.moveToFirst()) {
int imageIndex = cursor
.getColumnIndexOrThrow(StatusTable.PROFILE_IMAGE_URL);
do {
keepers.add(cursor.getString(imageIndex));
} while (cursor.moveToNext());
}
cursor.close();
mImageLoader.getImageManager().cleanup(keepers);
}
}
| Java |
package com.ch_linghu.fanfoudroid.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.text.Html;
import android.text.util.Linkify;
import android.util.Log;
import android.widget.TextView;
import android.widget.TextView.BufferType;
public class TextHelper {
private static final String TAG = "TextHelper";
public static String stringifyStream(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
return sb.toString();
}
private static HashMap<String, String> _userLinkMapping = new HashMap<String, String>();
private static final Pattern NAME_MATCHER = Pattern.compile("@.+?\\s");
private static final Linkify.MatchFilter NAME_MATCHER_MATCH_FILTER = new Linkify.MatchFilter() {
@Override
public final boolean acceptMatch(final CharSequence s, final int start,
final int end) {
String name = s.subSequence(start + 1, end).toString().trim();
boolean result = _userLinkMapping.containsKey(name);
return result;
}
};
private static final Linkify.TransformFilter NAME_MATCHER_TRANSFORM_FILTER = new Linkify.TransformFilter() {
@Override
public String transformUrl(Matcher match, String url) {
// TODO Auto-generated method stub
String name = url.subSequence(1, url.length()).toString().trim();
return _userLinkMapping.get(name);
}
};
private static final String TWITTA_USER_URL = "twitta://users/";
public static void linkifyUsers(TextView view) {
Linkify.addLinks(view, NAME_MATCHER, TWITTA_USER_URL,
NAME_MATCHER_MATCH_FILTER, NAME_MATCHER_TRANSFORM_FILTER);
}
private static final Pattern TAG_MATCHER = Pattern.compile("#\\w+#");
private static final Linkify.TransformFilter TAG_MATCHER_TRANSFORM_FILTER = new Linkify.TransformFilter() {
@Override
public final String transformUrl(Matcher match, String url) {
String result = url.substring(1, url.length() - 1);
return "%23" + result + "%23";
}
};
private static final String TWITTA_SEARCH_URL = "twitta://search/";
public static void linkifyTags(TextView view) {
Linkify.addLinks(view, TAG_MATCHER, TWITTA_SEARCH_URL, null,
TAG_MATCHER_TRANSFORM_FILTER);
}
private static Pattern USER_LINK = Pattern
.compile("@<a href=\"http:\\/\\/fanfou\\.com\\/(.*?)\" class=\"former\">(.*?)<\\/a>");
private static String preprocessText(String text) {
// 处理HTML格式返回的用户链接
Matcher m = USER_LINK.matcher(text);
while (m.find()) {
_userLinkMapping.put(m.group(2), m.group(1));
Log.d(TAG,
String.format("Found mapping! %s=%s", m.group(2),
m.group(1)));
}
// 将User Link的连接去掉
StringBuffer sb = new StringBuffer();
m = USER_LINK.matcher(text);
while (m.find()) {
m.appendReplacement(sb, "@$2");
}
m.appendTail(sb);
return sb.toString();
}
public static String getSimpleTweetText(String text) {
return Html.fromHtml(text).toString();
}
public static void setSimpleTweetText(TextView textView, String text) {
String processedText = getSimpleTweetText(text);
textView.setText(processedText);
}
public static void setTweetText(TextView textView, String text) {
String processedText = preprocessText(text);
textView.setText(Html.fromHtml(processedText), BufferType.SPANNABLE);
Linkify.addLinks(textView, Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES);
linkifyUsers(textView);
linkifyTags(textView);
_userLinkMapping.clear();
}
/**
* 从消息中获取全部提到的人,将它们按先后顺序放入一个列表
* @param msg 消息文本
* @return 消息中@的人的列表,按顺序存放
*/
public static List<String> getMentions(String msg){
ArrayList<String> mentionList = new ArrayList<String>();
final Pattern p = Pattern.compile("@(.*?)\\s");
final int MAX_NAME_LENGTH = 12; //简化判断,无论中英文最长12个字
Matcher m = p.matcher(msg);
while(m.find()){
String mention = m.group(1);
//过长的名字就忽略(不是合法名字) +1是为了补上“@”所占的长度
if (mention.length() <= MAX_NAME_LENGTH+1){
//避免重复名字
if (!mentionList.contains(mention)){
mentionList.add(m.group(1));
}
}
}
return mentionList;
}
}
| Java |
package com.ch_linghu.fanfoudroid.util;
import java.io.InputStream;
import java.io.OutputStream;
public class StreamUtils {
public static void CopyStream(InputStream is, OutputStream os)
{
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}
} | Java |
package com.ch_linghu.fanfoudroid.util;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.HashMap;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
/**
* Debug Timer
*
* Usage:
* --------------------------------
* DebugTimer.start();
* DebugTimer.mark("my_mark1"); // optional
* DebugTimer.stop();
*
* System.out.println(DebugTimer.__toString()); // get report
* --------------------------------
*
* @author LDS
*/
public class DebugTimer {
public static final int START = 0;
public static final int END = 1;
private static HashMap<String, Long> mTime = new HashMap<String, Long>();
private static long mStartTime = 0;
private static long mLastTime = 0;
/**
* Start a timer
*/
public static void start() {
reset();
mStartTime = touch();
}
/**
* Mark current time
*
* @param tag mark tag
* @return
*/
public static long mark(String tag) {
long time = System.currentTimeMillis() - mStartTime;
mTime.put(tag, time);
return time;
}
/**
* Mark current time
*
* @param tag mark tag
* @return
*/
public static long between(String tag, int startOrEnd) {
if(TwitterApplication.DEBUG){
Log.v("DEBUG", tag + " " + startOrEnd);
}
switch (startOrEnd) {
case START:
return mark(tag);
case END:
long time = System.currentTimeMillis() - mStartTime - get(tag, mStartTime);
mTime.put(tag, time);
//touch();
return time;
default:
return -1;
}
}
public static long betweenStart(String tag) {
return between(tag, START);
}
public static long betweenEnd(String tag) {
return between(tag, END);
}
/**
* Stop timer
*
* @return result
*/
public static String stop() {
mTime.put("_TOTLE", touch() - mStartTime);
return __toString();
}
public static String stop(String tag) {
mark(tag);
return stop();
}
/**
* Get a mark time
*
* @param tag mark tag
* @return time(milliseconds) or NULL
*/
public static long get(String tag) {
return get(tag, 0);
}
public static long get(String tag, long defaultValue) {
if (mTime.containsKey(tag)) {
return mTime.get(tag);
}
return defaultValue;
}
/**
* Reset timer
*/
public static void reset() {
mTime = new HashMap<String, Long>();
mStartTime = 0;
mLastTime = 0;
}
/**
* static toString()
*
* @return
*/
public static String __toString() {
return "Debuger [time =" + mTime.toString() + "]";
}
private static long touch() {
return mLastTime = System.currentTimeMillis();
}
public static DebugProfile[] getProfile() {
DebugProfile[] profile = new DebugProfile[mTime.size()];
long totel = mTime.get("_TOTLE");
int i = 0;
for (String key : mTime.keySet()) {
long time = mTime.get(key);
profile[i] = new DebugProfile(key, time, time/(totel*1.0) );
i++;
}
try {
Arrays.sort(profile);
} catch (NullPointerException e) {
// in case item is null, do nothing
}
return profile;
}
public static String getProfileAsString() {
StringBuilder sb = new StringBuilder();
for (DebugProfile p : getProfile()) {
sb.append("TAG: ");
sb.append(p.tag);
sb.append("\t INC: ");
sb.append(p.inc);
sb.append("\t INCP: ");
sb.append(p.incPercent);
sb.append("\n");
}
return sb.toString();
}
@Override
public String toString() {
return __toString();
}
}
class DebugProfile implements Comparable<DebugProfile> {
private static NumberFormat percent = NumberFormat.getPercentInstance();
public String tag;
public long inc;
public String incPercent;
public DebugProfile(String tag, long inc, double incPercent) {
this.tag = tag;
this.inc = inc;
percent = new DecimalFormat("0.00#%");
this.incPercent = percent.format(incPercent);
}
@Override
public int compareTo(DebugProfile o) {
// TODO Auto-generated method stub
return (int) (o.inc - this.inc);
}
}
| Java |
package com.ch_linghu.fanfoudroid.util;
import java.io.File;
import java.io.IOException;
import android.os.Environment;
/**
* 对SD卡文件的管理
* @author ch.linghu
*
*/
public class FileHelper {
private static final String TAG = "FileHelper";
private static final String BASE_PATH="fanfoudroid";
public static File getBasePath() throws IOException{
File basePath = new File(Environment.getExternalStorageDirectory(),
BASE_PATH);
if (!basePath.exists()){
if (!basePath.mkdirs()){
throw new IOException(String.format("%s cannot be created!", basePath.toString()));
}
}
if (!basePath.isDirectory()){
throw new IOException(String.format("%s is not a directory!", basePath.toString()));
}
return basePath;
}
}
| Java |
package com.ch_linghu.fanfoudroid.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import android.util.Log;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
public class DateTimeHelper {
private static final String TAG = "DateTimeHelper";
// Wed Dec 15 02:53:36 +0000 2010
public static final DateFormat TWITTER_DATE_FORMATTER = new SimpleDateFormat(
"E MMM d HH:mm:ss Z yyyy", Locale.US);
public static final DateFormat TWITTER_SEARCH_API_DATE_FORMATTER = new SimpleDateFormat(
"E, d MMM yyyy HH:mm:ss Z", Locale.US); // TODO: Z -> z ?
public static final Date parseDateTime(String dateString) {
try {
Log.v(TAG, String.format("in parseDateTime, dateString=%s", dateString));
return TWITTER_DATE_FORMATTER.parse(dateString);
} catch (ParseException e) {
Log.w(TAG, "Could not parse Twitter date string: " + dateString);
return null;
}
}
// Handle "yyyy-MM-dd'T'HH:mm:ss.SSS" from sqlite
public static final Date parseDateTimeFromSqlite(String dateString) {
try {
Log.v(TAG, String.format("in parseDateTime, dateString=%s", dateString));
return TwitterDatabase.DB_DATE_FORMATTER.parse(dateString);
} catch (ParseException e) {
Log.w(TAG, "Could not parse Twitter date string: " + dateString);
return null;
}
}
public static final Date parseSearchApiDateTime(String dateString) {
try {
return TWITTER_SEARCH_API_DATE_FORMATTER.parse(dateString);
} catch (ParseException e) {
Log.w(TAG, "Could not parse Twitter search date string: "
+ dateString);
return null;
}
}
public static final DateFormat AGO_FULL_DATE_FORMATTER = new SimpleDateFormat(
"yyyy-MM-dd HH:mm");
public static String getRelativeDate(Date date) {
Date now = new Date();
String prefix = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_prefix);
String sec = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_sec);
String min = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_min);
String hour = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_hour);
String day = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_day);
String suffix = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_suffix);
// Seconds.
long diff = (now.getTime() - date.getTime()) / 1000;
if (diff < 0) {
diff = 0;
}
if (diff < 60) {
return diff + sec + suffix;
}
// Minutes.
diff /= 60;
if (diff < 60) {
return prefix + diff + min + suffix;
}
// Hours.
diff /= 60;
if (diff < 24) {
return prefix + diff + hour + suffix;
}
return AGO_FULL_DATE_FORMATTER.format(date);
}
public static long getNowTime() {
return Calendar.getInstance().getTime().getTime();
}
}
| Java |
/***
Copyright (c) 2008-2009 CommonsWare, LLC
Portions (c) 2009 Google, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.commonsware.cwac.sacklist;
import java.util.ArrayList;
import java.util.List;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
/**
* Adapter that simply returns row views from a list.
*
* If you supply a size, you must implement newView(), to
* create a required view. The adapter will then cache these
* views.
*
* If you supply a list of views in the constructor, that
* list will be used directly. If any elements in the list
* are null, then newView() will be called just for those
* slots.
*
* Subclasses may also wish to override areAllItemsEnabled()
* (default: false) and isEnabled() (default: false), if some
* of their rows should be selectable.
*
* It is assumed each view is unique, and therefore will not
* get recycled.
*
* Note that this adapter is not designed for long lists. It
* is more for screens that should behave like a list. This
* is particularly useful if you combine this with other
* adapters (e.g., SectionedAdapter) that might have an
* arbitrary number of rows, so it all appears seamless.
*/
public class SackOfViewsAdapter extends BaseAdapter {
private List<View> views=null;
/**
* Constructor creating an empty list of views, but with
* a specified count. Subclasses must override newView().
*/
public SackOfViewsAdapter(int count) {
super();
views=new ArrayList<View>(count);
for (int i=0;i<count;i++) {
views.add(null);
}
}
/**
* Constructor wrapping a supplied list of views.
* Subclasses must override newView() if any of the elements
* in the list are null.
*/
public SackOfViewsAdapter(List<View> views) {
super();
this.views=views;
}
/**
* Get the data item associated with the specified
* position in the data set.
* @param position Position of the item whose data we want
*/
@Override
public Object getItem(int position) {
return(views.get(position));
}
/**
* How many items are in the data set represented by this
* Adapter.
*/
@Override
public int getCount() {
return(views.size());
}
/**
* Returns the number of types of Views that will be
* created by getView().
*/
@Override
public int getViewTypeCount() {
return(getCount());
}
/**
* Get the type of View that will be created by getView()
* for the specified item.
* @param position Position of the item whose data we want
*/
@Override
public int getItemViewType(int position) {
return(position);
}
/**
* Are all items in this ListAdapter enabled? If yes it
* means all items are selectable and clickable.
*/
@Override
public boolean areAllItemsEnabled() {
return(false);
}
/**
* Returns true if the item at the specified position is
* not a separator.
* @param position Position of the item whose data we want
*/
@Override
public boolean isEnabled(int position) {
return(false);
}
/**
* Get a View that displays the data at the specified
* position in the data set.
* @param position Position of the item whose data we want
* @param convertView View to recycle, if not null
* @param parent ViewGroup containing the returned View
*/
@Override
public View getView(int position, View convertView,
ViewGroup parent) {
View result=views.get(position);
if (result==null) {
result=newView(position, parent);
views.set(position, result);
}
return(result);
}
/**
* Get the row id associated with the specified position
* in the list.
* @param position Position of the item whose data we want
*/
@Override
public long getItemId(int position) {
return(position);
}
/**
* Create a new View to go into the list at the specified
* position.
* @param position Position of the item whose data we want
* @param parent ViewGroup containing the returned View
*/
protected View newView(int position, ViewGroup parent) {
throw new RuntimeException("You must override newView()!");
}
} | Java |
/***
Copyright (c) 2008-2009 CommonsWare, LLC
Portions (c) 2009 Google, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.commonsware.cwac.merge;
import java.util.ArrayList;
import java.util.List;
import android.database.DataSetObserver;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.SectionIndexer;
import com.commonsware.cwac.sacklist.SackOfViewsAdapter;
/**
* Adapter that merges multiple child adapters and views
* into a single contiguous whole.
*
* Adapters used as pieces within MergeAdapter must
* have view type IDs monotonically increasing from 0. Ideally,
* adapters also have distinct ranges for their row ids, as
* returned by getItemId().
*
*/
public class MergeAdapter extends BaseAdapter implements SectionIndexer {
private ArrayList<ListAdapter> pieces=new ArrayList<ListAdapter>();
/**
* Stock constructor, simply chaining to the superclass.
*/
public MergeAdapter() {
super();
}
/**
* Adds a new adapter to the roster of things to appear
* in the aggregate list.
* @param adapter Source for row views for this section
*/
public void addAdapter(ListAdapter adapter) {
pieces.add(adapter);
adapter.registerDataSetObserver(new CascadeDataSetObserver());
}
/**
* Adds a new View to the roster of things to appear
* in the aggregate list.
* @param view Single view to add
*/
public void addView(View view) {
addView(view, false);
}
/**
* Adds a new View to the roster of things to appear
* in the aggregate list.
* @param view Single view to add
* @param enabled false if views are disabled, true if enabled
*/
public void addView(View view, boolean enabled) {
ArrayList<View> list=new ArrayList<View>(1);
list.add(view);
addViews(list, enabled);
}
/**
* Adds a list of views to the roster of things to appear
* in the aggregate list.
* @param views List of views to add
*/
public void addViews(List<View> views) {
addViews(views, false);
}
/**
* Adds a list of views to the roster of things to appear
* in the aggregate list.
* @param views List of views to add
* @param enabled false if views are disabled, true if enabled
*/
public void addViews(List<View> views, boolean enabled) {
if (enabled) {
addAdapter(new EnabledSackAdapter(views));
}
else {
addAdapter(new SackOfViewsAdapter(views));
}
}
/**
* Get the data item associated with the specified
* position in the data set.
* @param position Position of the item whose data we want
*/
@Override
public Object getItem(int position) {
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
return(piece.getItem(position));
}
position-=size;
}
return(null);
}
/**
* Get the adapter associated with the specified
* position in the data set.
* @param position Position of the item whose adapter we want
*/
public ListAdapter getAdapter(int position) {
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
return(piece);
}
position-=size;
}
return(null);
}
/**
* How many items are in the data set represented by this
* Adapter.
*/
@Override
public int getCount() {
int total=0;
for (ListAdapter piece : pieces) {
total+=piece.getCount();
}
return(total);
}
/**
* Returns the number of types of Views that will be
* created by getView().
*/
@Override
public int getViewTypeCount() {
int total=0;
for (ListAdapter piece : pieces) {
total+=piece.getViewTypeCount();
}
return(Math.max(total, 1)); // needed for setListAdapter() before content add'
}
/**
* Get the type of View that will be created by getView()
* for the specified item.
* @param position Position of the item whose data we want
*/
@Override
public int getItemViewType(int position) {
int typeOffset=0;
int result=-1;
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
result=typeOffset+piece.getItemViewType(position);
break;
}
position-=size;
typeOffset+=piece.getViewTypeCount();
}
return(result);
}
/**
* Are all items in this ListAdapter enabled? If yes it
* means all items are selectable and clickable.
*/
@Override
public boolean areAllItemsEnabled() {
return(false);
}
/**
* Returns true if the item at the specified position is
* not a separator.
* @param position Position of the item whose data we want
*/
@Override
public boolean isEnabled(int position) {
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
return(piece.isEnabled(position));
}
position-=size;
}
return(false);
}
/**
* Get a View that displays the data at the specified
* position in the data set.
* @param position Position of the item whose data we want
* @param convertView View to recycle, if not null
* @param parent ViewGroup containing the returned View
*/
@Override
public View getView(int position, View convertView,
ViewGroup parent) {
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
return(piece.getView(position, convertView, parent));
}
position-=size;
}
return(null);
}
/**
* Get the row id associated with the specified position
* in the list.
* @param position Position of the item whose data we want
*/
@Override
public long getItemId(int position) {
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
return(piece.getItemId(position));
}
position-=size;
}
return(-1);
}
@Override
public int getPositionForSection(int section) {
int position=0;
for (ListAdapter piece : pieces) {
if (piece instanceof SectionIndexer) {
Object[] sections=((SectionIndexer)piece).getSections();
int numSections=0;
if (sections!=null) {
numSections=sections.length;
}
if (section<numSections) {
return(position+((SectionIndexer)piece).getPositionForSection(section));
}
else if (sections!=null) {
section-=numSections;
}
}
position+=piece.getCount();
}
return(0);
}
@Override
public int getSectionForPosition(int position) {
int section=0;
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
if (piece instanceof SectionIndexer) {
return(section+((SectionIndexer)piece).getSectionForPosition(position));
}
return(0);
}
else {
if (piece instanceof SectionIndexer) {
Object[] sections=((SectionIndexer)piece).getSections();
if (sections!=null) {
section+=sections.length;
}
}
}
position-=size;
}
return(0);
}
@Override
public Object[] getSections() {
ArrayList<Object> sections=new ArrayList<Object>();
for (ListAdapter piece : pieces) {
if (piece instanceof SectionIndexer) {
Object[] curSections=((SectionIndexer)piece).getSections();
if (curSections!=null) {
for (Object section : curSections) {
sections.add(section);
}
}
}
}
if (sections.size()==0) {
return(null);
}
return(sections.toArray(new Object[0]));
}
private static class EnabledSackAdapter extends SackOfViewsAdapter {
public EnabledSackAdapter(List<View> views) {
super(views);
}
@Override
public boolean areAllItemsEnabled() {
return(true);
}
@Override
public boolean isEnabled(int position) {
return(true);
}
}
private class CascadeDataSetObserver extends DataSetObserver {
@Override
public void onChanged() {
notifyDataSetChanged();
}
@Override
public void onInvalidated() {
notifyDataSetInvalidated();
}
}
} | Java |
package com.hlidskialf.android.hardware;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
public class ShakeListener implements SensorEventListener {
private static final int FORCE_THRESHOLD = 350;
private static final int TIME_THRESHOLD = 100;
private static final int SHAKE_TIMEOUT = 500;
private static final int SHAKE_DURATION = 1000;
private static final int SHAKE_COUNT = 3;
private SensorManager mSensorMgr;
private Sensor mSensor;
private float mLastX = -1.0f, mLastY = -1.0f, mLastZ = -1.0f;
private long mLastTime;
private OnShakeListener mShakeListener;
private Context mContext;
private int mShakeCount = 0;
private long mLastShake;
private long mLastForce;
public interface OnShakeListener {
public void onShake();
}
public ShakeListener(Context context) {
mContext = context;
resume();
}
public void setOnShakeListener(OnShakeListener listener) {
mShakeListener = listener;
}
public void resume() {
mSensorMgr = (SensorManager) mContext
.getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorMgr
.getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER);
if (mSensorMgr == null) {
throw new UnsupportedOperationException("Sensors not supported");
}
boolean supported = mSensorMgr.registerListener(this,
mSensor,
SensorManager.SENSOR_DELAY_GAME);
if (!supported) {
mSensorMgr.unregisterListener(this, mSensor);
throw new UnsupportedOperationException(
"Accelerometer not supported");
}
}
public void pause() {
if (mSensorMgr != null) {
mSensorMgr.unregisterListener(this,
mSensor);
mSensorMgr = null;
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
float[] values = event.values;
if (sensor.getType() != SensorManager.SENSOR_ACCELEROMETER)
return;
long now = System.currentTimeMillis();
if ((now - mLastForce) > SHAKE_TIMEOUT) {
mShakeCount = 0;
}
if ((now - mLastTime) > TIME_THRESHOLD) {
long diff = now - mLastTime;
float speed = Math.abs(values[SensorManager.DATA_X]
+ values[SensorManager.DATA_Y]
+ values[SensorManager.DATA_Z] - mLastX - mLastY - mLastZ)
/ diff * 10000;
if (speed > FORCE_THRESHOLD) {
if ((++mShakeCount >= SHAKE_COUNT)
&& (now - mLastShake > SHAKE_DURATION)) {
mLastShake = now;
mShakeCount = 0;
if (mShakeListener != null) {
mShakeListener.onShake();
}
}
mLastForce = now;
}
mLastTime = now;
mLastX = values[SensorManager.DATA_X];
mLastY = values[SensorManager.DATA_Y];
mLastZ = values[SensorManager.DATA_Z];
}
}
}
| Java |
package ImportsAndExports;
import java.util.LinkedList;
import java.util.Random;
public class createRandomAthletesDB {
String[] fnames = {"Alexandru","Adi","Andrei","Cosmin","Daniel","Mircea","Bogdan","Florin","Ionut","Marian","Sorin"};
String[] surnames = {"Gaman","Palko","Popescu","Pavel","Ciobanu","Paraschiv","Podaru","Neagoe","Diaconu","Tatru","Ionescu"};
String[] nationalities = {"Romania","Franta","Italia","Spania","Germania","Austria","Olanda","Luxemburg","U.S.A","Jamaica","Ecuador"};
Random generator = new Random();
float[] ca = new float[1000];
float[] pa = new float[1000];
public static void main(String args[]) {
new createRandomAthletesDB();
}
public createRandomAthletesDB() {
super();
this.setCA();
this.writeDB();
}
public void writeDB(){
dbImporting.writeDB("AtletiGenerati.txt", this.generate());
}
public LinkedList<String> generate(){
LinkedList<String> returnValue = new LinkedList<String>();
for (int i=1;i<1000;i++) {
returnValue.addAll(this.generateNewAthlete(i));
}
return returnValue;
}
public LinkedList<String> generateNewAthlete(int i){
LinkedList<String> returnValue = new LinkedList<String>();
returnValue.add(i+"");
returnValue.add(generator.nextInt((int) ca[i]/10+1)+""); // acc
returnValue.add(generator.nextInt((int) ca[i]/10+1)+""); // spd
returnValue.add(generator.nextInt((int) ca[i]/10+1)+""); // pac
returnValue.add(generator.nextInt((int) ca[i]/10+1)+""); // rea
returnValue.add(generator.nextInt((int) ca[i]/10+1)+""); // conc
returnValue.add(generator.nextInt((int) ca[i]/10+1)+""); // fit
returnValue.add(generator.nextInt((int) ca[i]/10+1)+""); // mor
returnValue.add(this.ca[i]+""); // cab
returnValue.add(this.pa[i]+""); // pab
returnValue.add(this.fnames[generator.nextInt(10)]); // random fname
returnValue.add(this.surnames[generator.nextInt(10)]); // random surname
returnValue.add(this.nationalities[generator.nextInt(10)]); // random nat
returnValue.add((generator.nextInt(29) + 1)+""); // ziua nasterii
returnValue.add((generator.nextInt(12) + 1)+""); // luna nasterii
returnValue.add((generator.nextInt(20)+1970)+""); // anul nasterii
returnValue.add("99.99"); // personal best
returnValue.add("1"); returnValue.add("1"); returnValue.add("1"); // data pentru pb
returnValue.add("null"); // locatia pb
returnValue.add("99.99"); // season best
returnValue.add("1"); returnValue.add("1"); returnValue.add("1"); // data pentru sb
returnValue.add("Null"); // locatia sb
returnValue.add("null"); // istoric, initial null
return returnValue;
}
public void setCA(){
for (int i=0;i<1000;i++) {
this.pa[i] = generator.nextInt(1000);
this.ca[i] = generator.nextInt((int) pa[i]+1);
}
}
}
| Java |
package Main.ImportsAndExports;
| Java |
package ImportsAndExports;
import java.util.LinkedList;
public class createRandomCompetitionDB {
LinkedList<String> nume = new LinkedList<String>();
LinkedList<String> locatie = new LinkedList<String>();
LinkedList<String> data = new LinkedList<String>();
LinkedList<String> categ = new LinkedList<String>();
public static void main(String args[]) {
new createRandomCompetitionDB();
}
public createRandomCompetitionDB() {
super();
this.readFiles();
this.writeNewDatabase("NewDatabase.txt");
}
public void writeNewDatabase(String s){
dbImporting.writeDB(s, this.createCompetition());
}
public LinkedList<String> createCompetition() {
LinkedList<String> returnValue = new LinkedList<String>();
for (int i=0;i<65;i++) {
returnValue.add(i+"");
returnValue.add(categ.get(i));
returnValue.add(data.get(i).split(" ")[0]);
returnValue.add(data.get(i).split(" ")[1]);
returnValue.add(data.get(i).split(" ")[2]);
returnValue.add(nume.get(i));
returnValue.add(locatie.get(i).split(",")[0]);
returnValue.add(locatie.get(i).split(",")[1]);
returnValue.add("99.99");
returnValue.add("1"); returnValue.add("1"); returnValue.add("2000");
returnValue.add("Nobody");
if (categ.get(i).equals("2") == true)
returnValue.add("0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255");
if (categ.get(i).equals("3") == true)
returnValue.add("0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127");
if (categ.get(i).equals("4"))
returnValue.add("0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63");
if (categ.get(i).equals("5") == true)
returnValue.add("0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31");
}
return returnValue;
}
public String listToString(LinkedList<String> a){
String s = "";
for (String aux : a)
s += a+" ";
return s;
}
public void readFiles() {
this.nume = dbImporting.readDB("CompNames.txt");
this.locatie = dbImporting.readDB("CompLocation.txt");
this.data = dbImporting.readDB("CompDates.txt");
this.categ = dbImporting.readDB("CompCateg.txt");
}
}
| Java |
package ImportsAndExports;
import java.util.LinkedList;
public class generator {
public generator() {
super();
}
public static void main(String args[]){
LinkedList<String> rv = new LinkedList<String>();
String s = "";
for (int j=0;j<256;j++)
s+=j+" ";
rv.add(s);
dbImporting.writeDB("n.txt", rv);
}
}
| Java |
package ImportsAndExports;
import BackendSimulation.Atlet;
import BackendSimulation.staticData;
import BackendSimulation.Competition;
import BackendSimulation.Manager;
import java.util.*;
import java.io.*;
public class dbImporting {
static LinkedList<String> details = new LinkedList<String>();
public dbImporting() {
super();
}
static int writeDB(String path, LinkedList<String> data)
{
try
{
File f = new File(path);
if (f.exists() == false){
f.createNewFile();
FileWriter fw = new FileWriter(path);
BufferedWriter bw = new BufferedWriter( fw );
for (int i=0;i<data.size();i++)
{
bw.write(data.get(i));
bw.newLine();
}
bw.close( ); // inchid fisierul
}
else{
f.createNewFile();
FileWriter fw = new FileWriter(path);
BufferedWriter bw = new BufferedWriter( fw );
for (int i=0;i<data.size();i++)
{
bw.append(data.get(i));
bw.newLine();
}
bw.close( ); // inchid fisierul
}
}
catch(IOException e ) // tratare io exception
{
System.out.println("IO ERROR : "+e.getMessage());
e.printStackTrace( );
return 1;
}
System.out.println( "all OK" ); // returnez mesaj de succes
return 0;
}
public static LinkedList<String> readDB(String path) // metoda de citire a unui fisier text
{LinkedList<String> aux = new LinkedList<String>();
try
{
Scanner sc = new Scanner(new File(path)); // incerc sa deschid fisierul cu calea fname
while (sc.hasNext()) // citesc din fisier atat timp cat exista urmatorul element
{
String x = sc.nextLine();
if (x.startsWith("//") == false)
aux.add(x);
} // sfarsitul citirii din fisier
sc.close(); //inchid fisierul text
return aux;
} // end try
catch (FileNotFoundException fnf)
{
System.out.println("File does not exist : "+path);// in cazul in care returneaza eroare, afisez mesajul
fnf.printStackTrace();
return null; // in caz de eroare, returnez null
} // end catch
catch (Exception e)
{
System.out.println("ERROR : "+e.getMessage());// in cazul in care returneaza eroare, afisez mesajul
e.printStackTrace();
return null; // in caz de eroare, returnez null
} // end catch
} // end int readfile()
public static LinkedList<Atlet> parseAtletImport() {
LinkedList<String> aux = readDB("Athletes.txt");
LinkedList<Atlet> returnValue = new LinkedList<Atlet>();
System.out.println("Debug test 3 : atlet aux size : "+aux.size());
while(aux.isEmpty() == false){
returnValue.add(new Atlet(aux));
for (int j=1;j<=27;j++) {aux.removeFirst();}
}
return returnValue;
}
public static LinkedList<Competition> parseCompetitionImport() {
LinkedList<String> aux = readDB("Comp.txt");
LinkedList<Competition> returnValue = new LinkedList<Competition>();
System.out.println("Debug test 1 : competition aux size : "+aux.size());
while(aux.isEmpty() == false){
returnValue.add(new Competition(aux));
for (int j=1;j<=14;j++) {aux.removeFirst();}
}
return returnValue;
}
public static LinkedList<Manager> parseManagerImport(){
LinkedList<String> aux = readDB("Managers.txt");
LinkedList<Manager> returnValue = new LinkedList<Manager>();
System.out.println("Debug test 2 : manager aux size : "+aux.size());
while(aux.isEmpty() == false){
returnValue.add(new Manager(aux));
for (int j=1;j<=13;j++) {aux.removeFirst();}
}
return returnValue;
}
public static void writePlayerDetails(Manager player) {
details.add("0");
details.add(player.firstName); details.add(player.lastName); details.add(player.nationalitate);
// details.add(player.dataNasterii.zi+""); details.add(player.dataNasterii.luna+""); details.add(player.dataNasterii.an+"");
//details.add(player.training+""); details.add(player.business+""); details.add(player.knowledge+"");details.add(player.renume+"") ;details.add(player.ability+"");
String s = "";
}
public static void writeCompetitionDetails(LinkedList<Competition> competitii){
details.add("-----");
for (Competition comp : competitii) {
details.add(comp.uniqueID+"");
details.add(comp.clasa+"");
details.add(comp.dataConcursului.zi+"");
details.add(comp.dataConcursului.luna+"");
details.add(comp.dataConcursului.an+"");
details.add(comp.numeleConcursului);
details.add(comp.orasulConcursului);
details.add(comp.taraConcursului);
details.add(comp.record+"");
details.add(comp.dataRecordului.zi+"");
details.add(comp.dataRecordului.luna+"");
details.add(comp.dataRecordului.an+"");
details.add(comp.numeDetinator);
String s = "";
if (comp.atletiInscrisi != null)
{
for (int inscris : comp.atletiInscrisi) {
s += inscris+" ";
}
details.add(s);
}
else
{details.add("null");}
}
}
public static Manager readPlayerDetails(String s){
LinkedList<String> aux = readDB("Saved/" + s +".txt");
System.out.println("Loading OK");
return new Manager(aux);
}
public static void writeAthletes(LinkedList<Atlet> ath) {
details.add("-----");
for (Atlet athlete : ath) {
details.add(athlete.uniqueID+"");
details.add(athlete.acceleration+"");
details.add(athlete.speed+"");
details.add(athlete.pace+"");
details.add(athlete.reaction+"");
details.add(athlete.concentration+"");
details.add(athlete.fitness+"");
details.add(athlete.morale+"");
details.add(athlete.currentAbility+"");
details.add(athlete.potentialAbility+"");
details.add(athlete.firstName);
details.add(athlete.lastName);
details.add(athlete.nationality);
details.add(athlete.dataNasterii.zi+"");
details.add(athlete.dataNasterii.luna+"");
details.add(athlete.dataNasterii.an+"");
details.add(athlete.personalBest+""); details.add(athlete.personalBestDate.zi+""); details.add(athlete.personalBestDate.luna+""); details.add(athlete.personalBestDate.an+""); details.add(athlete.personalBestLocation);
details.add(athlete.seasonBest+""); details.add(athlete.seasonBestDate.zi+""); details.add(athlete.seasonBestDate.luna+""); details.add(athlete.seasonBestDate.an+""); details.add(athlete.seasonBestLocation);
if (athlete.history.size() != 0)
{
String s = "";
for (float f : athlete.history) {
s += f+"";
}
details.add(s);
}
else
{details.add("null");}
}
}
public static void writeManagers(LinkedList<Manager> man){
details.add("-----");
for (Manager player : man){
details.add("0");
details.add(player.firstName); details.add(player.lastName); details.add(player.nationalitate);
details.add(player.dataNasterii.zi+""); details.add(player.dataNasterii.luna+""); details.add(player.dataNasterii.an+"");
details.add(player.training+""); details.add(player.business+""); details.add(player.knowledge+"");details.add(player.renume+"") ;details.add(player.ability+"");
String s = "";
for (int i=0;i<player.idAtletiSubContract.size();i++) {
s += player.idAtletiSubContract.get(i)+" ";
}
details.add(s);
}
}
public static void createSavedGame(){
// TODO
// writePlayerDetails(staticData.player);
writeManagers(staticData.managers);
writeAthletes(staticData.atlet);
writeCompetitionDetails(staticData.competitii);
writeDB("Saved/"+ staticData.player.firstName + " " + staticData.player.lastName +".txt",details);
details.clear();
}
public static LinkedList[] loadSavedGame(String s) {
LinkedList[] returnValue = new LinkedList[4]; returnValue[0] = new LinkedList<Manager>(); returnValue[1] = new LinkedList<Atlet>(); returnValue[2] = new LinkedList<Manager>(); returnValue[3] = new LinkedList<Competition>();
LinkedList<String> loadedData = readDB("Saved/" + s +".txt");
LinkedList<String> plyr = new LinkedList<String>();LinkedList<String> atl = new LinkedList<String>(); LinkedList<String> man = new LinkedList<String>();
LinkedList<String> comp = new LinkedList<String>();
int count = 0;
for (String substr : loadedData){
if (substr.startsWith("-----") == true) {count++;}
else
{
if (count == 0){
plyr.add(substr);
}
if (count == 1){
man.add(substr);
}
if (count == 2){
atl.add(substr);
}
if (count == 3){
comp.add(substr);
}
}
}
returnValue[0].add(new Manager(plyr));
System.out.println ("Debug : atlSaved size : " +atl.size());
while (atl.isEmpty() == false){
returnValue[1].add(new Atlet(atl));
for (int j=1;j<=27;j++) {atl.removeFirst();}
}
System.out.println ("Debug : manSaved size : " +man.size());
while (man.isEmpty() == false){
returnValue[2].add(new Manager(man));
for (int j=1;j<=13;j++) {man.removeFirst();}
}
System.out.println ("Debug : compSaved size : " +comp.size());
while (comp.isEmpty() == false){
returnValue[3].add(new Competition(comp));
for (int j=1;j<=14;j++) {comp.removeFirst();}
}
return returnValue;
}
}
| Java |
package GUI;
import BackendSimulation.AttributesCheck;
import BackendSimulation.Data;
import BackendSimulation.staticData;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.List;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.DebugGraphics;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
public class ManagerHome extends JFrame {
private JLabel jLabel1 = new JLabel();
private JLabel currentDateLabel = new JLabel();
private JLabel jLabel3 = new JLabel();
private JLabel jLabel4 = new JLabel();
private List list1 = new List();
private JLabel managerNameLabel = new JLabel();
private JLabel managerAgeLabel = new JLabel();
private JLabel managerNationalityLabel = new JLabel();
private JButton jButton1 = new JButton();
private JButton jButton2 = new JButton();
private JButton jButton3 = new JButton();
private JButton jButton4 = new JButton();
private JTable jTable1 = new JTable(new TabelCompetitii(staticData.competitionCount));
private JScrollPane jScrollPane1 = new JScrollPane(jTable1);
private BorderLayout borderLayout1 = new BorderLayout();
private JButton jButton5 = new JButton();
private JButton jButton6 = new JButton();
private JLabel recordMondial = new JLabel();
private JButton jButton7 = new JButton();
static int prevMonth = 1;
public ManagerHome() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
this.getContentPane().setLayout( null );
this.setSize(new Dimension(456, 339));
jLabel1.setText("Current date : ");
jLabel1.setBounds(new Rectangle(5, 80, 115, 20));
currentDateLabel.setText("jLabel2");
currentDateLabel.setBounds(new Rectangle(135, 80, 245, 20));
jLabel3.setText("Currently managed athletes :");
jLabel3.setBounds(new Rectangle(5, 110, 220, 20));
jLabel4.setText("Upcoming competitions :");
jLabel4.setBounds(new Rectangle(230, 110, 220, 20));
list1.setBounds(new Rectangle(5, 140, 140, 75));
managerNameLabel.setText("jLabel2");
managerNameLabel.setBounds(new Rectangle(5, 15, 200, 25));
managerAgeLabel.setText("jLabel5");
managerAgeLabel.setBounds(new Rectangle(220, 15, 105, 25));
managerNationalityLabel.setText("jLabel5");
managerNationalityLabel.setBounds(new Rectangle(335, 15, 115, 25));
jButton1.setText("1 day");
jButton1.setBounds(new Rectangle(10, 235, 125, 20));
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton1_actionPerformed(e);
}
});
jButton2.setText("1 week");
jButton2.setBounds(new Rectangle(155, 235, 125, 20));
jButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton2_actionPerformed(e);
}
});
jButton3.setText("next comp");
jButton3.setBounds(new Rectangle(295, 235, 125, 20));
jButton3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton3_actionPerformed(e);
}
});
jButton4.setText("Rankings");
jButton4.setBounds(new Rectangle(145, 275, 145, 20));
jButton4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton4_actionPerformed(e);
}
});
jScrollPane1.setBounds(new Rectangle(225, 135, 210, 75));
jScrollPane1.setDoubleBuffered(true);
jButton5.setText("search");
jButton5.setBounds(new Rectangle(305, 275, 130, 20));
jButton5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton5_actionPerformed(e);
}
});
jButton6.setText("comp");
jButton6.setBounds(new Rectangle(10, 275, 115, 20));
jButton6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton6_actionPerformed(e);
}
});
recordMondial.setText("jLabel2");
recordMondial.setBounds(new Rectangle(155, 150, 65, 20));
jButton7.setText("Training");
jButton7.setBounds(new Rectangle(295, 80, 145, 20));
jButton7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton7_actionPerformed(e);
}
});
jTable1.setAutoCreateRowSorter(true);
this.initAthletesList();
//this.initCompetitionsList();
this.initManagerLabels();
this.initDateLabel();
jScrollPane1.getViewport().add(jTable1, null);
this.getContentPane().add(jButton7, null);
this.getContentPane().add(recordMondial, null);
this.getContentPane().add(jButton6, null);
this.getContentPane().add(jButton5, null);
this.getContentPane().add(jScrollPane1, null);
this.getContentPane().add(jButton4, null);
this.getContentPane().add(jButton3, null);
this.getContentPane().add(jButton2, null);
this.getContentPane().add(jButton1, null);
this.getContentPane().add(managerNationalityLabel, null);
this.getContentPane().add(managerAgeLabel, null);
this.getContentPane().add(managerNameLabel, null);
this.getContentPane().add(list1, null);
this.getContentPane().add(jLabel4, null);
this.getContentPane().add(jLabel3, null);
this.getContentPane().add(currentDateLabel, null);
this.getContentPane().add(jLabel1, null);
this.setVisible(true);
this.addWindowListener(new WindowAdapter() {
public void windowOpened(WindowEvent e) {
this_windowOpened(e);
}
});
System.out.println("CC : "+staticData.competitionCount);
}
public void initAthletesList() {
// TODO
// for (int i=0;i<staticData.player.idAtletiSubContract.size();i++)
// list1.add(staticData.atlet.get(i).firstName + " " + staticData.atlet.get(i).lastName);
}
/* public void initCompetitionsList(){
for (int i=0;i<staticData.competitii.size();i++)
list2.add(staticData.competitii.get(i).numeleConcursului + ", " + staticData.competitii.get(i).orasulConcursului);
}*/
public void initDateLabel(){
this.currentDateLabel.setText(staticData.dataCurenta.dateToString());
this.recordMondial.setText(staticData.recordMondial+"");
}
public void initManagerLabels(){
// TODO
// this.managerNameLabel.setText(staticData.player.firstName + " " + staticData.player.lastName);
// this.managerAgeLabel.setText(staticData.player.age +" years");
// this.managerNationalityLabel.setText(staticData.player.nationalitate);
}
private void jButton1_actionPerformed(ActionEvent e) {
staticData.dataCurenta = staticData.dataCurenta.urmatoareaZi();
this.initDateLabel();
this.newDayRoutine();
this.repaint();
}
private void jButton2_actionPerformed(ActionEvent e) {
for (int i=1;i<=7;i++) {staticData.dataCurenta = staticData.dataCurenta.urmatoareaZi(); this.newDayRoutine();}
this.initDateLabel();
}
private void jButton4_actionPerformed(ActionEvent e) {
new Clasament();
this.dispose();
}
private void newDayRoutine(){
for (int i=0;i<staticData.atlet.size();i++)
if ( (staticData.atlet.get(i).dataNasterii.zi == staticData.dataCurenta.zi) && (staticData.atlet.get(i).dataNasterii.luna == staticData.dataCurenta.luna) )
staticData.atlet.get(i).age ++;
for (int i=0;i<staticData.managers.size();i++)
if ( (staticData.managers.get(i).dataNasterii.zi == staticData.dataCurenta.zi) && (staticData.managers.get(i).dataNasterii.luna == staticData.dataCurenta.luna) )
staticData.managers.get(i).age ++;
if ( (staticData.player.dataNasterii.zi == staticData.dataCurenta.zi) && (staticData.player.dataNasterii.luna == staticData.dataCurenta.luna) )
{staticData.player.age ++; this.managerAgeLabel.setText(staticData.player.age+" years");}
for (int i=0;i<staticData.competitii.size();i++)
if ( (staticData.competitii.get(i).dataConcursului.zi == staticData.dataCurenta.zi) && (staticData.competitii.get(i).dataConcursului.luna == staticData.dataCurenta.luna))
{this.dispose(); new CompetitionPage(i); staticData.competitionCount++; staticData.passedComp.add(i); }
AttributesCheck.updateDaily();
if (staticData.dataCurenta.luna != prevMonth ) {
AttributesCheck.updateMonthly();
prevMonth = staticData.dataCurenta.luna;
}
}
private void jButton5_actionPerformed(ActionEvent e) {
new AthleteSearch();
this.dispose();
}
private void jButton6_actionPerformed(ActionEvent e) {
new CompetitionSearch();
this.dispose();
}
private void this_windowOpened(WindowEvent e) {
jTable1.setModel(new TabelCompetitii(staticData.competitionCount));
jScrollPane1.repaint();
}
private void jButton3_actionPerformed(ActionEvent e) {
int aux = Data.nrZileIntreDate(staticData.dataCurenta, staticData.competitii.get(staticData.competitionCount).dataConcursului);
if (staticData.competitionCount == 0)
{aux = Data.nrZileIntreDate(staticData.dataCurenta, staticData.competitii.get(0).dataConcursului);}
for (int i=1;i<=aux;i++) {staticData.dataCurenta = staticData.dataCurenta.urmatoareaZi(); this.newDayRoutine();}
this.initDateLabel();
}
private void jButton7_actionPerformed(ActionEvent e) {
new Training();
this.dispose();
}
// CLASA Tabel Competitii
class TabelCompetitii extends AbstractTableModel {
private String[] columnNames = {"Data","Nume","Oras"};
private Object[][] date = new Object[staticData.competitii.size()-staticData.competitionCount][5];
private int dim = staticData.competitii.size();
public TabelCompetitii(int cc) {
loadData(cc);
}
public void loadData(int cc) {
for (int i=0;i<staticData.competitii.size()-cc;i++){
{System.out.println("Data : "+i);
System.out.println("Passed Comp dim"+staticData.passedComp.size());
date[i][0] = staticData.competitii.get(i+cc).dataConcursului.dateToString();
date[i][1] = staticData.competitii.get(i+cc).numeleConcursului;
date[i][2] = staticData.competitii.get(i+cc).orasulConcursului;
date[i][3] = staticData.competitii.get(i+cc).dataConcursului.zi;
date[i][4] = staticData.competitii.get(i+cc).dataConcursului.luna;
}
fireTableDataChanged();
}
}
/* public void sortData(int cc){
Object [] aux = new Object[100];
for (int i=0;i<staticData.competitii.size()-cc-2;i++)
for (int j=i+1;j<staticData.competitii.size()-cc-1;j++) {
int a = (Integer.parseInt(date[i][3].toString()));
int b = (Integer.parseInt(date[i][4].toString()));
int a2 = (Integer.parseInt(date[j][3].toString()));
int b2 = (Integer.parseInt(date[j][4].toString()));
if ((b > b2) || ((b == b2) && (a > a2) )){
for (int k=0;k<5;k++) {aux[k] = date[i][k];}
for (int k=0;k<5;k++) {date[i][k] = date[j][k];}
for (int k=0;k<5;k++) {date[j][k] = aux[k];}
}
}
}*/
@Override
public int findColumn(String columnName){
for (int i=0;i<columnNames.length;i++)
if (columnName == columnNames[i])
return i;
return -1;
}
@Override
public int getColumnCount() { return columnNames.length; }
@Override
public int getRowCount() { return date.length; }
@Override
public String getColumnName(int col) { return columnNames[col]; }
@Override
public Object getValueAt(int rowIndex, int columnIndex) { return date[rowIndex][columnIndex]; }
@Override
public Class getColumnClass(int c) { return getValueAt(staticData.competitionCount, c).getClass(); }
@Override
public boolean isCellEditable(int row,int col) {return false;}
}
}
| Java |
package GUI;
import java.awt.Dimension;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
public class ManagerPage extends JFrame {
public ManagerPage() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
this.getContentPane().setLayout( null );
this.setSize( new Dimension(400, 300) );
}
}
| Java |
package GUI;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
public class DataEditor extends JFrame {
private JTabbedPane jTabbedPane1 = new JTabbedPane();
private JPanel jPanel1 = new JPanel();
private JPanel jPanel2 = new JPanel();
private JList jList1 = new JList();
private JTextField accelerationValue = new JTextField();
private JTextField speedValue = new JTextField();
private JTextField paceValue = new JTextField();
private JTextField reactionValue = new JTextField();
private JTextField concentrationValue = new JTextField();
private JTextField fitnessValue = new JTextField();
private JTextField startingMoraleValue = new JTextField();
private JTextField firstName = new JTextField();
private JTextField lastName = new JTextField();
public DataEditor() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
this.getContentPane().setLayout( null );
this.setSize(new Dimension(630, 501));
jTabbedPane1.setBounds(new Rectangle(10, 5, 610, 460));
jPanel1.setLayout(null);
jList1.setBounds(new Rectangle(15, 20, 105, 410));
accelerationValue.setBounds(new Rectangle(175, 55, 65, 20));
speedValue.setBounds(new Rectangle(175, 80, 65, 20));
paceValue.setBounds(new Rectangle(175, 105, 65, 20));
paceValue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jTextField3_actionPerformed(e);
}
});
concentrationValue.setBounds(new Rectangle(175, 115, 65, 20));
reactionValue.setBounds(new Rectangle(175, 130, 65, 20));
reactionValue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jTextField3_actionPerformed(e);
}
});
concentrationValue.setBounds(new Rectangle(175, 155, 65, 20));
concentrationValue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jTextField3_actionPerformed(e);
}
});
fitnessValue.setBounds(new Rectangle(175, 180, 65, 20));
fitnessValue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jTextField3_actionPerformed(e);
}
});
startingMoraleValue.setBounds(new Rectangle(175, 205, 65, 20));
firstName.setBounds(new Rectangle(175, 20, 155, 20));
lastName.setBounds(new Rectangle(360, 20, 145, 20));
jPanel1.add(lastName, null);
jPanel1.add(firstName, null);
jPanel1.add(startingMoraleValue, null);
jPanel1.add(fitnessValue, null);
jPanel1.add(concentrationValue, null);
jPanel1.add(reactionValue, null);
jPanel1.add(paceValue, null);
jPanel1.add(speedValue, null);
jPanel1.add(accelerationValue, null);
jPanel1.add(jList1, null);
jTabbedPane1.addTab("jPanel1", jPanel1);
jTabbedPane1.addTab("jPanel2", jPanel2);
this.getContentPane().add(jTabbedPane1, null);
}
private void jTextField3_actionPerformed(ActionEvent e) {
}
}
| Java |
package GUI;
import BackendSimulation.*;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main extends JFrame {
private JButton jButton1 = new JButton();
private JButton jButton2 = new JButton();
private JButton jButton3 = new JButton();
private JButton jButton4 = new JButton();
private JButton jButton5 = new JButton();
private JButton jButton6 = new JButton();
private JButton jButton7 = new JButton();
public Main() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout( null );
this.setSize(new Dimension(359, 300));
jButton1.setText("New Game");
jButton1.setBounds(new Rectangle(10, 20, 135, 40));
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton1_actionPerformed(e);
}
});
jButton2.setText("Load Game");
jButton2.setBounds(new Rectangle(10, 65, 135, 40));
jButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton2_actionPerformed(e);
}
});
jButton3.setText("Options");
jButton3.setBounds(new Rectangle(10, 110, 135, 40));
jButton3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton3_actionPerformed(e);
}
});
jButton4.setText("Exit Game");
jButton4.setBounds(new Rectangle(10, 155, 135, 40));
jButton4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton4_actionPerformed(e);
}
});
jButton5.setText("view athlete");
jButton5.setBounds(new Rectangle(230, 130, 100, 20));
jButton5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton5_actionPerformed(e);
}
});
jButton6.setText("view competition");
jButton6.setBounds(new Rectangle(230, 155, 105, 20));
jButton6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton6_actionPerformed(e);
}
});
jButton7.setText("Manager");
jButton7.setBounds(new Rectangle(230, 105, 105, 20));
jButton7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton7_actionPerformed(e);
}
});
this.getContentPane().add(jButton7, null);
this.getContentPane().add(jButton6, null);
this.getContentPane().add(jButton5, null);
this.getContentPane().add(jButton4, null);
this.getContentPane().add(jButton3, null);
this.getContentPane().add(jButton2, null);
this.getContentPane().add(jButton1, null);
this.setVisible(true);
this.setTitle("preAlpha v2.1.7");
}
private void drawOptionsMenu() {
new Options();
}
private void jButton3_actionPerformed(ActionEvent e) {
this.drawOptionsMenu();
}
private void jButton5_actionPerformed(ActionEvent e) {
new AthletePage();
}
private void jButton6_actionPerformed(ActionEvent e) {
new CompetitionPage(0);
}
private void jButton7_actionPerformed(ActionEvent e) {
new ManagerHome();
}
private void jButton4_actionPerformed(ActionEvent e) {
System.exit(0);
}
private void jButton1_actionPerformed(ActionEvent e) {
new NewGameDialogs();
}
private void jButton2_actionPerformed(ActionEvent e) {
new LoadGame();
}
}
| Java |
package GUI;
import BackendSimulation.Competition;
import BackendSimulation.staticData;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.regex.PatternSyntaxException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableRowSorter;
public class CompetitionSearch extends JFrame {
private TableRowSorter sorter;
private TabelCompetitii tabelCompetitii = new TabelCompetitii();
private JScrollPane jScrollPane1 = new JScrollPane();
private JButton jButton1 = new JButton();
private JTextField jTextField1 = new JTextField();
private JTable jTable1 ;
public CompetitionSearch() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
this.getContentPane().setLayout( null );
this.setSize( new Dimension(400, 300) );
jScrollPane1.setBounds(new Rectangle(25, 50, 335, 215));
jButton1.setText("jButton1");
jButton1.setBounds(new Rectangle(255, 15, 105, 20));
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton1_actionPerformed(e);
}
});
jTextField1.setBounds(new Rectangle(40, 15, 150, 20));
jTextField1.getDocument().addDocumentListener(new DocumentListener(){
public void changedUpdate(DocumentEvent e) {newFilter();}
public void insertUpdate(DocumentEvent e) { newFilter();}
public void removeUpdate(DocumentEvent e) { newFilter();}
});
this.addSorter();
this.getContentPane().add(jTextField1, null);
this.getContentPane().add(jButton1, null);
jScrollPane1.getViewport().add(jTable1, null);
this.getContentPane().add(jScrollPane1, null);
this.jTable1.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
CompetitionPage c1 = new CompetitionPage (Integer.valueOf(jTable1.getValueAt(jTable1.getSelectedRow(), 4).toString()));
c1.removeAll(); c1.dispose();
new CompetitionDetails(); //(Integer.valueOf(jTable1.getValueAt(jTable1.getSelectedRow(), 4).toString()));
}
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
this.setVisible(true);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
this_windowClosing(e);
}
});
}
public void newFilter(){
RowFilter<TabelCompetitii, Object> rf = null;
try{
if (jTable1.getSelectedColumn() <= 0)
rf = RowFilter.regexFilter(jTextField1.getText(), jTable1.getSelectedColumn());
else
rf = RowFilter.regexFilter(jTextField1.getText(), jTable1.getSelectedColumn());
}
catch(PatternSyntaxException e){
e.printStackTrace(); return;
}
sorter.setRowFilter(rf);
}
public void addSorter() {
sorter = new TableRowSorter<TabelCompetitii>(tabelCompetitii);
jTable1 = new JTable(tabelCompetitii);
jTable1.setRowSorter(sorter);
jTable1.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
}
private void jButton1_actionPerformed(ActionEvent e) {
CompetitionPage c1 = new CompetitionPage (Integer.valueOf(jTable1.getValueAt(jTable1.getSelectedRow(), 4).toString()));
c1.removeAll(); c1.dispose();
new CompetitionDetails(); //(Integer.valueOf(jTable1.getValueAt(jTable1.getSelectedRow(), 4).toString()));
}
private void this_windowClosing(WindowEvent e) {
new ManagerHome();
}
private class TabelCompetitii extends AbstractTableModel {
private String[] columnNames = { "Data", "Nume Comp", "Categorie" ,"Oras","UID"};
private Object[][] date = new Object[staticData.competitii.size()][5];
public TabelCompetitii() {
loadData();
}
public void loadData() {
int iter = 0;
for (Competition comp : staticData.competitii) {
date[iter][0] = comp.dataConcursului.dateToString();
date[iter][1] = comp.numeleConcursului;
date[iter][2] = comp.numeClasa[comp.clasa - 1];
date[iter][3] = comp.orasulConcursului;
date[iter][4] = comp.uniqueID;
iter++;
}
}
@Override
public int findColumn(String columnName) {
for (int i = 0; i < columnNames.length; i++)
if (columnName == columnNames[i])
return i;
return -1;
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public int getRowCount() {
return date.length;
}
@Override
public String getColumnName(int col) {
return columnNames[col];
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return date[rowIndex][columnIndex];
}
@Override
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
}
}
| Java |
package GUI;
import java.awt.Dimension;
import BackendSimulation.*;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import oracle.jdeveloper.layout.VerticalFlowLayout;
public class CompetitionDetails extends JFrame {
private JTabbedPane jTabbedPane1 = new JTabbedPane();
private JPanel jPanel1 = new JPanel();
private JPanel jPanel2 = new JPanel();
private JPanel jPanel3 = new JPanel();
private JLabel lblCmpName = new JLabel();
private VerticalFlowLayout verticalFlowLayout1 = new VerticalFlowLayout();
private JLabel lblCmpCity = new JLabel();
private JLabel lblCmpDate = new JLabel();
private JLabel lblCmpRecord = new JLabel();
private JLabel jLabel2 = new JLabel();
public CompetitionDetails() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
this.getContentPane().setLayout( null );
this.setSize( new Dimension(400, 300) );
jTabbedPane1.setBounds(new Rectangle(10, 15, 375, 250));
jPanel1.setLayout(null);
jPanel3.setBounds(new Rectangle(45, 10, 270, 160));
jPanel3.setLayout(verticalFlowLayout1);
lblCmpName.setText("jLabel1");
lblCmpCity.setText("jLabel1");
lblCmpDate.setText("jLabel1");
lblCmpRecord.setText("jLabel1");
jLabel2.setText("Record :");
jPanel3.add(lblCmpName, null);
jPanel3.add(lblCmpCity, null);
jPanel3.add(lblCmpDate, null);
jPanel3.add(jLabel2, null);
jPanel3.add(lblCmpRecord, null);
jPanel1.add(jPanel3, null);
jTabbedPane1.addTab("jPanel1", jPanel1);
jTabbedPane1.addTab("jPanel2", jPanel2);
this.getContentPane().add(jTabbedPane1, null);
initLabel();
this.setVisible(true);
}
void initLabel(){
lblCmpName.setText(staticData.competitii.get(0).numeleConcursului);
lblCmpCity.setText(staticData.competitii.get(0).orasulConcursului +" , " +staticData.competitii.get(0).taraConcursului);
lblCmpDate.setText(staticData.competitii.get(0).dataConcursului.dateToString());
lblCmpRecord.setText(staticData.competitii.get(0).record +", " + staticData.competitii.get(0).numeDetinator + ", " +staticData.competitii.get(0).dataRecordului.dateToString());
}
}
| Java |
package GUI;
import ImportsAndExports.*;
import BackendSimulation.*;
import java.awt.CheckboxGroup;
import java.awt.Choice;
import java.awt.Dimension;
import java.awt.List;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class NewGameDialogs extends JFrame {
private JTextField firstNameLabel = new JTextField();
private JTextField lastNameLabel = new JTextField();
private JLabel jLabel1 = new JLabel();
private JLabel jLabel2 = new JLabel();
private JLabel jLabel3 = new JLabel();
private JRadioButton buttonEasy = new JRadioButton();
private JRadioButton buttonMedium = new JRadioButton();
private JRadioButton buttonHard = new JRadioButton();
private Choice choice1 = new Choice();
private Choice choice2 = new Choice();
private Choice choice3 = new Choice();
private JButton jButton1 = new JButton();
private List list1 = new List();
private JLabel jLabel4 = new JLabel();
public NewGameDialogs() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
this.getContentPane().setLayout( null );
this.setSize( new Dimension(400, 300) );
firstNameLabel.setBounds(new Rectangle(15, 35, 90, 20));
lastNameLabel.setBounds(new Rectangle(130, 35, 90, 20));
jLabel1.setText("Nume");
jLabel1.setBounds(new Rectangle(25, 15, 85, 15));
jLabel2.setText("Prenume");
jLabel2.setBounds(new Rectangle(135, 15, 85, 15));
jLabel3.setText("Data Nasterii");
jLabel3.setBounds(new Rectangle(255, 15, 120, 15));
buttonEasy.setText("Easy");
buttonEasy.setBounds(new Rectangle(10, 175, 100, 20));
buttonEasy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonEasy_actionPerformed(e);
}
});
buttonMedium.setText("Medium");
buttonMedium.setBounds(new Rectangle(10, 200, 100, 20));
buttonMedium.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonMedium_actionPerformed(e);
}
});
buttonHard.setText("Hard");
buttonHard.setBounds(new Rectangle(10, 225, 100, 20));
buttonHard.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonHard_actionPerformed(e);
}
});
choice1.setBounds(new Rectangle(235, 35, 45, 20));
choice2.setBounds(new Rectangle(285, 35, 45, 20));
choice3.setBounds(new Rectangle(335, 35, 55, 20));
jButton1.setText("Initialise new game");
jButton1.setBounds(new Rectangle(245, 230, 140, 20));
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton1_actionPerformed(e);
}
});
list1.setBounds(new Rectangle(15, 90, 140, 70));
jLabel4.setText("Nation");
jLabel4.setBounds(new Rectangle(20, 65, 125, 20));
this.initialiseBirthDateChoice();
this.initialiseNations();
this.getContentPane().add(jLabel4, null);
this.getContentPane().add(list1, null);
this.getContentPane().add(jButton1, null);
this.getContentPane().add(choice3, null);
this.getContentPane().add(choice2, null);
this.getContentPane().add(choice1, null);
this.getContentPane().add(buttonHard, null);
this.getContentPane().add(buttonMedium, null);
this.getContentPane().add(buttonEasy, null);
this.getContentPane().add(jLabel3, null);
this.getContentPane().add(jLabel2, null);
this.getContentPane().add(jLabel1, null);
this.getContentPane().add(lastNameLabel, null);
this.getContentPane().add(firstNameLabel, null);
this.setVisible(true);
}
private void buttonEasy_actionPerformed(ActionEvent e) {
if (buttonMedium.isSelected()) {buttonMedium.setSelected(false);}
if (buttonHard.isSelected()) {buttonHard.setSelected(false);}
}
private void buttonMedium_actionPerformed(ActionEvent e) {
if (buttonEasy.isSelected()) {buttonEasy.setSelected(false);}
if (buttonHard.isSelected()) {buttonHard.setSelected(false);}
}
private void buttonHard_actionPerformed(ActionEvent e) {
if (buttonEasy.isSelected()) {buttonEasy.setSelected(false);}
if (buttonMedium.isSelected()) {buttonMedium.setSelected(false);}
}
private void initialiseBirthDateChoice() {
for (int i=1;i<=12;i++)
this.choice2.add(Integer.toString(i));
for (int i=1;i<=31;i++)
this.choice1.add(Integer.toString(i));
for (int i=1960;i<=1992;i++)
this.choice3.add(Integer.toString(i));
}
private void initialiseNations(){
list1.add("Romania");
list1.add("Unknown");
}
private boolean validateData(){
switch (Integer.valueOf(this.choice2.getSelectedItem()))
{
case 1 : {return true;}
case 2 : if (Integer.valueOf(this.choice1.getSelectedItem()) > 28) {return false;} else {return true;}
case 3 : {return true;}
case 4 : if (Integer.valueOf(this.choice1.getSelectedItem()) == 31) {return false;} else {return true;}
case 5 : {return true;}
case 6 : if (Integer.valueOf(this.choice1.getSelectedItem()) == 31) {return false;} else {return true;}
case 7 : {return true;}
case 8 : {return true;}
case 9 : if (Integer.valueOf(this.choice1.getSelectedItem()) == 31) {return false;} else {return true;}
case 10 : {return true;}
case 11 : if (Integer.valueOf(this.choice1.getSelectedItem()) == 31) {return false;} else {return true;}
case 12 : if (Integer.valueOf(this.choice1.getSelectedItem()) == 31) {return false;} else {return true;}
}
return true;
}
private Atlet setPlayerDetails(){
Atlet player = new Atlet();
player.firstName = this.firstNameLabel.getText();
player.lastName = this.lastNameLabel.getText();
player.nationality = this.list1.getSelectedItem();
player.dataNasterii = new Data(Integer.valueOf(choice1.getSelectedItem()),Integer.valueOf(choice2.getSelectedItem()),Integer.valueOf(choice3.getSelectedItem()));
player.age = staticData.dataCurenta.an - player.dataNasterii.an ;
Random generator = new Random();
if (buttonEasy.isSelected()) {
}
if (buttonMedium.isSelected()){
}
if (buttonHard.isSelected()){
}
return player;
}
private void jButton1_actionPerformed(ActionEvent e) {
if (! this.validateData())
{JOptionPane.showMessageDialog(this, "Data is not valid!", "Error", JOptionPane.ERROR_MESSAGE);}
else {
staticData.player = setPlayerDetails();
new staticData();
dbImporting.createSavedGame();
JOptionPane.showMessageDialog(this, "Initialisation succesful!", "Succes", JOptionPane.INFORMATION_MESSAGE);
new ManagerHome();
this.dispose();
}
}
}
| Java |
package GUI;
| Java |
package GUI;
import BackendSimulation.staticData;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.regex.PatternSyntaxException;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableRowSorter;
public class AthleteSearch extends JFrame {
private TableRowSorter sorter;
private TabelAtleti tabelAtleti = new TabelAtleti();
private JTable jTable1;
private JScrollPane jScrollPane1 = new JScrollPane();
private JTextField jTextField1 = new JTextField();
private JButton jButton1 = new JButton();
public AthleteSearch() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
this.getContentPane().setLayout(null);
this.setSize(new Dimension(400, 300));
jScrollPane1.setBounds(new Rectangle(50, 60, 265, 145));
jTextField1.setBounds(new Rectangle(50, 20, 115, 20));
jButton1.setText("details");
jButton1.setBounds(new Rectangle(255, 20, 110, 20));
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton1_actionPerformed(e);
}
});
jTextField1.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
newFilter();
}
public void insertUpdate(DocumentEvent e) {
newFilter();
}
public void removeUpdate(DocumentEvent e) {
newFilter();
}
});
this.addSorter();
this.getContentPane().add(jButton1, null);
this.getContentPane().add(jTextField1, null);
jScrollPane1.getViewport().add(jTable1, null);
this.getContentPane().add(jScrollPane1, null);
this.jTable1.addMouseListener(new MouseListener() {
int count = 0;
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Click!!");
if (e.getClickCount() == 2)
new AthletePage((Integer.valueOf(tabelAtleti.getValueAt(jTable1.getSelectedRow(), 3).toString())));
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
this.setVisible(true);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
this_windowClosing(e);
}
});
}
public void newFilter() {
RowFilter<TabelAtleti, Object> rf = null;
try {
if (jTable1.getSelectedColumn() <= 0)
rf = RowFilter.regexFilter(jTextField1.getText(), 0);
else
rf = RowFilter.regexFilter(jTextField1.getText(), jTable1.getSelectedColumn());
} catch (PatternSyntaxException e) {
e.printStackTrace();
return;
}
sorter.setRowFilter(rf);
}
public void addSorter() {
sorter = new TableRowSorter<TabelAtleti>(tabelAtleti);
jTable1 = new JTable(tabelAtleti);
jTable1.setRowSorter(sorter);
jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
private void jButton1_actionPerformed(ActionEvent e) {
new AthletePage((Integer.valueOf(tabelAtleti.getValueAt(jTable1.getSelectedRow(), 3).toString())));
}
private void this_windowClosing(WindowEvent e) {
new ManagerHome();
}
private class TabelAtleti extends AbstractTableModel {
private String[] columnNames = { "Nume", "Prenume", "Varsta" };
private Object[][] date = new Object[staticData.atlet.size()][4];
public TabelAtleti() {
loadData();
}
public void loadData() {
for (int i = 0; i < staticData.atlet.size(); i++) {
date[i][0] = staticData.atlet.get(i).firstName;
date[i][1] = staticData.atlet.get(i).lastName;
date[i][2] = staticData.atlet.get(i).age;
date[i][3] = staticData.atlet.get(i).uniqueID;
}
}
@Override
public int findColumn(String columnName) {
for (int i = 0; i < columnNames.length; i++)
if (columnName == columnNames[i])
return i;
return -1;
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public int getRowCount() {
return date.length;
}
@Override
public String getColumnName(int col) {
return columnNames[col];
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return date[rowIndex][columnIndex];
}
@Override
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
}
}
| Java |
package GUI;
import BackendSimulation.Atlet;
import BackendSimulation.Manager;
import BackendSimulation.staticData;
import ImportsAndExports.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.awt.Dimension;
import java.awt.List;
import java.awt.Rectangle;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class LoadGame extends JFrame {
private JLabel jLabel1 = new JLabel();
private List list1 = new List();
private JButton jButton1 = new JButton();
public LoadGame() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
this.getContentPane().setLayout( null );
this.setSize( new Dimension(400, 300) );
jLabel1.setText("Currently saved games :");
jLabel1.setBounds(new Rectangle(15, 10, 220, 35));
list1.setBounds(new Rectangle(15, 55, 258, 130));
this.initGamesList();
list1.addMouseListener(new MouseListener (){
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2){
new staticData(1);
// TODO
// staticData.player = (Manager)dbImporting.loadSavedGame(list1.getSelectedItem())[0].getFirst();
staticData.atlet = dbImporting.loadSavedGame(list1.getSelectedItem())[1];
staticData.managers = dbImporting.loadSavedGame(list1.getSelectedItem())[2];
staticData.competitii = dbImporting.loadSavedGame(list1.getSelectedItem())[3];
staticData.player.age = staticData.dataCurenta.an - staticData.player.dataNasterii.an ;
for (Atlet atl : staticData.atlet)
atl.age = staticData.dataCurenta.an - atl.dataNasterii.an;
for (Manager man : staticData.managers)
man.age = staticData.dataCurenta.an - man.dataNasterii.an;
JOptionPane.showMessageDialog(new JFrame(), "Game Loaded!", "Loading...", JOptionPane.PLAIN_MESSAGE);
new ManagerHome();
LoadGame.this.dispose();
}
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
jButton1.setText("load");
jButton1.setBounds(new Rectangle(285, 60, 105, 25));
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton1_actionPerformed(e);
}
});
this.getContentPane().add(jButton1, null);
this.getContentPane().add(list1, null);
this.getContentPane().add(jLabel1, null);
this.setVisible(true);
}
public void initGamesList(){
File dir = new File("Saved");
String[] saves = dir.list();
for (String game : saves) {game = game.substring(0, game.length()-4); list1.add(game);}
}
private void jButton1_actionPerformed(ActionEvent e) {
new staticData(1);
// TODO
// staticData.player = (Manager)dbImporting.loadSavedGame(list1.getSelectedItem())[0].getFirst();
staticData.atlet = dbImporting.loadSavedGame(list1.getSelectedItem())[1];
staticData.managers = dbImporting.loadSavedGame(list1.getSelectedItem())[2];
staticData.competitii = dbImporting.loadSavedGame(list1.getSelectedItem())[3];
staticData.player.age = staticData.dataCurenta.an - staticData.player.dataNasterii.an ;
for (Atlet atl : staticData.atlet)
atl.age = staticData.dataCurenta.an - atl.dataNasterii.an;
for (Manager man : staticData.managers)
man.age = staticData.dataCurenta.an - man.dataNasterii.an;
JOptionPane.showMessageDialog(this, "Game Loaded!", "Loading...", JOptionPane.PLAIN_MESSAGE);
this.dispose();
new ManagerHome();
}
}
| Java |
package GUI;
import BackendSimulation.*;
import ImportsAndExports.*;
import java.awt.Dimension;
import java.awt.PopupMenu;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
public class CompetitionPage extends JFrame {
private JTable jTable1 = new JTable(new TabelAtleti());
private JLabel competitionNameLabel = new JLabel();
private JLabel competitionSetByLabel = new JLabel();
private JLabel competitionRecordLabel = new JLabel();
private JLabel competitionDateLabel = new JLabel();
private JLabel jLabel2 = new JLabel();
private JLabel jLabel3 = new JLabel();
private JLabel jLabel1 = new JLabel();
private JLabel competitionClassLabel = new JLabel();
private Competition competition = new Competition();
private JScrollPane jScrollPane1 = new JScrollPane(jTable1);
static int passUid;
private JButton jButton1 = new JButton();
private JButton jButton2 = new JButton();
private JButton jButton3 = new JButton();
public CompetitionPage(int uid) {
try {
jbInit(uid);
} catch (Exception e) {
e.printStackTrace();
}
}
public CompetitionPage() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
private void jbInit(int uid) throws Exception {
passUid = uid;
this.getContentPane().setLayout( null );
this.setSize(new Dimension(403, 338));
competitionNameLabel.setText("jLabel1");
competitionNameLabel.setBounds(new Rectangle(10, 5, 245, 20));
competitionSetByLabel.setText("jLabel4");
competitionSetByLabel.setBounds(new Rectangle(130, 90, 260, 15));
competitionRecordLabel.setText("jLabel4");
competitionRecordLabel.setBounds(new Rectangle(130, 70, 260, 15));
competitionDateLabel.setText("jLabel4");
competitionDateLabel.setBounds(new Rectangle(95, 50, 130, 15));
jLabel2.setText("Date : ");
jLabel2.setBounds(new Rectangle(10, 50, 85, 15));
jLabel3.setText("Set by :");
jLabel3.setBounds(new Rectangle(5, 90, 120, 15));
jLabel1.setText("Current Record :");
jLabel1.setBounds(new Rectangle(5, 70, 120, 15));
competitionClassLabel.setText("jLabel1");
competitionClassLabel.setBounds(new Rectangle(10, 25, 245, 20));
jScrollPane1.setBounds(new Rectangle(10, 120, 365, 145));
jButton1.setText("jButton1");
jButton1.setBounds(new Rectangle(10, 280, 105, 20));
jButton2.setText("view results");
jButton2.setBounds(new Rectangle(135, 280, 100, 20));
jButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton2_actionPerformed(e);
}
});
jButton3.setText("skip competition");
jButton3.setBounds(new Rectangle(255, 280, 100, 20));
jButton3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton3_actionPerformed(e);
}
});
jScrollPane1.getViewport().add(jTable1, null);
this.getContentPane().add(jButton3, null);
this.getContentPane().add(jButton2, null);
this.getContentPane().add(jButton1, null);
this.getContentPane().add(jScrollPane1, null);
this.getContentPane().add(competitionClassLabel, null);
this.getContentPane().add(jLabel1, null);
this.getContentPane().add(jLabel3, null);
this.getContentPane().add(jLabel2, null);
this.getContentPane().add(competitionDateLabel, null);
this.getContentPane().add(competitionRecordLabel, null);
this.getContentPane().add(competitionSetByLabel, null);
this.getContentPane().add(competitionNameLabel, null);
this.importCompetition(uid);
this.setAll();
this.setVisible(true);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
this_windowClosed(e);
}
});
}
private void importCompetition(int uid) {
this.competition = staticData.competitii.get(uid);
}
private void setAll() {
this.competitionNameLabel.setText(competition.numeleConcursului + ", " + competition.orasulConcursului);
this.competitionClassLabel.setText(competition.numeClasa[competition.clasa - 1]);
this.competitionDateLabel.setText(competition.dataConcursului.dateToString());
this.competitionRecordLabel.setText(competition.record + "");
this.competitionSetByLabel.setText(competition.numeDetinator + ", " + competition.dataRecordului.dateToString());
}
private void jbInit() throws Exception {
/* this.getContentPane().setLayout( null );
this.setSize(new Dimension(403, 338));
competitionNameLabel.setText("jLabel1");
competitionNameLabel.setBounds(new Rectangle(10, 5, 245, 20));
competitionSetByLabel.setText("jLabel4");
competitionSetByLabel.setBounds(new Rectangle(130, 90, 260, 15));
competitionRecordLabel.setText("jLabel4");
competitionRecordLabel.setBounds(new Rectangle(130, 70, 260, 15));
competitionDateLabel.setText("jLabel4");
competitionDateLabel.setBounds(new Rectangle(95, 50, 130, 15));
jLabel2.setText("Date : ");
jLabel2.setBounds(new Rectangle(10, 50, 85, 15));
jLabel3.setText("Set by :");
jLabel3.setBounds(new Rectangle(5, 90, 120, 15));
jLabel1.setText("Current Record :");
jLabel1.setBounds(new Rectangle(5, 70, 120, 15));
competitionClassLabel.setText("jLabel1");
competitionClassLabel.setBounds(new Rectangle(10, 25, 245, 20));
jScrollPane1.setBounds(new Rectangle(10, 120, 365, 145));
jButton1.setText("jButton1");
jButton1.setBounds(new Rectangle(10, 280, 105, 20));
jButton2.setText("view results");
jButton2.setBounds(new Rectangle(135, 280, 100, 20));
jButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton2_actionPerformed(e);
}
});
jButton3.setText("skip competition");
jButton3.setBounds(new Rectangle(255, 280, 100, 20));
jButton3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton3_actionPerformed(e);
}
});
jScrollPane1.getViewport().add(jTable1, null);
this.getContentPane().add(jButton3, null);
this.getContentPane().add(jButton2, null);
this.getContentPane().add(jButton1, null);
this.getContentPane().add(jScrollPane1, null);
this.getContentPane().add(competitionClassLabel, null);
this.getContentPane().add(jLabel1, null);
this.getContentPane().add(jLabel3, null);
this.getContentPane().add(jLabel2, null);
this.getContentPane().add(competitionDateLabel, null);
this.getContentPane().add(competitionRecordLabel, null);
this.getContentPane().add(competitionSetByLabel, null);
this.getContentPane().add(competitionNameLabel, null);
this.importCompetition(0);
this.setAll();
this.setVisible(true);
this.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
this_windowClosed(e);
}
});*/
}
private void jButton2_actionPerformed(ActionEvent e) {
new CompetitionResultsPage(passUid);
this.dispose();
System.out.println("Action has been performed");
}
private void jButton3_actionPerformed(ActionEvent e) {
CompetitionResultsPage p = new CompetitionResultsPage(passUid);
p.checkAndSetRecords();
p.dispose();
this.dispose();
}
private void this_windowClosed(WindowEvent e) {
System.out.println("Window closed :D");
CompetitionResultsPage p = new CompetitionResultsPage(passUid);
p.checkAndSetRecords();
p.dispose();
new ManagerHome();
}
private class TabelAtleti extends AbstractTableModel {
private String[] columnNames = { "Nume", "Prenume", "Varsta" };
private Object[][] date = null;
public TabelAtleti() {
loadData();
}
public void loadData() {
if (staticData.competitii.get(passUid).atletiInscrisi != null)
{
date = new Object[staticData.competitii.get(passUid).atletiInscrisi.size()][4];
for (int i = 0; i < staticData.competitii.get(passUid).atletiInscrisi.size(); i++) {
date[i][0] = staticData.atlet.get(i).firstName;
date[i][1] = staticData.atlet.get(i).lastName;
date[i][2] = staticData.atlet.get(i).age;
date[i][3] = staticData.atlet.get(i).uniqueID;
}
}
else {
date = new Object[1][4];
date[0][0] = "a";
date[0][1] = "b";
date[0][2] = "c";
date[0][3] = "none";
}
}
@Override
public int findColumn(String columnName) {
for (int i = 0; i < columnNames.length; i++)
if (columnName == columnNames[i])
return i;
return -1;
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public int getRowCount() {
return date.length;
}
@Override
public String getColumnName(int col) {
return columnNames[col];
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return date[rowIndex][columnIndex];
}
@Override
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
}
}
| Java |
package GUI;
import ImportsAndExports.*;
import BackendSimulation.*;
import BackendSimulation.Data;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import oracle.jdeveloper.layout.BoxLayout2;
import oracle.jdeveloper.layout.OverlayLayout2;
public class AthletePage extends JFrame {
private Atlet atlet ;
private JTabbedPane jTabbedPane1 = new JTabbedPane();
private JPanel details = new JPanel();
private JLabel dataNasteriiLabel = new JLabel();
private JLabel contractedUntilLabel = new JLabel();
private JLabel contractedToLabel = new JLabel();
private JLabel seasonBestSetOnLabel = new JLabel();
private JLabel personalBestSetOnLabel = new JLabel();
private JLabel seasonBestLabel = new JLabel();
private JLabel personalBestLabel = new JLabel();
private JLabel concentrationLabel = new JLabel();
private JLabel fitnessLabel = new JLabel();
private JLabel moraleLabel = new JLabel();
private JLabel paceLabel = new JLabel();
private JLabel reactionLabel = new JLabel();
private JLabel jLabel10 = new JLabel();
private JLabel jLabel9 = new JLabel();
private JLabel jLabel8 = new JLabel();
private JLabel jLabel7 = new JLabel();
private JLabel jLabel6 = new JLabel();
private JLabel jLabel5 = new JLabel();
private JLabel speedLabel = new JLabel();
private JLabel accelerationLabel = new JLabel();
private JLabel jLabel2 = new JLabel();
private JLabel numeSiPrenume = new JLabel();
private BoxLayout2 boxLayout21 = new BoxLayout2();
private JPanel jPanel1 = new JPanel();
private JLabel jLabel1 = new JLabel();
private JTable jTable1 ;
private JScrollPane jScrollPane1 = new JScrollPane(jTable1);// DEBUG AND TESTING PURPOSES
public static int uid;
// Testing purposes
public AthletePage(int uid) {
try {
jbInit(uid);
} catch (Exception e) {
e.printStackTrace();
}
}
public AthletePage() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
private void jbInit(int uid) throws Exception {
this.uid = uid;
this.importAthlete(uid);
this.getContentPane().setLayout(boxLayout21);
this.setSize( new Dimension(400, 300) );
this.setVisible(true);
details.setLayout(null);
dataNasteriiLabel.setText("jLabel1");
dataNasteriiLabel.setBounds(new Rectangle(10, 30, 235, 15));
contractedUntilLabel.setText("Until : ");
contractedUntilLabel.setBounds(new Rectangle(255, 120, 125, 15));
contractedToLabel.setText("Contracted to :");
contractedToLabel.setBounds(new Rectangle(255, 135, 135, 15));
seasonBestSetOnLabel.setText("jLabel19");
seasonBestSetOnLabel.setBounds(new Rectangle(75, 95, 300, 15));
personalBestSetOnLabel.setText("jLabel18");
personalBestSetOnLabel.setBounds(new Rectangle(85, 65, 240, 15));
seasonBestLabel.setText("Season Best : ");
seasonBestLabel.setBounds(new Rectangle(10, 80, 180, 15));
personalBestLabel.setText("Personal Best : ");
personalBestLabel.setBounds(new Rectangle(10, 50, 185, 15));
concentrationLabel.setText("jLabel3");
concentrationLabel.setBounds(new Rectangle(95, 165, 35, 15));
fitnessLabel.setText("jLabel3");
fitnessLabel.setBounds(new Rectangle(95, 195, 35, 15));
moraleLabel.setText("jLabel3");
moraleLabel.setBounds(new Rectangle(95, 210, 35, 15));
paceLabel.setText("jLabel3");
paceLabel.setBounds(new Rectangle(95, 150, 35, 15));
reactionLabel.setText("jLabel3");
reactionLabel.setBounds(new Rectangle(95, 180, 40, 15));
jLabel10.setText("Morale");
jLabel10.setBounds(new Rectangle(10, 210, 60, 15));
jLabel9.setText("Fitness");
jLabel9.setBounds(new Rectangle(10, 195, 45, 15));
jLabel8.setText("Concentration");
jLabel8.setBounds(new Rectangle(10, 165, 75, 15));
jLabel7.setText("Pace");
jLabel7.setBounds(new Rectangle(10, 150, 45, 15));
jLabel6.setText("Reaction");
jLabel6.setBounds(new Rectangle(10, 180, 65, 15));
jLabel5.setText("Speed");
jLabel5.setBounds(new Rectangle(10, 120, 55, 15));
speedLabel.setText("jLabel3");
speedLabel.setBounds(new Rectangle(95, 120, 50, 15));
accelerationLabel.setText("jLabel3");
accelerationLabel.setBounds(new Rectangle(95, 135, 45, 15));
jLabel2.setText("Acceleration");
jLabel2.setBounds(new Rectangle(10, 135, 60, 15));
numeSiPrenume.setText("jLabel1");
numeSiPrenume.setBounds(new Rectangle(10, 10, 360, 15));
jPanel1.setLayout(null);
jLabel1.setText("Competition History :");
jLabel1.setBounds(new Rectangle(10, 5, 325, 15));
jScrollPane1.setBounds(new Rectangle(15, 35, 365, 195));
details.add(dataNasteriiLabel, null);
details.add(contractedUntilLabel, null);
details.add(seasonBestSetOnLabel, null);
details.add(personalBestSetOnLabel, null);
details.add(seasonBestLabel, null);
details.add(personalBestLabel, null);
details.add(concentrationLabel, null);
details.add(fitnessLabel, null);
details.add(moraleLabel, null);
details.add(paceLabel, null);
details.add(reactionLabel, null);
details.add(jLabel10, null);
details.add(jLabel9, null);
details.add(jLabel8, null);
details.add(jLabel7, null);
details.add(jLabel5, null);
details.add(speedLabel, null);
details.add(accelerationLabel, null);
details.add(jLabel2, null);
details.add(numeSiPrenume, null);
details.add(jLabel6, null);
details.add(contractedToLabel, null);
jTabbedPane1.addTab("details", details);
this.jTable1 = new JTable(new IstoricTabel(uid));
jScrollPane1.getViewport().add(jTable1, null);
jPanel1.add(jScrollPane1, null);
jPanel1.add(jLabel1, null);
jTabbedPane1.addTab("History", jPanel1);
this.getContentPane().add(jTabbedPane1, null);
this.setAll();
this.setVisible(true);
}
private void importAthlete(int uid) {
this.atlet = staticData.atlet.get(uid);
}
private void setAll(){
this.numeSiPrenume.setText(atlet.firstName + " " + atlet.lastName + ", " + atlet.age + " years, " + atlet.nationality);
this.dataNasteriiLabel.setText("Data nasterii : " + atlet.dataNasterii.dateToString());
this.personalBestLabel.setText("Personal Best : " + atlet.personalBest);
this.personalBestSetOnLabel.setText(atlet.personalBestDate.dateToString() + " " + atlet.personalBestLocation);
this.seasonBestLabel.setText("Season Best : " + atlet.seasonBest);
this.seasonBestSetOnLabel.setText(atlet.seasonBestDate.dateToString() + " " + atlet.seasonBestLocation);
this.accelerationLabel.setText(String.valueOf(atlet.acceleration));
this.speedLabel.setText(String.valueOf(atlet.speed));
this.paceLabel.setText(String.valueOf(atlet.pace));
this.reactionLabel.setText(String.valueOf(atlet.reaction));
this.concentrationLabel.setText(String.valueOf(atlet.concentration));
this.fitnessLabel.setText(String.valueOf(atlet.fitness));
this.moraleLabel.setText(String.valueOf(atlet.morale));
}
private void initiateTables(){
this.jTable1.setModel(new IstoricTabel(uid));
this.jTabbedPane1.repaint();
}
private void jbInit() throws Exception {
this.importAthlete(0);
this.getContentPane().setLayout(boxLayout21);
this.setSize( new Dimension(400, 300) );
this.setVisible(true);
details.setLayout(null);
dataNasteriiLabel.setText("jLabel1");
dataNasteriiLabel.setBounds(new Rectangle(10, 30, 235, 15));
contractedUntilLabel.setText("Until : ");
contractedUntilLabel.setBounds(new Rectangle(255, 120, 125, 15));
contractedToLabel.setText("Contracted to :");
contractedToLabel.setBounds(new Rectangle(255, 135, 135, 15));
seasonBestSetOnLabel.setText("jLabel19");
seasonBestSetOnLabel.setBounds(new Rectangle(75, 95, 300, 15));
personalBestSetOnLabel.setText("jLabel18");
personalBestSetOnLabel.setBounds(new Rectangle(85, 65, 240, 15));
seasonBestLabel.setText("Season Best : ");
seasonBestLabel.setBounds(new Rectangle(10, 80, 180, 15));
personalBestLabel.setText("Personal Best : ");
personalBestLabel.setBounds(new Rectangle(10, 50, 185, 15));
concentrationLabel.setText("jLabel3");
concentrationLabel.setBounds(new Rectangle(95, 165, 35, 15));
fitnessLabel.setText("jLabel3");
fitnessLabel.setBounds(new Rectangle(95, 195, 35, 15));
moraleLabel.setText("jLabel3");
moraleLabel.setBounds(new Rectangle(95, 210, 35, 15));
paceLabel.setText("jLabel3");
paceLabel.setBounds(new Rectangle(95, 150, 35, 15));
reactionLabel.setText("jLabel3");
reactionLabel.setBounds(new Rectangle(95, 180, 40, 15));
jLabel10.setText("Morale");
jLabel10.setBounds(new Rectangle(10, 210, 60, 15));
jLabel9.setText("Fitness");
jLabel9.setBounds(new Rectangle(10, 195, 45, 15));
jLabel8.setText("Concentration");
jLabel8.setBounds(new Rectangle(10, 165, 75, 15));
jLabel7.setText("Pace");
jLabel7.setBounds(new Rectangle(10, 150, 45, 15));
jLabel6.setText("Reaction");
jLabel6.setBounds(new Rectangle(10, 180, 65, 15));
jLabel5.setText("Speed");
jLabel5.setBounds(new Rectangle(10, 120, 55, 15));
speedLabel.setText("jLabel3");
speedLabel.setBounds(new Rectangle(95, 120, 50, 15));
accelerationLabel.setText("jLabel3");
accelerationLabel.setBounds(new Rectangle(95, 135, 45, 15));
jLabel2.setText("Acceleration");
jLabel2.setBounds(new Rectangle(10, 135, 60, 15));
numeSiPrenume.setText("jLabel1");
numeSiPrenume.setBounds(new Rectangle(10, 10, 360, 15));
jPanel1.setLayout(null);
jLabel1.setText("Competition History :");
jLabel1.setBounds(new Rectangle(10, 5, 325, 15));
jScrollPane1.setBounds(new Rectangle(15, 35, 365, 195));
details.add(dataNasteriiLabel, null);
details.add(contractedUntilLabel, null);
details.add(seasonBestSetOnLabel, null);
details.add(personalBestSetOnLabel, null);
details.add(seasonBestLabel, null);
details.add(personalBestLabel, null);
details.add(concentrationLabel, null);
details.add(fitnessLabel, null);
details.add(moraleLabel, null);
details.add(paceLabel, null);
details.add(reactionLabel, null);
details.add(jLabel10, null);
details.add(jLabel9, null);
details.add(jLabel8, null);
details.add(jLabel7, null);
details.add(jLabel5, null);
details.add(speedLabel, null);
details.add(accelerationLabel, null);
details.add(jLabel2, null);
details.add(numeSiPrenume, null);
details.add(jLabel6, null);
details.add(contractedToLabel, null);
jTabbedPane1.addTab("details", details);
jScrollPane1.getViewport().add(jTable1, null);
jPanel1.add(jScrollPane1, null);
jPanel1.add(jLabel1, null);
jTabbedPane1.addTab("History", jPanel1);
this.getContentPane().add(jTabbedPane1, null);
this.setAll();
this.setVisible(true);
}
class IstoricTabel extends AbstractTableModel{
private String[] columnNames = { "Count","Timp" };
private Object[][] date = new Object[staticData.atlet.get(uid).history.size()][2];
public IstoricTabel(int uid) {
loadData(uid);
}
public void loadData(int uid) {
System.out.println(staticData.atlet.get(uid).history.size());
for (int i=0;i<staticData.atlet.get(uid).history.size();i++) {
date[i][0] = i;
date[i][1] = staticData.atlet.get(uid).history.get(i);
System.out.println("UID : "+ uid);
System.out.println("Debug : "+staticData.atlet.get(uid).history.get(i));
}
}
@Override
public int findColumn(String columnName) {
for (int i = 0; i < columnNames.length; i++)
if (columnName == columnNames[i])
return i;
return -1;
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public int getRowCount() {
return date.length;
}
@Override
public String getColumnName(int col) {
return columnNames[col];
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return date[rowIndex][columnIndex];
}
@Override
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
}
}
| Java |
package GUI;
import BackendSimulation.*;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Label;
import java.awt.List;
import java.awt.Rectangle;
import java.awt.ScrollPane;
import java.awt.GridLayout;
import java.awt.Scrollbar;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumn;
public class Clasament extends JFrame {
private JTable jTable1 = new JTable(new TabelAtleti());
private JScrollPane jScrollPane1;
public Clasament() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
this.rutineTabel();
jScrollPane1 = new JScrollPane(jTable1);
this.getContentPane().setLayout(null);
this.setSize(new Dimension(400, 300));
jScrollPane1.setBounds(new Rectangle(10, 25, 375, 230));
this.getContentPane().add(jScrollPane1, null);
this.jTable1.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
new AthletePage(Integer.valueOf((jTable1.getValueAt(jTable1.getSelectedRow(), 0)).toString()));
}
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
this.jScrollPane1.repaint();
this.setVisible(true);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
this_windowClosing(e);
}
});
}
public void rutineTabel() {
jTable1.setAutoCreateRowSorter(true);
jTable1.setDragEnabled(false);
this.jTable1.setAutoResizeMode(this.jTable1.AUTO_RESIZE_OFF);
TableColumn aux = this.jTable1.getColumnModel().getColumn(0);
aux.setPreferredWidth(0);
}
private void this_windowClosing(WindowEvent e) {
new ManagerHome();
}
// CLASA TABEL ATLETI !!!
class TabelAtleti extends AbstractTableModel {
private String[] columnNames = { "UID", "Nume", "Prenume", "Nationalitate", "Season Best", "Personal Best" };
private Object[][] date = new Object[staticData.atlet.size()][6];
public TabelAtleti() {
loadData();
}
public void loadData() {
for (int i = 0; i < staticData.atlet.size(); i++) {
date[i][0] = staticData.atlet.get(i).uniqueID;
date[i][1] = staticData.atlet.get(i).firstName;
date[i][2] = staticData.atlet.get(i).lastName;
date[i][3] = staticData.atlet.get(i).nationality;
date[i][4] = staticData.atlet.get(i).seasonBest;
date[i][5] = staticData.atlet.get(i).personalBest;
}
date = sortData(date);
}
public Object[][] sortData(Object[][] data) {
for (int i = 0; i < staticData.atlet.size() - 1; i++)
for (int j = i + 1; j < staticData.atlet.size(); j++)
if (Float.parseFloat(data[i][4].toString()) > Float.parseFloat(data[j][4].toString())) {
Object[] aux = new Object[6];
for (int i2 = 0; i2 < 6; i2++)
aux[i2] = data[i][i2];
for (int i2 = 0; i2 < 6; i2++)
data[i][i2] = data[j][i2];
for (int i2 = 0; i2 < 6; i2++)
data[j][i2] = aux[i2];
}
return data;
}
@Override
public int findColumn(String columnName) {
for (int i = 0; i < columnNames.length; i++)
if (columnName == columnNames[i])
return i;
return -1;
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public int getRowCount() {
return date.length;
}
@Override
public String getColumnName(int col) {
return columnNames[col];
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return date[rowIndex][columnIndex];
}
@Override
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
}
}
| Java |
package GUI;
import java.awt.Dimension;
import javax.swing.JFrame;
public class CompetitionHistory extends JFrame {
public CompetitionHistory() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
this.getContentPane().setLayout( null );
this.setSize( new Dimension(400, 300) );
}
}
| Java |
package GUI;
import BackendSimulation.Atlet;
import BackendSimulation.Brackets;
import BackendSimulation.staticData;
import java.awt.Choice;
import java.awt.Dimension;
import java.awt.Container;
import java.awt.Rectangle;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.LinkedList;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTable;
import javax.swing.SpinnerListModel;
import javax.swing.table.AbstractTableModel;
import javax.swing.SpinnerDateModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class CompetitionResultsPage extends JFrame {
private static LinkedList<LinkedList<Atlet>> competitie ;
private static int competitionLevel = 0;
private static int levelIterator = 0;
private static int timeIterator = 0;
private JTable jTable1 = new JTable();
private JScrollPane jScrollPane1 = new JScrollPane();
private JSpinner jSpinner1 = new JSpinner();
private JSpinner jSpinner2 = new JSpinner();
static int uid;
public CompetitionResultsPage(int id) {
try {
jbInit(id);
} catch (Exception e) {
e.printStackTrace();
}
}
private void jbInit(int id) throws Exception {
this.addWindowListener(new WindowAdapter() {
public void windowOpened(WindowEvent e) {
this_windowOpened(e);
}
});
competitie = new Brackets(id).comp;
staticData.competitii.get(id).rezultate = competitie;
uid = id;
this.initSpinner1();
this.initSpinner2();
this.getContentPane().setLayout( null );
this.setSize(new Dimension(423, 328));
jScrollPane1.setBounds(new Rectangle(20, 100, 375, 185));
jSpinner1.setBounds(new Rectangle(200, 30, 95, 20));
jSpinner1.addChangeListener(new ChangeListener(){
public void stateChanged(ChangeEvent e){
jSpinner1_stateChanged(e);
}
});
jSpinner2.setBounds(new Rectangle(330, 30, 60, 20));
jSpinner2.addChangeListener(new ChangeListener(){
public void stateChanged(ChangeEvent e){
jSpinner2_stateChanged(e);
}
});
jScrollPane1.getViewport().add(jTable1, null);
this.getContentPane().add(jSpinner2, null);
this.getContentPane().add(jSpinner1, null);
this.getContentPane().add(jScrollPane1, null);
this.setVisible(true);
this.addWindowListener(new WindowAdapter() {
public void windowOpened(WindowEvent e) {
this_windowOpened(e);
}
public void windowDeactivated(WindowEvent e) {
this_windowDeactivated(e);
}
});
//this.debugData();
}
public void checkAndSetRecords(){
/*int iter1=0,iter2=0; // probleme la iterator, trebuiesc facute cazuri
switch (staticData.competitii.get(0).clasa){
case 1: {iter1=0;iter2 = 0; break;} case 2: {iter1=0;iter2 = 0; break;} case 3: {iter1=32;iter2 = 0; break;} case 4: {iter1=32;iter2 = 0; break;}
case 5: {iter1=48;iter2 = 1; break;} case 6: {iter1=56;iter2 = 2; break;} case 7: {iter1=60;iter2 = 3; break;} case 8: {iter1=62;iter2 = 4; break;}
}
for (int i= iter1;i<63;i++) {
if (iter1 == 32 || iter1 == 48 || iter1 == 56 || iter1 == 60 || iter1 == 62) {iter2++;}
for (int j=0;j<8;j++) {System.out.println("Verificari : "+ (Float.compare(competitie.get(i).get(j).competitionTime[iter2],new Float(0))));
if ((competitie.get(i).get(j).competitionTime[iter2] < competitie.get(i).get(j).personalBest) && (competitie.get(i).get(j).competitionTime[iter2] != 0f) )
{competitie.get(i).get(j).setNewPersonalBest(competitie.get(i).get(j).competitionTime[iter2], staticData.competitii.get(0)); }
if ((competitie.get(i).get(j).competitionTime[iter2] < competitie.get(i).get(j).seasonBest) && (competitie.get(i).get(j).competitionTime[iter2] != 0f) )
{competitie.get(i).get(j).setNewSeasonBest(competitie.get(i).get(j).competitionTime[iter2], staticData.competitii.get(0)); }
if ((competitie.get(i).get(j).competitionTime[iter2] < staticData.competitii.get(0).record) && (competitie.get(i).get(j).competitionTime[iter2] != 0f))
{staticData.competitii.get(0).setNewRecord(competitie.get(i).get(j), competitie.get(i).get(j).competitionTime[iter2], staticData.dataCurenta); }
}
}
*/
for (int i : staticData.competitii.get(uid).atletiInscrisi) {
for (float f : staticData.atlet.get(i).history)
{
if (f < staticData.atlet.get(i).personalBest)
{
staticData.atlet.get(i).setNewPersonalBest(f, staticData.competitii.get(0));
staticData.atlet.get(i).setNewSeasonBest(f, staticData.competitii.get(0));
}
if (f < staticData.atlet.get(i).seasonBest)
staticData.atlet.get(i).setNewSeasonBest(f, staticData.competitii.get(0));
if (f < staticData.recordMondial){
staticData.setNewWR(f, staticData.atlet.get(i), staticData.competitii.get(0));
}
}
}
for (int i : staticData.competitii.get(uid).atletiInscrisi) {
for (float f : staticData.atlet.get(i).history)
if (f < staticData.competitii.get(uid).record)
staticData.competitii.get(uid).setNewRecord(staticData.atlet.get(i),f,staticData.dataCurenta);
}
}
private void debugData(){
for (LinkedList<Atlet> lista : competitie)
if (lista.isEmpty() == false)
for (Atlet a : lista)
for (float f : a.competitionTime)
System.out.println(a.firstName+" "+f);
}
private void jSpinner2_stateChanged(ChangeEvent e){
if (jSpinner2.getValue().toString().equals("Finala")) {levelIterator = 0;}
else
{
for (int i=1;i<=32;i++)
{
if (Integer.valueOf(jSpinner2.getValue().toString()) == i ) {levelIterator = i-1;}
}
}
jTable1.setModel(new TabelAtleti());
jScrollPane1.repaint();
System.out.println("DebugTest: "+(competitionLevel+levelIterator));
}
private void this_windowOpened(WindowEvent e) {
System.out.println("Window has been opened");
this.addResultsHistory();
this.checkAndSetRecords();
}
private void jSpinner1_stateChanged(ChangeEvent e){
System.out.println("Event fired !");
levelIterator = 0;
this.initSpinner2();
jTable1.setModel(new TabelAtleti());
jScrollPane1.repaint();
}
private void initSpinner2(){
String value = jSpinner1.getValue().toString();
String[] toInsert = null;
SpinnerListModel model = null;
if (value.equalsIgnoreCase("Seria")) {
competitionLevel = 0;toInsert = new String[32]; for (int i=1;i<=32;i++) {toInsert[i-1] = i+"";}
timeIterator = 0;
}
if (value.equalsIgnoreCase("Saisprezecimea")) {
competitionLevel = 32;toInsert = new String[16]; for (int i=1;i<=16;i++) {toInsert[i-1] = i+"";}
timeIterator = 1;
}
if (value.equalsIgnoreCase("Optimea")) {
competitionLevel = 49;toInsert = new String[8]; for (int i=1;i<=8;i++) {toInsert[i-1] = i+"";}
timeIterator = 2;
}
if (value.equalsIgnoreCase("Sfertul")) {
competitionLevel = 56;toInsert = new String[4]; for (int i=1;i<=4;i++) {toInsert[i-1] = i+"";}
timeIterator = 3;
}
if (value.equalsIgnoreCase("Semifinala")) {
competitionLevel = 60;toInsert = new String[2]; for (int i=1;i<=2;i++) {toInsert[i-1] = i+"";}
timeIterator = 4;
}
if (value.equalsIgnoreCase("Finala")) {
competitionLevel = 62;toInsert = new String[1]; for (int i=1;i<=1;i++) {toInsert[i-1] = "Finala";}
timeIterator = 5;
}
model = new SpinnerListModel(toInsert);
jSpinner2.setModel(model);
jSpinner2.repaint();
}
private void initSpinner1(){
String[] etape = {"Seria","Saisprezecimea","Optimea","Sfertul","Semifinala","Finala"};
String[] etapeSpinner = null;
SpinnerListModel model = null;
switch (staticData.competitii.get(uid).clasa) {
case 1 : {timeIterator = 0;etapeSpinner = new String[6];etapeSpinner = etape; break;}
case 2 : {timeIterator = 0;etapeSpinner = new String[6];etapeSpinner = etape; break;}
case 3 : {timeIterator = 1;competitionLevel = 32;etapeSpinner = new String[5];etapeSpinner[0] ="Saisprezecimea" ;etapeSpinner[1] ="Optimea" ;etapeSpinner[2] ="Sfertul" ;etapeSpinner[3] = "Semifinala" ;etapeSpinner[4] = "Finala"; break;}
case 4 : {timeIterator = 2;competitionLevel = 48;etapeSpinner = new String[4];etapeSpinner[0] ="Optimea" ;etapeSpinner[1] ="Sfertul" ;etapeSpinner[2] ="Semifinala" ;etapeSpinner[3] ="Finala" ; break;}
case 5 : {timeIterator = 3;competitionLevel = 56;etapeSpinner = new String[3];etapeSpinner[0] ="Sfertul" ;etapeSpinner[1] ="Semifinala" ;etapeSpinner[2] ="Finala" ; break;}
// case 6 : {timeIterator = 3;competitionLevel = 60;etapeSpinner = new String[3];etapeSpinner[0] = new String(etape[3]); etapeSpinner[1] = new String (etape[4]); etapeSpinner[2] = new String(etape[5]) ;break; }
// case 7 : {timeIterator = 4;competitionLevel = 60;etapeSpinner = new String[2];etapeSpinner[0] = new String(etape[4]); etapeSpinner[1] = new String(etape[5]); break;}
// case 8 : {timeIterator = 5;competitionLevel = 62;etapeSpinner = new String[1];etapeSpinner[0] = new String(etape[5]); jSpinner2 = new JSpinner(new SpinnerListModel(etapeSpinner)); break;}
}
System.out.println("SpinnerSize : "+etapeSpinner.length);
System.out.println("CompLevel : "+competitionLevel);
model = new SpinnerListModel(etapeSpinner);
jSpinner1.setModel(model);
jSpinner1.repaint();
jTable1.setModel(new TabelAtleti());
jScrollPane1.repaint();
}
private void addResultsHistory() {
for (int i : staticData.competitii.get(uid).atletiInscrisi)
{
LinkedList<Float> rv = new LinkedList<Float>();
for (int j=0;j<staticData.atlet.get(i).competitionTime.length;j++) {
if (staticData.atlet.get(i).competitionTime[j] != 0f)
rv.add(staticData.atlet.get(i).competitionTime[j]);
}
staticData.atlet.get(i).history.addAll(rv);
}
}
private void this_windowDeactivated(WindowEvent e) {
System.out.println("Window has been deactivated");
this.dispose();
new ManagerHome();
}
private class TabelAtleti extends AbstractTableModel {
private String[] columnNames = { "Nume", "Prenume", "Timp", "UID" };
private Object[][] date = new Object[competitie.get(competitionLevel).size()][4];
public TabelAtleti() {
loadData();
}
public void loadData() {
int iter = 0;
competitie.set(competitionLevel+levelIterator, sortList(competitie.get(competitionLevel+levelIterator),timeIterator));
for (Atlet i : competitie.get(competitionLevel+levelIterator)) {
date[iter][0] = i.firstName;
date[iter][1] = i.lastName;
date[iter][2] = i.competitionTime[timeIterator];
date[iter][3] = i.uniqueID;
iter++;
}
fireTableDataChanged();
}
public LinkedList<Atlet> sortList(LinkedList<Atlet> lista,int iterator)
{
for (int i=0;i<lista.size()-1;i++)
for (int j=i+1;j<lista.size();j++)
if (lista.get(i).competitionTime[iterator] > lista.get(j).competitionTime[iterator])
{
Atlet aux = lista.get(i);
lista.set(i,lista.get(j));
lista.set(j, aux);
}
return lista;
}
@Override
public int findColumn(String columnName) {
for (int i = 0; i < columnNames.length; i++)
if (columnName == columnNames[i])
return i;
return -1;
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public int getRowCount() {
return date.length;
}
@Override
public String getColumnName(int col) {
return columnNames[col];
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return date[rowIndex][columnIndex];
}
@Override
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
}
}
| Java |
package GUI;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Options extends JFrame {
public boolean closeFlag = false;
public Options() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
this.getContentPane().setLayout( null );
this.setSize(new Dimension(388, 289));
this.setVisible(true);
this.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
this_windowClosed(e);
}
});
}
private void this_windowClosed(WindowEvent e) {
}
private void jButton1_actionPerformed(ActionEvent e) {
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.