code
stringlengths
3
1.18M
language
stringclasses
1 value
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.graphics.drawable.BitmapDrawable; 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.RelativeLayout.LayoutParams; 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 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.base; import android.app.Activity; import android.content.Intent; import android.graphics.drawable.AnimationDrawable; import android.graphics.drawable.BitmapDrawable; import android.text.TextPaint; import android.util.Log; import android.view.View; import android.view.ViewGroup; 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.RelativeLayout.LayoutParams; 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.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.MenuDialog; import com.ch_linghu.fanfoudroid.ui.module.NavBar; /** * @deprecated 使用 {@link NavBar} 代替 */ public class WithHeaderActivity extends BaseActivity { private static final String TAG = "WithHeaderActivity"; 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; protected ImageView refreshButton; protected ImageButton searchButton; protected ImageButton writeButton; protected TextView titleButton; protected Button backButton; protected ImageButton homeButton; protected MenuDialog dialog; protected EditText searchEdit; protected Feedback mFeedback; // FIXME: 刷新动画二选一, DELETE ME protected AnimationDrawable mRefreshAnimation; protected ProgressBar mProgress = null; protected ProgressBar mLoadingProgress = null; //搜索硬按键行为 @Override public boolean onSearchRequested() { Intent intent = new Intent(); intent.setClass(this, SearchActivity.class); startActivity(intent); return true; } // LOGO按钮 protected void addTitleButton() { titleButton = (TextView) findViewById(R.id.title); titleButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { int top = titleButton.getTop(); int height = titleButton.getHeight(); int x = top + height; if (null == dialog) { Log.d(TAG, "Create menu dialog."); dialog = new MenuDialog(WithHeaderActivity.this); dialog.bindEvent(WithHeaderActivity.this); dialog.setPosition(-1, x); } // toggle dialog if (dialog.isShowing()) { dialog.dismiss(); //没机会触发 } else { dialog.show(); } } }); } protected void setHeaderTitle(String title) { titleButton.setBackgroundDrawable( new BitmapDrawable()); titleButton.setText(title); LayoutParams lp = new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT,android.view.ViewGroup.LayoutParams.WRAP_CONTENT); lp.setMargins(3, 12, 0, 0); titleButton.setLayoutParams(lp); // 中文粗体 TextPaint tp = titleButton.getPaint(); tp.setFakeBoldText(true); } protected void setHeaderTitle(int resource) { titleButton.setBackgroundResource(resource); } // 刷新 protected void addRefreshButton() { final Activity that = this; refreshButton = (ImageView) findViewById(R.id.top_refresh); // FIXME: 暂时取消旋转效果, 测试ProgressBar //refreshButton.setBackgroundResource(R.drawable.top_refresh); //mRefreshAnimation = (AnimationDrawable) refreshButton.getBackground(); // FIXME: DELETE ME mProgress = (ProgressBar) findViewById(R.id.progress_bar); mLoadingProgress = (ProgressBar) findViewById(R.id.top_refresh_progressBar); mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS); refreshButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (that instanceof Refreshable) { ((Refreshable) that).doRetrieve(); } else { Log.e(TAG, "The current view " + that.getClass().getName() + " cann't be retrieved"); } } }); } /** * @param v * @deprecated use {@link WithHeaderActivity#setRefreshAnimation(boolean)} */ protected void animRotate(View v) { setRefreshAnimation(true); } /** * @param progress 0~100 * @deprecated use feedback */ public void setGlobalProgress(int progress) { if ( null != mProgress) { mProgress.setProgress(progress); } } /** * 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"); } } // 搜索 protected void addSearchButton() { searchButton = (ImageButton) findViewById(R.id.search); searchButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // // 旋转动画 // Animation anim = AnimationUtils.loadAnimation(v.getContext(), // R.anim.scale_lite); // v.startAnimation(anim); //go to SearchActivity startSearch(); } }); } // 这个方法会在SearchActivity里重写 protected boolean startSearch() { Intent intent = new Intent(); intent.setClass(this, SearchActivity.class); startActivity(intent); return true; } //搜索框 protected void addSearchBox() { searchEdit = (EditText) findViewById(R.id.search_edit); } // 撰写 protected void addWriteButton() { writeButton = (ImageButton) findViewById(R.id.writeMessage); writeButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // 动画 Animation anim = AnimationUtils.loadAnimation(v.getContext(), R.anim.scale_lite); v.startAnimation(anim); // forward to write activity Intent intent = new Intent(); intent.setClass(v.getContext(), WriteActivity.class); v.getContext().startActivity(intent); } }); } // 回首页 protected void addHomeButton() { homeButton = (ImageButton) findViewById(R.id.home); homeButton.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); } }); } // 返回 protected void addBackButton() { backButton = (Button) findViewById(R.id.top_back); // 中文粗体 // TextPaint tp = backButton.getPaint(); // tp.setFakeBoldText(true); backButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Go back to previous activity finish(); } }); } protected void initHeader(int style) { //FIXME: android 1.6似乎不支持addHeaderView中使用的方法 // 来增加header,造成header无法显示和使用。 // 改用在layout xml里include的方法来确保显示 switch (style) { case HEADER_STYLE_HOME: //addHeaderView(R.layout.header); addTitleButton(); addWriteButton(); addSearchButton(); addRefreshButton(); break; case HEADER_STYLE_BACK: //addHeaderView(R.layout.header_back); addBackButton(); addWriteButton(); addSearchButton(); addRefreshButton(); break; case HEADER_STYLE_WRITE: //addHeaderView(R.layout.header_write); addBackButton(); //addHomeButton(); break; case HEADER_STYLE_SEARCH: //addHeaderView(R.layout.header_search); addBackButton(); addSearchBox(); addSearchButton(); break; } } private void addHeaderView(int resource) { // find content root view ViewGroup root = (ViewGroup) getWindow().getDecorView(); ViewGroup content = (ViewGroup) root.getChildAt(0); View header = View.inflate(WithHeaderActivity.this, resource, null); // LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT); content.addView(header, 0); } @Override protected void onDestroy() { // dismiss dialog before destroy // to avoid android.view.WindowLeaked Exception if (dialog != null){ dialog.dismiss(); } super.onDestroy(); } }
Java
package com.ch_linghu.fanfoudroid.ui.base; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.data.User; import com.ch_linghu.fanfoudroid.fanfou.Paging; 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.TaskManager; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback; import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter; import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter; public abstract class UserArrayBaseActivity extends UserListBaseActivity { static final String TAG = "UserArrayBaseActivity"; // Views. protected ListView mUserList; protected UserArrayAdapter mUserListAdapter; protected TextView loadMoreBtn; protected ProgressBar loadMoreGIF; protected TextView loadMoreBtnTop; protected ProgressBar loadMoreGIFTop; protected static int lastPosition = 0; // Tasks. protected TaskManager taskManager = new TaskManager(); private GenericTask mRetrieveTask; private GenericTask mFollowersRetrieveTask; private GenericTask mGetMoreTask;// 每次100用户 public abstract Paging getCurrentPage();// 加载 public abstract Paging getNextPage();// 加载 // protected abstract String[] getIds(); protected abstract List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers( String userId, Paging page) throws HttpException; private ArrayList<com.ch_linghu.fanfoudroid.data.User> allUserList; @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate."); if (super._onCreate(savedInstanceState)) { doRetrieve();// 加载第一页 return true; } else { return false; } } @Override public void doRetrieve() { Log.d(TAG, "Attempting retrieve."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mRetrieveTask = new RetrieveTask(); mRetrieveTask.setFeedback(mFeedback); mRetrieveTask.setListener(mRetrieveTaskListener); mRetrieveTask.execute(); // Add Task to manager taskManager.addTask(mRetrieveTask); } } private TaskListener mRetrieveTaskListener = new TaskAdapter() { @Override public String getName() { return "RetrieveTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { draw(); } updateProgress(""); } @Override public void onPreExecute(GenericTask task) { onRetrieveBegin(); } @Override public void onProgressUpdate(GenericTask task, Object param) { Log.d(TAG, "onProgressUpdate"); draw(); } }; public void updateProgress(String progress) { mProgressText.setText(progress); } public void onRetrieveBegin() { updateProgress(getString(R.string.page_status_refreshing)); } /** * TODO:从API获取当前Followers * * @author Dino * */ private class RetrieveTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { Log.d(TAG, "load RetrieveTask"); List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null; try { usersList = getUsers(getUserId(), getCurrentPage()); } catch (HttpException e) { e.printStackTrace(); return TaskResult.IO_ERROR; } publishProgress(SimpleFeedback.calProgressBySize(40, 20, usersList)); for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) { if (isCancelled()) { return TaskResult.CANCELLED; } allUserList.add(User.create(user)); if (isCancelled()) { return TaskResult.CANCELLED; } } return TaskResult.OK; } } @Override protected int getLayoutId() { return R.layout.follower; } @Override protected void setupState() { setTitle(getActivityTitle()); mUserList = (ListView) findViewById(R.id.follower_list); setupListHeader(true); mUserListAdapter = new UserArrayAdapter(this); mUserList.setAdapter(mUserListAdapter); allUserList = new ArrayList<com.ch_linghu.fanfoudroid.data.User>(); } @Override protected String getActivityTitle() { // TODO Auto-generated method stub return null; } @Override protected boolean useBasicMenu() { return true; } @Override protected User getContextItemUser(int position) { // position = position - 1; // 加入footer跳过footer if (position < mUserListAdapter.getCount()) { User item = (User) mUserListAdapter.getItem(position); if (item == null) { return null; } else { return item; } } else { return null; } } /** * TODO:不知道啥用 */ @Override protected void updateTweet(Tweet tweet) { // TODO Auto-generated method stub } @Override protected ListView getUserList() { return mUserList; } @Override protected TweetAdapter getUserAdapter() { return mUserListAdapter; } /** * 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用 */ protected void setupListHeader(boolean addFooter) { // Add footer to Listview View footer = View.inflate(this, R.layout.listview_footer, null); mUserList.addFooterView(footer, null, true); // Find View loadMoreBtn = (TextView) findViewById(R.id.ask_for_more); loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar); } @Override protected void specialItemClicked(int position) { if (position == mUserList.getCount() - 1) { // footer loadMoreGIF.setVisibility(View.VISIBLE); doGetMore(); } } public void doGetMore() { Log.d(TAG, "Attempting getMore."); mFeedback.start(""); if (mGetMoreTask != null && mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mGetMoreTask = new GetMoreTask(); mGetMoreTask.setListener(getMoreListener); mGetMoreTask.execute(); // Add Task to manager taskManager.addTask(mGetMoreTask); } } private TaskListener getMoreListener = new TaskAdapter() { @Override public String getName() { return "getMore"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { super.onPostExecute(task, result); draw(); mFeedback.success(""); loadMoreGIF.setVisibility(View.GONE); } }; /** * TODO:需要重写,获取下一批用户,按页分100页一次 * * @author Dino * */ private class GetMoreTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { Log.d(TAG, "load RetrieveTask"); List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null; try { usersList = getUsers(getUserId(), getNextPage()); mFeedback.update(60); } catch (HttpException e) { e.printStackTrace(); return TaskResult.IO_ERROR; } // 将获取到的数据(保存/更新)到数据库 getDb().syncWeiboUsers(usersList); mFeedback.update(100 - (int) Math.floor(usersList.size() * 2)); for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) { if (isCancelled()) { return TaskResult.CANCELLED; } allUserList.add(User.create(user)); if (isCancelled()) { return TaskResult.CANCELLED; } } mFeedback.update(99); return TaskResult.OK; } } public void draw() { mUserListAdapter.refresh(allUserList); } }
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.base; import java.util.ArrayList; import java.util.List; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.data.User; import com.ch_linghu.fanfoudroid.db.UserInfoTable; 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.TaskManager; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback; import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter; import com.ch_linghu.fanfoudroid.ui.module.UserCursorAdapter; import com.ch_linghu.fanfoudroid.util.DateTimeHelper; /** * TwitterCursorBaseLine用于带有静态数据来源(对应数据库的,与twitter表同构的特定表)的展现 */ public abstract class UserCursorBaseActivity extends UserListBaseActivity { /** * 第一种方案:(采取第一种) 暂不放在数据库中,直接从Api读取。 * * 第二种方案: 麻烦的是api数据与数据库同步,当收听人数比较多的时候,一次性读取太费流量 按照饭否api每次分页100人 * 当收听数<100时先从数据库一次性根据API返回的ID列表读取数据,如果数据库中的收听数<总数,那么从API中读取所有用户信息并同步到数据库中。 * 当收听数>100时采取分页加载,先按照id * 获取数据库里前100用户,如果用户数量<100则从api中加载,从page=1开始下载,同步到数据库中,单击更多继续从数据库中加载 * 当数据库中的数据读取到最后一页后,则从api中加载并更新到数据库中。 单击刷新按钮则从api加载并同步到数据库中 * */ static final String TAG = "UserCursorBaseActivity"; // Views. protected ListView mUserList; protected UserCursorAdapter mUserListAdapter; protected TextView loadMoreBtn; protected ProgressBar loadMoreGIF; protected TextView loadMoreBtnTop; protected ProgressBar loadMoreGIFTop; protected static int lastPosition = 0; // Tasks. protected TaskManager taskManager = new TaskManager(); private GenericTask mRetrieveTask; private GenericTask mFollowersRetrieveTask; private GenericTask mGetMoreTask;// 每次十个用户 protected abstract String getUserId();// 获得用户id private TaskListener mRetrieveTaskListener = new TaskAdapter() { @Override public String getName() { return "RetrieveTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { SharedPreferences.Editor editor = getPreferences().edit(); editor.putLong(Preferences.LAST_TWEET_REFRESH_KEY, DateTimeHelper.getNowTime()); editor.commit(); // TODO: 1. StatusType(DONE) ; 2. 只有在取回的数据大于MAX时才做GC, // 因为小于时可以保证数据的连续性 // FIXME: gc需要带owner // getDb().gc(getDatabaseType()); // GC draw(); goTop(); } else { // Do nothing. } // loadMoreGIFTop.setVisibility(View.GONE); updateProgress(""); } @Override public void onPreExecute(GenericTask task) { onRetrieveBegin(); } @Override public void onProgressUpdate(GenericTask task, Object param) { Log.d(TAG, "onProgressUpdate"); draw(); } }; private TaskListener mFollowerRetrieveTaskListener = new TaskAdapter() { @Override public String getName() { return "FollowerRetrieve"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { SharedPreferences sp = getPreferences(); SharedPreferences.Editor editor = sp.edit(); editor.putLong(Preferences.LAST_FOLLOWERS_REFRESH_KEY, DateTimeHelper.getNowTime()); editor.commit(); } else { // Do nothing. } } }; // Refresh data at startup if last refresh was this long ago or greater. private static final long REFRESH_THRESHOLD = 5 * 60 * 1000; // Refresh followers if last refresh was this long ago or greater. private static final long FOLLOWERS_REFRESH_THRESHOLD = 12 * 60 * 60 * 1000; abstract protected Cursor fetchUsers(); public abstract int getDatabaseType(); public abstract String fetchMaxId(); public abstract String fetchMinId(); public abstract List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers() throws HttpException; public abstract void addUsers( ArrayList<com.ch_linghu.fanfoudroid.data.User> tusers); // public abstract List<Status> getMessageSinceId(String maxId) // throws WeiboException; public abstract List<com.ch_linghu.fanfoudroid.fanfou.User> getUserSinceId( String maxId) throws HttpException; public abstract List<Status> getMoreMessageFromId(String minId) throws HttpException; public abstract Paging getNextPage();// 下一页数 public abstract Paging getCurrentPage();// 当前页数 protected abstract String[] getIds(); public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1; // public static final int CONTEXT_AT_ID = Menu.FIRST + 2; public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3; public static final int CONTEXT_DM_ID = Menu.FIRST + 4; public static final int CONTEXT_MORE_ID = Menu.FIRST + 5; public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6; public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7; @Override protected void setupState() { Cursor cursor; cursor = fetchUsers(); // setTitle(getActivityTitle()); startManagingCursor(cursor); mUserList = (ListView) findViewById(R.id.follower_list); // TODO: 需处理没有数据时的情况 Log.d("LDS", cursor.getCount() + " cursor count"); setupListHeader(true); mUserListAdapter = new UserCursorAdapter(this, cursor); mUserList.setAdapter(mUserListAdapter); // ? registerOnClickListener(mTweetList); } /** * 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用 */ protected void setupListHeader(boolean addFooter) { // Add footer to Listview View footer = View.inflate(this, R.layout.listview_footer, null); mUserList.addFooterView(footer, null, true); // Find View loadMoreBtn = (TextView) findViewById(R.id.ask_for_more); loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar); // loadMoreBtnTop = (TextView)findViewById(R.id.ask_for_more_header); // loadMoreGIFTop = // (ProgressBar)findViewById(R.id.rectangleProgressBar_header); // loadMoreAnimation = (AnimationDrawable) // loadMoreGIF.getIndeterminateDrawable(); } @Override protected void specialItemClicked(int position) { if (position == mUserList.getCount() - 1) { // footer loadMoreGIF.setVisibility(View.VISIBLE); doGetMore(); } } @Override protected int getLayoutId() { return R.layout.follower; } @Override protected ListView getUserList() { return mUserList; } @Override protected TweetAdapter getUserAdapter() { return mUserListAdapter; } @Override protected boolean useBasicMenu() { return true; } protected User getContextItemUser(int position) { // position = position - 1; // 加入footer跳过footer if (position < mUserListAdapter.getCount()) { Cursor cursor = (Cursor) mUserListAdapter.getItem(position); if (cursor == null) { return null; } else { return UserInfoTable.parseCursor(cursor); } } else { return null; } } @Override protected void updateTweet(Tweet tweet) { // TODO: updateTweet() 在哪里调用的? 目前尚只支持: // updateTweet(String tweetId, ContentValues values) // setFavorited(String tweetId, String isFavorited) // 看是否还需要增加updateTweet(Tweet tweet)方法 // 对所有相关表的对应消息都进行刷新(如果存在的话) // getDb().updateTweet(TwitterDbAdapter.TABLE_FAVORITE, tweet); // getDb().updateTweet(TwitterDbAdapter.TABLE_MENTION, tweet); // getDb().updateTweet(TwitterDbAdapter.TABLE_TWEET, tweet); } @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate."); if (super._onCreate(savedInstanceState)) { goTop(); // skip the header boolean shouldRetrieve = false; // FIXME: 该子类页面全部使用了这个统一的计时器,导致进入Mention等分页面后经常不会自动刷新 long lastRefreshTime = mPreferences.getLong( Preferences.LAST_TWEET_REFRESH_KEY, 0); long nowTime = DateTimeHelper.getNowTime(); long diff = nowTime - lastRefreshTime; Log.d(TAG, "Last refresh was " + diff + " ms ago."); /* * if (diff > REFRESH_THRESHOLD) { shouldRetrieve = true; } else if * (Utils.isTrue(savedInstanceState, SIS_RUNNING_KEY)) { // Check to * see if it was running a send or retrieve task. // It makes no * sense to resend the send request (don't want dupes) // so we * instead retrieve (refresh) to see if the message has // posted. * Log.d(TAG, * "Was last running a retrieve or send task. Let's refresh."); * shouldRetrieve = true; } */ shouldRetrieve = true; if (shouldRetrieve) { doRetrieve(); } long lastFollowersRefreshTime = mPreferences.getLong( Preferences.LAST_FOLLOWERS_REFRESH_KEY, 0); diff = nowTime - lastFollowersRefreshTime; Log.d(TAG, "Last followers refresh was " + diff + " ms ago."); /* * if (diff > FOLLOWERS_REFRESH_THRESHOLD && (mRetrieveTask == null * || mRetrieveTask.getStatus() != GenericTask.Status.RUNNING)) { * Log.d(TAG, "Refresh followers."); doRetrieveFollowers(); } */ return true; } else { return false; } } @Override protected void onResume() { Log.d(TAG, "onResume."); if (lastPosition != 0) { mUserList.setSelection(lastPosition); } 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 onRestoreInstanceState(Bundle bundle) { super.onRestoreInstanceState(bundle); // mTweetEdit.updateCharsRemain(); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy."); super.onDestroy(); taskManager.cancelAll(); } @Override protected void onPause() { Log.d(TAG, "onPause."); super.onPause(); lastPosition = mUserList.getFirstVisiblePosition(); } @Override protected void onRestart() { Log.d(TAG, "onRestart."); super.onRestart(); } @Override protected void onStart() { Log.d(TAG, "onStart."); super.onStart(); } @Override protected void onStop() { Log.d(TAG, "onStop."); super.onStop(); } // UI helpers. @Override protected String getActivityTitle() { // TODO Auto-generated method stub return null; } @Override protected void adapterRefresh() { mUserListAdapter.notifyDataSetChanged(); mUserListAdapter.refresh(); } // Retrieve interface public void updateProgress(String progress) { mProgressText.setText(progress); } public void draw() { mUserListAdapter.refresh(); } public void goTop() { Log.d(TAG, "goTop."); mUserList.setSelection(1); } private void doRetrieveFollowers() { Log.d(TAG, "Attempting followers retrieve."); if (mFollowersRetrieveTask != null && mFollowersRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mFollowersRetrieveTask = new FollowersRetrieveTask(); mFollowersRetrieveTask.setListener(mFollowerRetrieveTaskListener); mFollowersRetrieveTask.execute(); taskManager.addTask(mFollowersRetrieveTask); // Don't need to cancel FollowersTask (assuming it ends properly). mFollowersRetrieveTask.setCancelable(false); } } public void onRetrieveBegin() { updateProgress(getString(R.string.page_status_refreshing)); } public void doRetrieve() { Log.d(TAG, "Attempting retrieve."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mRetrieveTask = new RetrieveTask(); mRetrieveTask.setListener(mRetrieveTaskListener); mRetrieveTask.setFeedback(mFeedback); mRetrieveTask.execute(); // Add Task to manager taskManager.addTask(mRetrieveTask); } } /** * TODO:从API获取当前Followers,并同步到数据库 * * @author Dino * */ private class RetrieveTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { Log.d(TAG, "load RetrieveTask"); List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null; try { usersList = getApi().getFollowersList(getUserId(), getCurrentPage()); } catch (HttpException e) { e.printStackTrace(); } publishProgress(SimpleFeedback.calProgressBySize(40, 20, usersList)); ArrayList<User> users = new ArrayList<User>(); for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) { if (isCancelled()) { return TaskResult.CANCELLED; } users.add(User.create(user)); if (isCancelled()) { return TaskResult.CANCELLED; } } addUsers(users); return TaskResult.OK; } } private class FollowersRetrieveTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { Log.d(TAG, "load FollowersErtrieveTask"); List<com.ch_linghu.fanfoudroid.fanfou.User> t_users = getUsers(); getDb().syncWeiboUsers(t_users); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } return TaskResult.OK; } } /** * TODO:需要重写,获取下一批用户,按页分100页一次 * * @author Dino * */ private class GetMoreTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { Log.d(TAG, "load RetrieveTask"); List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null; try { usersList = getApi().getFollowersList(getUserId(), getNextPage()); } catch (HttpException e) { e.printStackTrace(); } publishProgress(SimpleFeedback.calProgressBySize(40, 20, usersList)); ArrayList<User> users = new ArrayList<User>(); for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) { if (isCancelled()) { return TaskResult.CANCELLED; } users.add(User.create(user)); if (isCancelled()) { return TaskResult.CANCELLED; } } addUsers(users); return TaskResult.OK; } } private TaskListener getMoreListener = new TaskAdapter() { @Override public String getName() { return "getMore"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { super.onPostExecute(task, result); draw(); loadMoreGIF.setVisibility(View.GONE); } }; public void doGetMore() { Log.d(TAG, "Attempting getMore."); if (mGetMoreTask != null && mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mGetMoreTask = new GetMoreTask(); mGetMoreTask.setFeedback(mFeedback); mGetMoreTask.setListener(getMoreListener); mGetMoreTask.execute(); // Add Task to manager taskManager.addTask(mGetMoreTask); } } }
Java
package com.ch_linghu.fanfoudroid.ui.base; public interface Refreshable { void doRetrieve(); }
Java
package com.ch_linghu.fanfoudroid.ui.base; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.Window; import com.ch_linghu.fanfoudroid.AboutDialog; import com.ch_linghu.fanfoudroid.LoginActivity; import com.ch_linghu.fanfoudroid.PreferencesActivity; 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.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.fanfou.Weibo; import com.ch_linghu.fanfoudroid.service.TwitterService; /** * A BaseActivity has common routines and variables for an Activity that * contains a list of tweets and a text input field. * * Not the cleanest design, but works okay for several Activities in this app. */ public class BaseActivity extends Activity { private static final String TAG = "BaseActivity"; protected SharedPreferences mPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); _onCreate(savedInstanceState); } // 因为onCreate方法无法返回状态,因此无法进行状态判断, // 为了能对上层返回的信息进行判断处理,我们使用_onCreate代替真正的 // onCreate进行工作。onCreate仅在顶层调用_onCreate。 protected boolean _onCreate(Bundle savedInstanceState) { if (!checkIsLogedIn()) { return false; } else { PreferenceManager.setDefaultValues(this, R.xml.preferences, false); mPreferences = TwitterApplication.mPref; // PreferenceManager.getDefaultSharedPreferences(this); return true; } } protected void handleLoggedOut() { if (isTaskRoot()) { showLogin(); } else { setResult(RESULT_LOGOUT); } finish(); } public TwitterDatabase getDb() { return TwitterApplication.mDb; } public Weibo getApi() { return TwitterApplication.mApi; } public SharedPreferences getPreferences() { return mPreferences; } @Override protected void onDestroy() { super.onDestroy(); } protected boolean isLoggedIn() { return getApi().isLoggedIn(); } private static final int RESULT_LOGOUT = RESULT_FIRST_USER + 1; // Retrieve interface // public ImageManager getImageManager() { // return TwitterApplication.mImageManager; // } private void _logout() { TwitterService.unschedule(BaseActivity.this); getDb().clearData(); getApi().reset(); // Clear SharedPreferences SharedPreferences.Editor editor = mPreferences.edit(); editor.clear(); editor.commit(); // TODO: 提供用户手动情况所有缓存选项 TwitterApplication.mImageLoader.getImageManager().clear(); // TODO: cancel notifications. TwitterService.unschedule(BaseActivity.this); handleLoggedOut(); } public void logout() { Dialog dialog = new AlertDialog.Builder(BaseActivity.this) .setTitle("提示").setMessage("确实要注销吗?") .setPositiveButton("确定", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { _logout(); } }).setNegativeButton("取消", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).create(); dialog.show(); } protected void showLogin() { Intent intent = new Intent(this, LoginActivity.class); // TODO: might be a hack? intent.putExtra(Intent.EXTRA_INTENT, getIntent()); startActivity(intent); } protected void manageUpdateChecks() { boolean isEnabled = mPreferences.getBoolean( Preferences.CHECK_UPDATES_KEY, false); if (isEnabled) { TwitterService.schedule(this); } else if (!TwitterService.isWidgetEnabled()) { TwitterService.unschedule(this); } } // Menus. protected static final int OPTIONS_MENU_ID_LOGOUT = 1; protected static final int OPTIONS_MENU_ID_PREFERENCES = 2; protected static final int OPTIONS_MENU_ID_ABOUT = 3; protected static final int OPTIONS_MENU_ID_SEARCH = 4; protected static final int OPTIONS_MENU_ID_REPLIES = 5; protected static final int OPTIONS_MENU_ID_DM = 6; protected static final int OPTIONS_MENU_ID_TWEETS = 7; protected static final int OPTIONS_MENU_ID_TOGGLE_REPLIES = 8; protected static final int OPTIONS_MENU_ID_FOLLOW = 9; protected static final int OPTIONS_MENU_ID_UNFOLLOW = 10; protected static final int OPTIONS_MENU_ID_IMAGE_CAPTURE = 11; protected static final int OPTIONS_MENU_ID_PHOTO_LIBRARY = 12; protected static final int OPTIONS_MENU_ID_EXIT = 13; /** * 如果增加了Option Menu常量的数量,则必须重载此方法, 以保证其他人使用常量时不产生重复 * * @return 最大的Option Menu常量 */ protected int getLastOptionMenuId() { return OPTIONS_MENU_ID_EXIT; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); // SubMenu submenu = // menu.addSubMenu(R.string.write_label_insert_picture); // submenu.setIcon(android.R.drawable.ic_menu_gallery); // // submenu.add(0, OPTIONS_MENU_ID_IMAGE_CAPTURE, 0, // R.string.write_label_take_a_picture); // submenu.add(0, OPTIONS_MENU_ID_PHOTO_LIBRARY, 0, // R.string.write_label_choose_a_picture); // // MenuItem item = menu.add(0, OPTIONS_MENU_ID_SEARCH, 0, // R.string.omenu_search); // item.setIcon(android.R.drawable.ic_search_category_default); // item.setAlphabeticShortcut(SearchManager.MENU_KEY); MenuItem item; item = menu.add(0, OPTIONS_MENU_ID_PREFERENCES, 0, R.string.omenu_settings); item.setIcon(android.R.drawable.ic_menu_preferences); item = menu.add(0, OPTIONS_MENU_ID_LOGOUT, 0, R.string.omenu_signout); item.setIcon(android.R.drawable.ic_menu_revert); item = menu.add(0, OPTIONS_MENU_ID_ABOUT, 0, R.string.omenu_about); item.setIcon(android.R.drawable.ic_menu_info_details); item = menu.add(0, OPTIONS_MENU_ID_EXIT, 0, R.string.omenu_exit); item.setIcon(android.R.drawable.ic_menu_rotate); return true; } protected static final int REQUEST_CODE_LAUNCH_ACTIVITY = 0; protected static final int REQUEST_CODE_PREFERENCES = 1; @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case OPTIONS_MENU_ID_LOGOUT: logout(); return true; case OPTIONS_MENU_ID_SEARCH: onSearchRequested(); return true; case OPTIONS_MENU_ID_PREFERENCES: Intent launchPreferencesIntent = new Intent().setClass(this, PreferencesActivity.class); startActivityForResult(launchPreferencesIntent, REQUEST_CODE_PREFERENCES); return true; case OPTIONS_MENU_ID_ABOUT: AboutDialog.show(this); return true; case OPTIONS_MENU_ID_EXIT: exit(); return true; } return super.onOptionsItemSelected(item); } protected void exit() { TwitterService.unschedule(this); Intent i = new Intent(Intent.ACTION_MAIN); i.addCategory(Intent.CATEGORY_HOME); startActivity(i); } protected void launchActivity(Intent intent) { // TODO: probably don't need this result chaining to finish upon logout. // since the subclasses have to check in onResume. startActivityForResult(intent, REQUEST_CODE_LAUNCH_ACTIVITY); } protected void launchDefaultActivity() { Intent intent = new Intent(); intent.setClass(this, TwitterActivity.class); startActivity(intent); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_PREFERENCES && resultCode == RESULT_OK) { manageUpdateChecks(); } else if (requestCode == REQUEST_CODE_LAUNCH_ACTIVITY && resultCode == RESULT_LOGOUT) { Log.d(TAG, "Result logout."); handleLoggedOut(); } } protected boolean checkIsLogedIn() { if (!getApi().isLoggedIn()) { Log.d(TAG, "Not logged in."); handleLoggedOut(); return false; } return true; } }
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.base; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MotionEvent; import android.view.View; import android.widget.ListView; import android.widget.ProgressBar; 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.data.Tweet; import com.ch_linghu.fanfoudroid.db.StatusTable; import com.ch_linghu.fanfoudroid.fanfou.IDs; 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.TaskManager; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.module.FlingGestureListener; import com.ch_linghu.fanfoudroid.ui.module.MyActivityFlipper; import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback; import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter; import com.ch_linghu.fanfoudroid.ui.module.TweetCursorAdapter; import com.ch_linghu.fanfoudroid.util.DateTimeHelper; import com.ch_linghu.fanfoudroid.util.DebugTimer; import com.ch_linghu.fanfoudroid.util.MiscHelper; /** * TwitterCursorBaseLine用于带有静态数据来源(对应数据库的,与twitter表同构的特定表)的展现 */ public abstract class TwitterCursorBaseActivity extends TwitterListBaseActivity { static final String TAG = "TwitterCursorBaseActivity"; // Views. protected ListView mTweetList; protected TweetCursorAdapter mTweetAdapter; protected View mListHeader; protected View mListFooter; protected TextView loadMoreBtn; protected ProgressBar loadMoreGIF; protected TextView loadMoreBtnTop; protected ProgressBar loadMoreGIFTop; protected static int lastPosition = 0; // Tasks. protected TaskManager taskManager = new TaskManager(); private GenericTask mRetrieveTask; private GenericTask mFollowersRetrieveTask; private GenericTask mGetMoreTask; private int mRetrieveCount = 0; private TaskListener mRetrieveTaskListener = new TaskAdapter() { @Override public String getName() { return "RetrieveTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { mFeedback.failed("登录信息出错"); logout(); } else if (result == TaskResult.OK) { // TODO: XML处理, GC压力 SharedPreferences.Editor editor = getPreferences().edit(); editor.putLong(Preferences.LAST_TWEET_REFRESH_KEY, DateTimeHelper.getNowTime()); editor.commit(); // TODO: 1. StatusType(DONE) ; if (mRetrieveCount >= StatusTable.MAX_ROW_NUM) { // 只有在取回的数据大于MAX时才做GC, 因为小于时可以保证数据的连续性 getDb().gc(getUserId(), getDatabaseType()); // GC } draw(); if (task == mRetrieveTask) { goTop(); } } else if (result == TaskResult.IO_ERROR) { //FIXME: bad smell if (task == mRetrieveTask) { mFeedback.failed(((RetrieveTask) task).getErrorMsg()); } else if (task == mGetMoreTask) { mFeedback.failed(((GetMoreTask) task).getErrorMsg()); } } else { // do nothing } // 刷新按钮停止旋转 loadMoreGIFTop.setVisibility(View.GONE); loadMoreGIF.setVisibility(View.GONE); // DEBUG if (TwitterApplication.DEBUG){ DebugTimer.stop(); Log.v("DEBUG", DebugTimer.getProfileAsString()); } } @Override public void onPreExecute(GenericTask task) { mRetrieveCount = 0; if(TwitterApplication.DEBUG){ DebugTimer.start(); } } @Override public void onProgressUpdate(GenericTask task, Object param) { Log.d(TAG, "onProgressUpdate"); draw(); } }; private TaskListener mFollowerRetrieveTaskListener = new TaskAdapter() { @Override public String getName() { return "FollowerRetrieve"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { SharedPreferences sp = getPreferences(); SharedPreferences.Editor editor = sp.edit(); editor.putLong(Preferences.LAST_FOLLOWERS_REFRESH_KEY, DateTimeHelper.getNowTime()); editor.commit(); } else { // Do nothing. } } }; // Refresh data at startup if last refresh was this long ago or greater. private static final long REFRESH_THRESHOLD = 5 * 60 * 1000; // Refresh followers if last refresh was this long ago or greater. private static final long FOLLOWERS_REFRESH_THRESHOLD = 12 * 60 * 60 * 1000; abstract protected void markAllRead(); abstract protected Cursor fetchMessages(); public abstract int getDatabaseType(); public abstract String getUserId(); public abstract String fetchMaxId(); public abstract String fetchMinId(); public abstract int addMessages(ArrayList<Tweet> tweets, boolean isUnread); public abstract List<Status> getMessageSinceId(String maxId) throws HttpException; public abstract List<Status> getMoreMessageFromId(String minId) throws HttpException; public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1; // public static final int CONTEXT_AT_ID = Menu.FIRST + 2; public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3; public static final int CONTEXT_DM_ID = Menu.FIRST + 4; public static final int CONTEXT_MORE_ID = Menu.FIRST + 5; public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6; public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7; @Override protected void setupState() { Cursor cursor; cursor = fetchMessages(); // getDb().fetchMentions(); setTitle(getActivityTitle()); startManagingCursor(cursor); mTweetList = (ListView) findViewById(R.id.tweet_list); // TODO: 需处理没有数据时的情况 Log.d("LDS", cursor.getCount() + " cursor count"); setupListHeader(true); mTweetAdapter = new TweetCursorAdapter(this, cursor); mTweetList.setAdapter(mTweetAdapter); // ? registerOnClickListener(mTweetList); } /** * 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用 */ protected void setupListHeader(boolean addFooter) { // Add Header to ListView mListHeader = View.inflate(this, R.layout.listview_header, null); mTweetList.addHeaderView(mListHeader, null, true); // Add Footer to ListView mListFooter = View.inflate(this, R.layout.listview_footer, null); mTweetList.addFooterView(mListFooter, null, true); // Find View loadMoreBtn = (TextView) findViewById(R.id.ask_for_more); loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar); loadMoreBtnTop = (TextView) findViewById(R.id.ask_for_more_header); loadMoreGIFTop = (ProgressBar) findViewById(R.id.rectangleProgressBar_header); } @Override protected void specialItemClicked(int position){ //注意 mTweetAdapter.getCount 和 mTweetList.getCount的区别 //前者仅包含数据的数量(不包括foot和head),后者包含foot和head //因此在同时存在foot和head的情况下,list.count = adapter.count + 2 if (position == 0){ //第一个Item(header) loadMoreGIFTop.setVisibility(View.VISIBLE); doRetrieve(); }else if (position == mTweetList.getCount()-1){ //最后一个Item(footer) loadMoreGIF.setVisibility(View.VISIBLE); doGetMore(); } } @Override protected int getLayoutId() { return R.layout.main; } @Override protected ListView getTweetList() { return mTweetList; } @Override protected TweetAdapter getTweetAdapter() { return mTweetAdapter; } @Override protected boolean useBasicMenu() { return true; } @Override protected Tweet getContextItemTweet(int position) { position = position - 1; // 因为List加了Header和footer,所以要跳过第一个以及忽略最后一个 if (position >= 0 && position < mTweetAdapter.getCount()) { Cursor cursor = (Cursor) mTweetAdapter.getItem(position); if (cursor == null) { return null; } else { return StatusTable.parseCursor(cursor); } } else { return null; } } @Override protected void updateTweet(Tweet tweet) { // TODO: updateTweet() 在哪里调用的? 目前尚只支持: // updateTweet(String tweetId, ContentValues values) // setFavorited(String tweetId, String isFavorited) // 看是否还需要增加updateTweet(Tweet tweet)方法 // 对所有相关表的对应消息都进行刷新(如果存在的话) // getDb().updateTweet(TwitterDbAdapter.TABLE_FAVORITE, tweet); // getDb().updateTweet(TwitterDbAdapter.TABLE_MENTION, tweet); // getDb().updateTweet(TwitterDbAdapter.TABLE_TWEET, tweet); } @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate."); if (super._onCreate(savedInstanceState)) { goTop(); // skip the header // Mark all as read. // getDb().markAllMentionsRead(); markAllRead(); boolean shouldRetrieve = false; // FIXME: 该子类页面全部使用了这个统一的计时器,导致进入Mention等分页面后经常不会自动刷新 long lastRefreshTime = mPreferences.getLong( Preferences.LAST_TWEET_REFRESH_KEY, 0); long nowTime = DateTimeHelper.getNowTime(); long diff = nowTime - lastRefreshTime; Log.d(TAG, "Last refresh was " + diff + " ms ago."); if (diff > REFRESH_THRESHOLD) { shouldRetrieve = true; } else if (MiscHelper.isTrue(savedInstanceState, SIS_RUNNING_KEY)) { // Check to see if it was running a send or retrieve task. // It makes no sense to resend the send request (don't want // dupes) // so we instead retrieve (refresh) to see if the message has // posted. Log.d(TAG, "Was last running a retrieve or send task. Let's refresh."); shouldRetrieve = true; } if (shouldRetrieve) { doRetrieve(); } long lastFollowersRefreshTime = mPreferences.getLong( Preferences.LAST_FOLLOWERS_REFRESH_KEY, 0); diff = nowTime - lastFollowersRefreshTime; Log.d(TAG, "Last followers refresh was " + diff + " ms ago."); //FIXME: 目前还没有对Followers列表做逻辑处理,因此暂时去除对Followers的获取。 // 未来需要实现@用户提示时,对Follower操作需要做一次review和refactoring // 现在频繁会出现主键冲突的问题。 // // Should Refresh Followers // if (diff > FOLLOWERS_REFRESH_THRESHOLD // && (mRetrieveTask == null || mRetrieveTask.getStatus() != GenericTask.Status.RUNNING)) { // Log.d(TAG, "Refresh followers."); // doRetrieveFollowers(); // } // 手势识别 registerGestureListener(); return true; } else { return false; } } @Override protected void onResume() { Log.d(TAG, "onResume."); if (lastPosition != 0) { mTweetList.setSelection(lastPosition); } 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 onRestoreInstanceState(Bundle bundle) { super.onRestoreInstanceState(bundle); // mTweetEdit.updateCharsRemain(); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy."); super.onDestroy(); taskManager.cancelAll(); } @Override protected void onPause() { Log.d(TAG, "onPause."); super.onPause(); lastPosition = mTweetList.getFirstVisiblePosition(); } @Override protected void onRestart() { Log.d(TAG, "onRestart."); super.onRestart(); } @Override protected void onStart() { Log.d(TAG, "onStart."); super.onStart(); } @Override protected void onStop() { Log.d(TAG, "onStop."); super.onStop(); } // UI helpers. @Override protected String getActivityTitle() { return null; } @Override protected void adapterRefresh() { mTweetAdapter.notifyDataSetChanged(); mTweetAdapter.refresh(); } // Retrieve interface public void updateProgress(String progress) { mProgressText.setText(progress); } public void draw() { mTweetAdapter.refresh(); } public void goTop() { Log.d(TAG, "goTop."); mTweetList.setSelection(1); } private void doRetrieveFollowers() { Log.d(TAG, "Attempting followers retrieve."); if (mFollowersRetrieveTask != null && mFollowersRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mFollowersRetrieveTask = new FollowersRetrieveTask(); mFollowersRetrieveTask.setListener(mFollowerRetrieveTaskListener); mFollowersRetrieveTask.execute(); taskManager.addTask(mFollowersRetrieveTask); // Don't need to cancel FollowersTask (assuming it ends properly). mFollowersRetrieveTask.setCancelable(false); } } public void doRetrieve() { Log.d(TAG, "Attempting retrieve."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mRetrieveTask = new RetrieveTask(); mRetrieveTask.setFeedback(mFeedback); mRetrieveTask.setListener(mRetrieveTaskListener); mRetrieveTask.execute(); // Add Task to manager taskManager.addTask(mRetrieveTask); } } private class RetrieveTask extends GenericTask { private String _errorMsg; public String getErrorMsg() { return _errorMsg; } @Override protected TaskResult _doInBackground(TaskParams... params) { List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList; try { String maxId = fetchMaxId(); // getDb().fetchMaxMentionId(); statusList = getMessageSinceId(maxId); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); _errorMsg = e.getMessage(); return TaskResult.IO_ERROR; } ArrayList<Tweet> tweets = new ArrayList<Tweet>(); for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) { if (isCancelled()) { return TaskResult.CANCELLED; } tweets.add(Tweet.create(status)); if (isCancelled()) { return TaskResult.CANCELLED; } } publishProgress(SimpleFeedback.calProgressBySize(40, 20, tweets)); mRetrieveCount = addMessages(tweets, false); return TaskResult.OK; } } private class FollowersRetrieveTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { // TODO: 目前仅做新API兼容性改动,待完善Follower处理 IDs followers = getApi().getFollowersIDs(); List<String> followerIds = Arrays.asList(followers.getIDs()); getDb().syncFollowers(followerIds); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } return TaskResult.OK; } } // GET MORE TASK private class GetMoreTask extends GenericTask { private String _errorMsg; public String getErrorMsg() { return _errorMsg; } @Override protected TaskResult _doInBackground(TaskParams... params) { List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList; String minId = fetchMinId(); // getDb().fetchMaxMentionId(); if (minId == null) { return TaskResult.FAILED; } try { statusList = getMoreMessageFromId(minId); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); _errorMsg = e.getMessage(); return TaskResult.IO_ERROR; } if (statusList == null) { return TaskResult.FAILED; } ArrayList<Tweet> tweets = new ArrayList<Tweet>(); publishProgress(SimpleFeedback.calProgressBySize(40, 20, tweets)); for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) { if (isCancelled()) { return TaskResult.CANCELLED; } tweets.add(Tweet.create(status)); if (isCancelled()) { return TaskResult.CANCELLED; } } addMessages(tweets, false); // getDb().addMentions(tweets, false); return TaskResult.OK; } } public void doGetMore() { Log.d(TAG, "Attempting getMore."); if (mGetMoreTask != null && mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mGetMoreTask = new GetMoreTask(); mGetMoreTask.setFeedback(mFeedback); mGetMoreTask.setListener(mRetrieveTaskListener); mGetMoreTask.execute(); // Add Task to manager taskManager.addTask(mGetMoreTask); } } //////////////////// Gesture test ///////////////////////////////////// private static boolean useGestrue; { useGestrue = TwitterApplication.mPref.getBoolean(Preferences.USE_GESTRUE, false); if (useGestrue) { Log.v(TAG, "Using Gestrue!"); } else { Log.v(TAG, "Not Using Gestrue!"); } } protected FlingGestureListener myGestureListener = null; @Override public boolean onTouchEvent(MotionEvent event) { if (useGestrue && myGestureListener != null) { return myGestureListener.getDetector().onTouchEvent(event); } return super.onTouchEvent(event); } // use it in _onCreate private void registerGestureListener() { if (useGestrue) { myGestureListener = new FlingGestureListener(this, MyActivityFlipper.create(this)); getTweetList().setOnTouchListener(myGestureListener); } } }
Java
package com.ch_linghu.fanfoudroid.ui.base; import android.app.ListActivity; /** * TODO: 准备重构现有的几个ListActivity * * 目前几个ListActivity存在的问题是 : * 1. 因为要实现[刷新]这些功能, 父类设定了子类继承时必须要实现的方法, * 而刷新/获取其实更多的时候可以理解成是ListView的层面, 这在于讨论到底是一个"可刷新的Activity" * 还是一个拥有"可刷新的ListView"的Activity, 如果改成后者, 则只要在父类拥有一个实现了可刷新接口的ListView即可, * 而无需强制要求子类去直接实现某些方法. * 2. 父类过于专制, 比如getLayoutId()等抽象方法的存在只是为了在父类进行setContentView, 而此类方法可以下放到子类去自行实现, * 诸如此类的, 应该下放给子类更自由的空间. 理想状态为不使用抽象类. * 3. 随着功能扩展, 需要将几个不同的ListActivity子类重复的部分重新抽象到父类来, 已减少代码重复. * 4. TwitterList和UserList代码存在重复现象, 可抽象. * 5. TwitterList目前过于依赖Cursor类型的List, 而没有Array类型的抽象类. * */ public class BaseListActivity extends ListActivity { }
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. */ /** * AbstractTwitterListBaseLine用于抽象tweets List的展现 * UI基本元素要求:一个ListView用于tweet列表 * 一个ProgressText用于提示信息 */ package com.ch_linghu.fanfoudroid.ui.base; import android.content.Intent; 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 android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.TextView; import com.ch_linghu.fanfoudroid.DmActivity; import com.ch_linghu.fanfoudroid.MentionActivity; import com.ch_linghu.fanfoudroid.ProfileActivity; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.StatusActivity; import com.ch_linghu.fanfoudroid.TwitterActivity; import com.ch_linghu.fanfoudroid.WriteActivity; import com.ch_linghu.fanfoudroid.WriteDmActivity; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.data.Tweet; 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.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.ui.module.TweetAdapter; import com.ch_linghu.fanfoudroid.util.TextHelper; public abstract class TwitterListBaseActivity extends BaseActivity implements Refreshable { static final String TAG = "TwitterListBaseActivity"; protected TextView mProgressText; protected Feedback mFeedback; protected NavBar mNavbar; protected static final int STATE_ALL = 0; protected static final String SIS_RUNNING_KEY = "running"; // Tasks. protected GenericTask mFavTask; 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(); } } }; static final int DIALOG_WRITE_ID = 0; abstract protected int getLayoutId(); abstract protected ListView getTweetList(); abstract protected TweetAdapter getTweetAdapter(); abstract protected void setupState(); abstract protected String getActivityTitle(); abstract protected boolean useBasicMenu(); abstract protected Tweet getContextItemTweet(int position); abstract protected void updateTweet(Tweet tweet); public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1; // public static final int CONTEXT_AT_ID = Menu.FIRST + 2; public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3; public static final int CONTEXT_DM_ID = Menu.FIRST + 4; public static final int CONTEXT_MORE_ID = Menu.FIRST + 5; public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6; public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7; /** * 如果增加了Context Menu常量的数量,则必须重载此方法, * 以保证其他人使用常量时不产生重复 * @return 最大的Context Menu常量 */ protected int getLastContextMenuId(){ return CONTEXT_DEL_FAV_ID; } @Override protected boolean _onCreate(Bundle savedInstanceState){ if (super._onCreate(savedInstanceState)){ setContentView(getLayoutId()); mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this); mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS); mPreferences.getInt(Preferences.TWITTER_ACTIVITY_STATE_KEY, STATE_ALL); // 提示栏 mProgressText = (TextView) findViewById(R.id.progress_text); setupState(); registerForContextMenu(getTweetList()); registerOnClickListener(getTweetList()); return true; } else { return false; } } @Override protected void onResume() { super.onResume(); checkIsLogedIn(); } @Override protected void onDestroy() { super.onDestroy(); if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { mFavTask.cancel(true); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { Log.d("FLING", "onContextItemSelected"); super.onCreateContextMenu(menu, v, menuInfo); if (useBasicMenu()){ AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; Tweet tweet = getContextItemTweet(info.position); if (tweet == null) { Log.w(TAG, "Selected item not available."); return; } menu.add(0, CONTEXT_MORE_ID, 0, tweet.screenName + getResources().getString(R.string.cmenu_user_profile_prefix)); menu.add(0, CONTEXT_REPLY_ID, 0, R.string.cmenu_reply); menu.add(0, CONTEXT_RETWEET_ID, 0, R.string.cmenu_retweet); menu.add(0, CONTEXT_DM_ID, 0, R.string.cmenu_direct_message); if (tweet.favorited.equals("true")) { menu.add(0, CONTEXT_DEL_FAV_ID, 0, R.string.cmenu_del_fav); } else { menu.add(0, CONTEXT_ADD_FAV_ID, 0, R.string.cmenu_add_fav); } } } @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); } switch (item.getItemId()) { case CONTEXT_MORE_ID: launchActivity(ProfileActivity.createIntent(tweet.userId)); return true; case CONTEXT_REPLY_ID: { // TODO: this isn't quite perfect. It leaves extra empty spaces if // you perform the reply action again. Intent intent = WriteActivity.createNewReplyIntent(tweet.screenName, tweet.id); startActivity(intent); return true; } case CONTEXT_RETWEET_ID: Intent intent = WriteActivity.createNewRepostIntent(this, tweet.text, tweet.screenName, tweet.id); startActivity(intent); return true; case CONTEXT_DM_ID: launchActivity(WriteDmActivity.createIntent(tweet.userId)); return true; case CONTEXT_ADD_FAV_ID: doFavorite("add", tweet.id); return true; case CONTEXT_DEL_FAV_ID: doFavorite("del", tweet.id); return true; default: return super.onContextItemSelected(item); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case OPTIONS_MENU_ID_TWEETS: launchActivity(TwitterActivity.createIntent(this)); return true; case OPTIONS_MENU_ID_REPLIES: launchActivity(MentionActivity.createIntent(this)); return true; case OPTIONS_MENU_ID_DM: launchActivity(DmActivity.createIntent()); return true; } return super.onOptionsItemSelected(item); } protected void draw() { getTweetAdapter().refresh(); } protected void goTop() { getTweetList().setSelection(1); } protected void adapterRefresh(){ getTweetAdapter().refresh(); } // for HasFavorite interface public void doFavorite(String action, String id) { if (!TextHelper.isEmpty(id)) { if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING){ return; }else{ mFavTask = new TweetCommonTask.FavoriteTask(this); mFavTask.setListener(mFavTaskListener); TaskParams params = new TaskParams(); params.put("action", action); params.put("id", id); mFavTask.execute(params); } } } public void onFavSuccess() { // updateProgress(getString(R.string.refreshing)); adapterRefresh(); } public void onFavFailure() { // updateProgress(getString(R.string.refreshing)); } protected void specialItemClicked(int position){ } protected void registerOnClickListener(ListView listView) { listView.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Tweet tweet = getContextItemTweet(position); if (tweet == null) { Log.w(TAG, "Selected item not available."); specialItemClicked(position); }else{ launchActivity(StatusActivity.createIntent(tweet)); } } }); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } }
Java
package com.ch_linghu.fanfoudroid.ui.base; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.DialogInterface; 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 android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.ch_linghu.fanfoudroid.DmActivity; 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.UserTimelineActivity; import com.ch_linghu.fanfoudroid.WriteActivity; import com.ch_linghu.fanfoudroid.WriteDmActivity; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.data.User; 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.module.Feedback; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory; import com.ch_linghu.fanfoudroid.ui.module.NavBar; import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType; import com.ch_linghu.fanfoudroid.util.TextHelper; public abstract class UserListBaseActivity extends BaseActivity implements Refreshable { static final String TAG = "TwitterListBaseActivity"; protected TextView mProgressText; protected NavBar mNavbar; protected Feedback mFeedback; protected static final int STATE_ALL = 0; protected static final String SIS_RUNNING_KEY = "running"; private static final String USER_ID = "userId"; // Tasks. protected GenericTask mFavTask; 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(); } } }; static final int DIALOG_WRITE_ID = 0; abstract protected int getLayoutId(); abstract protected ListView getUserList(); abstract protected TweetAdapter getUserAdapter(); abstract protected void setupState(); abstract protected String getActivityTitle(); abstract protected boolean useBasicMenu(); abstract protected User getContextItemUser(int position); abstract protected void updateTweet(Tweet tweet); protected abstract String getUserId();// 获得用户id public static final int CONTENT_PROFILE_ID = Menu.FIRST + 1; public static final int CONTENT_STATUS_ID = Menu.FIRST + 2; public static final int CONTENT_DEL_FRIEND = Menu.FIRST + 3; public static final int CONTENT_ADD_FRIEND = Menu.FIRST + 4; public static final int CONTENT_SEND_DM = Menu.FIRST + 5; public static final int CONTENT_SEND_MENTION = Menu.FIRST + 6; /** * 如果增加了Context Menu常量的数量,则必须重载此方法, 以保证其他人使用常量时不产生重复 * * @return 最大的Context Menu常量 */ // protected int getLastContextMenuId(){ // return CONTEXT_DEL_FAV_ID; // } @Override protected boolean _onCreate(Bundle savedInstanceState) { if (super._onCreate(savedInstanceState)) { setContentView(getLayoutId()); mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this); mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS); mPreferences.getInt(Preferences.TWITTER_ACTIVITY_STATE_KEY, STATE_ALL); mProgressText = (TextView) findViewById(R.id.progress_text); setupState(); registerForContextMenu(getUserList()); registerOnClickListener(getUserList()); return true; } else { return false; } } @Override protected void onResume() { super.onResume(); checkIsLogedIn(); } @Override protected void onDestroy() { super.onDestroy(); if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { mFavTask.cancel(true); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); if (useBasicMenu()) { AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; User user = getContextItemUser(info.position); if (user == null) { Log.w(TAG, "Selected item not available."); return; } menu.add(0, CONTENT_PROFILE_ID, 0, user.screenName + getResources().getString( R.string.cmenu_user_profile_prefix)); menu.add(0, CONTENT_STATUS_ID, 0, user.screenName + getResources().getString(R.string.cmenu_user_status)); menu.add(0, CONTENT_SEND_MENTION, 0, getResources().getString(R.string.cmenu_user_send_prefix) + user.screenName + getResources().getString( R.string.cmenu_user_sendmention_suffix)); menu.add(0, CONTENT_SEND_DM, 0, getResources().getString(R.string.cmenu_user_send_prefix) + user.screenName + getResources().getString( R.string.cmenu_user_senddm_suffix)); } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); User user = getContextItemUser(info.position); if (user == null) { Log.w(TAG, "Selected item not available."); return super.onContextItemSelected(item); } switch (item.getItemId()) { case CONTENT_PROFILE_ID: launchActivity(ProfileActivity.createIntent(user.id)); return true; case CONTENT_STATUS_ID: launchActivity(UserTimelineActivity .createIntent(user.id, user.name)); return true; case CONTENT_DEL_FRIEND: delFriend(user.id); return true; case CONTENT_ADD_FRIEND: addFriend(user.id); return true; case CONTENT_SEND_MENTION: launchActivity(WriteActivity.createNewTweetIntent(String.format( "@%s ", user.screenName))); return true; case CONTENT_SEND_DM: launchActivity(WriteDmActivity.createIntent(user.id)); return true; default: return super.onContextItemSelected(item); } } /** * 取消关注 * * @param id */ private void delFriend(final String id) { Builder diaBuilder = new AlertDialog.Builder(UserListBaseActivity.this) .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(getBaseContext(), "取消关注成功", Toast.LENGTH_SHORT) .show(); } else if (result == TaskResult.FAILED) { Toast.makeText(getBaseContext(), "取消关注失败", 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(UserListBaseActivity.this) .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(getBaseContext(), "关注成功", Toast.LENGTH_SHORT) .show(); } else if (result == TaskResult.FAILED) { Toast.makeText(getBaseContext(), "关注失败", Toast.LENGTH_SHORT) .show(); } } @Override public String getName() { // TODO Auto-generated method stub return null; } }; @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case OPTIONS_MENU_ID_TWEETS: launchActivity(TwitterActivity.createIntent(this)); return true; case OPTIONS_MENU_ID_REPLIES: launchActivity(MentionActivity.createIntent(this)); return true; case OPTIONS_MENU_ID_DM: launchActivity(DmActivity.createIntent()); return true; } return super.onOptionsItemSelected(item); } private void draw() { getUserAdapter().refresh(); } private void goTop() { getUserList().setSelection(0); } protected void adapterRefresh() { getUserAdapter().refresh(); } // for HasFavorite interface public void doFavorite(String action, String id) { if (!TextHelper.isEmpty(id)) { if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mFavTask = new TweetCommonTask.FavoriteTask(this); mFavTask.setFeedback(mFeedback); mFavTask.setListener(mFavTaskListener); TaskParams params = new TaskParams(); params.put("action", action); params.put("id", id); mFavTask.execute(params); } } } public void onFavSuccess() { // updateProgress(getString(R.string.refreshing)); adapterRefresh(); } public void onFavFailure() { // updateProgress(getString(R.string.refreshing)); } protected void specialItemClicked(int position) { } /* * TODO:单击列表项 */ protected void registerOnClickListener(ListView listView) { listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //Toast.makeText(getBaseContext(), "选择第"+position+"个列表",Toast.LENGTH_SHORT).show(); User user = getContextItemUser(position); if (user == null) { Log.w(TAG, "selected item not available"); specialItemClicked(position); } else { launchActivity(ProfileActivity.createIntent(user.id)); } } }); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } }
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 android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListAdapter; import java.util.ArrayList; import java.util.List; /** * 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 android.database.DataSetObserver; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListAdapter; import android.widget.SectionIndexer; import java.util.ArrayList; import java.util.List; 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
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Nivel1 here. * * @author (your name) * @version (a version number or a date) */ public class Nivel1 extends World { /** * Constructor for objects of class Nivel1. * */ public Nivel1() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(700, 300, 1); prepare(); } /** * Prepare the world for the start of the program. That is: create the initial * objects and add them to the world. */ private void prepare() { Daga daga = new Daga(); addObject(daga, 0, 150); Ninja ninja = new Ninja(); addObject(ninja, 56, 259); } }
Java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Nivel3 here. * * @author (your name) * @version (a version number or a date) */ public class Nivel3 extends World { /** * Constructor for objects of class Nivel3. * */ public Nivel3() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(600, 400, 1); } }
Java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Elixir here. * * @author (your name) * @version (a version number or a date) */ public class Elixir extends Bonos { /** * Act - do whatever the Elixir wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { if(isTouching(Roca.class)){ this.setLocation(getX(), 250); } if(isTouching(Agujero.class)){ this.setLocation(getX()-20, getY()); } } }
Java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Bonos here. * * @author (your name) * @version (a version number or a date) */ public class Bonos extends Actor { /** * Act - do whatever the Bonos wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { // Add your action code here. } }
Java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Cuervo here. * * @author (your name) * @version (a version number or a date) */ public class Cuervo extends Enemigos { private boolean facingLeft; private int Speed; private int animationCounter; private final GreenfootImage cuervoL = new GreenfootImage("Cuervo.png"); private final GreenfootImage cuervoL0 = new GreenfootImage("Cuervo0.png"); private final GreenfootImage cuervoR = new GreenfootImage(cuervoL); private final GreenfootImage cuervoR0 = new GreenfootImage(cuervoL0); private Ninja ninja; private GreenfootSound DagaEncajada; public Cuervo(){ Speed = 3; animationCounter = 0; facingLeft = true; cuervoR.mirrorHorizontally(); cuervoR0.mirrorHorizontally(); DagaEncajada = new GreenfootSound("DagaEncajada.wav"); } /** * Act - do whatever the Cuervo wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { mueve(); checaLimite(); checaColision(); } /** * Mueve Cuervo hacia la Izquierda */ public void mueve(){ setLocation (this.getX() - Speed, this.getY()); animationCounter ++; if(animationCounter < 8){ if(facingLeft) setImage(cuervoL0); else setImage(cuervoR0); }else if(animationCounter < 16){ if(facingLeft) setImage(cuervoL); else setImage(cuervoR); }else if(animationCounter == 16) animationCounter = 0; } public void checaLimite(){ if(getX()< 5 ){ Speed = -Speed; facingLeft = false; } else if(getX() > getWorld().getWidth()-5){ Speed = -Speed; facingLeft = true; } } public void checaColision(){ Niveles mundo = (Niveles)this.getWorld(); ninja = mundo.ninja; if(isTouching(Daga.class)){ ninja.aumentaPuntos(10); DagaEncajada.play(); removeTouching(Daga.class); getWorld().removeObject(this); } } public boolean regresaFacingLeft(){ return facingLeft; } }
Java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Cerca here. * * @author (your name) * @version (a version number or a date) */ public class Cerca extends Obstaculos { private int Speed = 2; /** * Act - do whatever the Cerca wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { mueve(); checaMovimiento(); } public void mueve(){ setLocation (this.getX(), this.getY() - Speed); } public void checaMovimiento(){ if(getY() > getWorld().getHeight()-20 || getY() < 10){ Speed += 4; Speed = -Speed; } } }
Java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Menu here. * * @author (your name) * @version (a version number or a date) */ public class Menu extends World { /** * Constructor for objects of class Menu. * */ public Menu() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(600, 400, 1); } }
Java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Sumo here. * * @author (your name) * @version (a version number or a date) */ public class Sumo extends Enemigos { private int Speed; private int Salud ; private int animationCounter; private boolean moveLeft; private boolean isDead = false; private Cuchillo cuchillo; private Elixir elixir; private Ninja ninja; private GreenfootSound DagaEncajada; private final GreenfootImage WalkRight0 = new GreenfootImage("sumoC0.png"); private final GreenfootImage WalkRight1 = new GreenfootImage("sumoC1.png"); private final GreenfootImage WalkLeft0 = new GreenfootImage(WalkRight0); private final GreenfootImage WalkLeft1 = new GreenfootImage(WalkRight1); public Sumo(){ Salud = 300; Speed = 1; animationCounter = 0; isDead = false; WalkLeft0.mirrorHorizontally(); WalkLeft1.mirrorHorizontally(); moveLeft = true; DagaEncajada = new GreenfootSound("DagaEncajada.wav"); } /** * Act - do whatever the Sumo wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { checaColision(); if(isDead == false){ if(ninjaCerca()){ if(moveLeft) mueveLeft(); else mueveRight(); } } } public void mueveLeft() { setLocation (this.getX() - Speed, this.getY()); animationCounter ++; if(animationCounter < 6) setImage(WalkLeft0); else if(animationCounter < 12) setImage(WalkLeft1); else if(animationCounter == 12) animationCounter = 0; } public void mueveRight() { setLocation (this.getX() + Speed, this.getY()); animationCounter ++; if(animationCounter < 6) setImage(WalkLeft0); else if(animationCounter < 12) setImage(WalkLeft1); else if(animationCounter == 12) animationCounter = 0; } public boolean ninjaCerca(){ Niveles mundo = (Niveles)this.getWorld(); ninja = mundo.ninja(); if( ninja.ninjaX() < this.getX()) moveLeft = true; else moveLeft = false; if(this.getX() - 300 >= ninja.ninjaX() || this.getX() + 300 <= ninja.ninjaX()) return false; else return true; } public void checaColision(){ Niveles mundo = (Niveles)this.getWorld(); ninja = mundo.ninja; if(isTouching(Daga.class)){ DagaEncajada.play(); removeTouching(Daga.class); setLocation (this.getX()+10, this.getY()); Salud -= 50; } if(isTouching(Onda.class)){ DagaEncajada.play(); removeTouching(Onda.class); setLocation (this.getX()+10, this.getY()); Salud -= 50; } if(Salud <= 0){ ninja.aumentaPuntos(10); cuchillo = new Cuchillo(); mundo.addObject(cuchillo, this.getX(), this.getY()+10); elixir = new Elixir(); mundo.addObject(elixir, this.getX(), this.getY()+10); getWorld().removeObject(this); isDead = true; } } }
Java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.Color; /** * Write a description of class Letrero here. * * @author (your name) * @version (a version number or a date) */ public class Letrero extends Actor { private static final Color transparent = new Color(0,0,0,0); int Var = 0; public Letrero(String mensaje, int letrero){ this.despliega(mensaje, letrero); } public void despliega(String mensaje, int letrero){ if(letrero == 1) super.setImage( new GreenfootImage(mensaje, 20, java.awt.Color.BLACK,transparent)); else if(letrero == 2) super.setImage( new GreenfootImage(mensaje, 20, java.awt.Color.BLACK,transparent )); else if(letrero == 3) super.setImage( new GreenfootImage(mensaje, 20, java.awt.Color.BLACK,transparent )); } /** * Act - do whatever the Letrero wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { if(Var == 0){ removeTouching(Letrero.class); Var += 1; } } }
Java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Obstaculos here. * * @author (your name) * @version (a version number or a date) */ public class Obstaculos extends Actor { /** * Act - do whatever the Obstaculos wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { // Add your action code here. } }
Java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Nivel2 here. * * @author (your name) * @version (a version number or a date) */ public class Nivel2 extends World { /** * Constructor for objects of class Nivel2. * */ public Nivel2() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(600, 400, 1); } }
Java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class NinjaM here. * * @author (your name) * @version (a version number or a date) */ public class NinjaM extends Enemigos { private int Salud ; private int Speed; private int Tiempo; private int animationCounter; private boolean moveLeft; private final int NUM_IMAG = 4; private Elixir elixir; private Ninja ninja; private DagaNM dagaNM; private GreenfootSound DagaEncajada; private boolean isDead = false; private final GreenfootImage atacaLeft = new GreenfootImage("ninjaMLC.png"); private final GreenfootImage atacaRight = new GreenfootImage(atacaLeft); private final GreenfootImage ninjaMLeft = new GreenfootImage("ninjamalo.png"); private final GreenfootImage ninjaMRight = new GreenfootImage(ninjaMLeft); private final GreenfootImage[] RunLeft = new GreenfootImage[NUM_IMAG];//Arreglo de imagenes correr hacia la derecha private final GreenfootImage[] RunRight = new GreenfootImage[NUM_IMAG]; public NinjaM(){ Salud = 200; Speed = 3; Tiempo = 0; animationCounter = 0; isDead = false; for(int i = 0; i<NUM_IMAG; i++){ RunLeft[i] = new GreenfootImage("ninjamaloC"+i+".png"); } for(int i = 0; i<NUM_IMAG; i++){ RunRight[i] = new GreenfootImage(RunLeft[i]); RunRight[i].mirrorHorizontally(); } DagaEncajada = new GreenfootSound("DagaEncajada.wav"); atacaRight.mirrorHorizontally(); ninjaMRight.mirrorHorizontally(); } /** * Act - do whatever the NinjaM wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { if(ninjaCerca()){ if(moveLeft) setImage(atacaLeft); else setImage(atacaRight); if( Tiempo > 30){ lanceKnife(); Tiempo = 0; } Tiempo ++; if(Tiempo > 50) Tiempo = 0; } if(moveLeft) setImage(ninjaMLeft); else setImage(ninjaMRight); checaColision(); } public boolean ninjaCerca(){ Niveles mundo = (Niveles)this.getWorld(); Ninja ninja = mundo.ninja(); if( ninja.ninjaX() < this.getX()) moveLeft = true; else moveLeft = false; if(this.getX() - 300 >= ninja.ninjaX() || this.getX() + 300 <= ninja.ninjaX()) return false; else return true; } public void checaColision(){ Niveles mundo = (Niveles)this.getWorld(); ninja = mundo.ninja; if(isTouching(Daga.class)){ DagaEncajada.play(); removeTouching(Daga.class); Salud -= 50; } if(isTouching(Onda.class)){ DagaEncajada.play(); removeTouching(Onda.class); Salud -= 50; } if(Salud <= 0){ ninja.aumentaPuntos(10); elixir = new Elixir(); mundo.addObject(elixir, this.getX(), this.getY()+10); getWorld().removeObject(this); isDead = true; } } public void lanceKnife(){ World world = this.getWorld(); Greenfoot.playSound("Cuchillo.wav"); dagaNM = new DagaNM(moveLeft); world.addObject(dagaNM, this.getX(), this.getY()-50); } }
Java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Daga here. * * @author (your name) * @version (a version number or a date) */ public class Daga extends Ninja { private boolean Dir; public Daga(boolean dir){ Dir = dir; } /** * Act - do whatever the Daga wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { move(); } private void move(){ if(Dir) super.move(10); else { super.setRotation(180); super.move(10); } } }
Java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Roca here. * * @author (your name) * @version (a version number or a date) */ public class Roca extends Obstaculos { /** * Act - do whatever the Roca wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { // Add your action code here. } }
Java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Nivel1 here. * * @author (your name) * @version (a version number or a date) */ public class Niveles extends World { //Variables de instancia private int Nivel; // variable para poder cambiar de nivel private int Scroll;//Variable que controla el scroll de los niveles private int ninjaPosX;// variable X para la posiscion de el ninja private int ninjaPosY;//variable para la posicion de el ninja en Y private int posMoneda; private int soundCounter;//variable para el sonido de fondo el del juego private int ayudaSig =0; //variable para pasar de siguiente pagina en la ayuda public GreenfootSound soundNivel1; public GreenfootSound soundNivel2; Ninja ninja = new Ninja(); SaludL salud = new SaludL(); /** * Constructor de el Niveles * */ public Niveles() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(800, 320, 1, false); Greenfoot.setSpeed(47); //Asigna la velocidad de el juego //Greenfoot.start();//inicia el juego soundNivel1 = new GreenfootSound("fondo1.wav"); soundNivel1.setVolume(70); soundNivel2 = new GreenfootSound("fondo2.wav"); soundNivel2.setVolume(70); posMoneda = 50; soundCounter = 0; iniciaNivel( 0 ); setPaintOrder(Cuchillo.class,Vida.class,Letrero.class,SaludL.class,Cerca.class,Ninja.class, Moneda.class, Roca.class,Sumo.class, NinjaM.class,Ladron.class, Cuervo.class); } /* * Medtodo actuda de el mundo * */ public void act(){ soundCounter ++; if(Nivel == 1){ soundNivel1.play(); }else if(Nivel == 2){ soundNivel2.play(); }else if(Nivel == 3){ // MusicaN3.play(); } } /* * Inicia el Nivel correspondiente dependiendo de el avance de el jugador */ public void iniciaNivel(int nivel) { Nivel = nivel; if(Nivel == 0)//****************MENU**************** preparaMenu(); else if(Nivel == 1)//****************************** NIVEL 1 ************************** preparaNivel1(1); else if(Nivel == 2)//****************************** NIVEL 2 ************************** preparaNivel2(1); else if(Nivel == 3)//****************************** NIVEL 3 ************************** preparaNivel3(2); else if(Nivel == 4) ganaste(); else if (Nivel == -1)//****************************** GAME OVER ************************** gameOver(); } /* * Metodo para preparar el nivel 1 */ public void preparaNivel1(int scroll){ Scroll = scroll; setBackground("Nivel1.png"); removeObjects(getObjects(null)); if(Scroll == 1){ //************************Escenario 1 Nivel 1*************************** ninjaPosX = 40; ninjaPosY = 280; //posicion inicial de el ninja addObject(ninja, ninjaPosX ,ninjaPosY); addObject(new SaludL(),150,10); addObject(new Letrero("Puntos = 0", 1),400,20); addObject(new Letrero(" = 3", 2),500,20); addObject(new Vida(),470,20); addObject(new Letrero(" = 5", 3),600,20); addObject(new Cuchillo(),570,20); addObject(new Cuervo(),512,60); addObject(new Cuervo(),448,181); addObject(new Cuervo(),225,91); addObject(new Roca(), 350, 290); addObject(new Roca(), 748, 290); addObject(new Cerca(), 200, 230);//primera cerca addObject(new Cerca(), 527, 282);//Segunda Cerca for(int i=0; i < 4; i++) addObject(new Moneda(),100 +(i*posMoneda) ,300); for(int i=0; i< 4; i++) addObject(new Moneda(),350,250 - (i*posMoneda)); for(int i=0; i < 5; i++) addObject(new Moneda(),450 +(i*posMoneda) ,300); for(int i=0; i< 3; i++) addObject(new Moneda(),670,200 - (i*posMoneda)); for(int i=0; i< 4; i++) addObject(new Moneda(),750,250 - (i*posMoneda)); addObject(new Ladron(), 835, 280); }else if(Scroll == 2){ removeObjects(getObjects(null)); ninjaPosX = 40; ninjaPosY = 280; //posicion inicial de el ninja addObject(new SaludL(),150,10); addObject(ninja, ninjaPosX ,ninjaPosY); ninja.CambiaLetros(1); ninja.CambiaLetros(2); addObject(new Vida(),470,20); ninja.CambiaLetros(3); addObject(new Cuchillo(),570,20); addObject(ninja, ninjaPosX ,ninjaPosY); addObject(new Cuervo(),448,142); addObject(new Cuervo(),225,49); addObject(new Cuervo(),512,90); addObject(new Roca(), 500, 290); addObject(new Roca(), 700, 290); addObject(new Cerca(), 200, 280);//primera cerca addObject(new Cerca(), 270, 250);//Segunda Cerca addObject(new Cerca(), 600, 150);//cuarta cerca addObject(new Ladron(), 835, 280); for(int i=0; i < 7; i++) addObject(new Moneda(),100 +(i*posMoneda) ,300); for(int i=0; i< 4; i++) addObject(new Moneda(),350,250 - (i*posMoneda)); for(int i=0; i< 5; i++) addObject(new Moneda(),500,250 - (i*posMoneda)); for(int i=0; i< 2; i++) addObject(new Moneda(),580 + (i*posMoneda),150); addObject(new Moneda(),600,300); for(int i=0; i< 4; i++) addObject(new Moneda(),700+(i*posMoneda),250 - (i*posMoneda)); } } /* * Metodo para preparar objetos de el nivel 2 */ public void preparaNivel2(int scroll){ Scroll = scroll; removeObjects(getObjects(null)); setBackground("Nivel2.png"); if(Scroll == 1){ ninjaPosX = 40; ninjaPosY = 280; addObject(new SaludL(),150,10); addObject(ninja, ninjaPosX ,ninjaPosY); ninja.CambiaLetros(1); ninja.CambiaLetros(2); addObject(new Vida(),470,20); ninja.CambiaLetros(3); addObject(new Cuchillo(),570,20); addObject(ninja, ninjaPosX ,ninjaPosY); addObject(new Cuervo(),700,142); addObject(new Cuervo(),512,60); addObject(new Roca(), 748, 290); addObject(new Cerca(), 170, 200); addObject(new Cerca(), 450, 150); addObject(new Agujero(), 650, 310); for(int i=0; i < 5; i++) addObject(new Moneda(),250 +(i*posMoneda) ,300); for(int i=0; i< 3; i++) addObject(new Moneda(),250+(i*posMoneda),250 - (i*posMoneda)); for(int i=0; i< 4; i++) addObject(new Moneda(),750,250 - (i*posMoneda)); for(int i=0; i< 3; i++) addObject(new Moneda(),600+(i*posMoneda),100 + (i*posMoneda)); addObject(new NinjaM(), 550, 280); addObject(new Ladron(), 835, 280); }else if(Scroll == 2){ removeObjects(getObjects(null)); ninjaPosX = 40; ninjaPosY = 280; addObject(ninja, ninjaPosX ,ninjaPosY); addObject(new SaludL(),150,10); ninja.CambiaLetros(1); ninja.CambiaLetros(2); addObject(new Vida(),470,20); ninja.CambiaLetros(3); addObject(new Cuchillo(),570,20); addObject(new Cuervo(),448,142); addObject(new Cuervo(),225,49); addObject(new Roca(), 200, 290); addObject(new Cerca(), 370, 150); addObject(new Cerca(), 550, 200); addObject(new Agujero(), 770, 310); for(int i=0; i< 4; i++) addObject(new Moneda(),200,250 - (i*posMoneda)); for(int i=0; i< 4; i++) addObject(new Moneda(),750 + (i*posMoneda),250) ; for(int i=0; i< 3; i++) addObject(new Moneda(),600,300 - (i*posMoneda)); addObject(new NinjaM(), 570, 280); addObject(new NinjaM(), 420, 280); addObject(new Ladron(), 835, 280); } } /* * Metodo para preparar los objetos de el nivel3 */ public void preparaNivel3(int scroll){ Scroll = scroll; removeObjects(getObjects(null)); setBackground("Nivel3.png"); if(Scroll == 1){ removeObjects(getObjects(null)); ninjaPosX = 40; ninjaPosY = 280; addObject(ninja, ninjaPosX ,ninjaPosY); addObject(new SaludL(),150,10); ninja.CambiaLetros(1); ninja.CambiaLetros(2); addObject(new Vida(),470,20); ninja.CambiaLetros(3); addObject(new Cuchillo(),570,20); addObject(new Cuervo(),448,142); addObject(new Cuervo(),225,49); addObject(new Cuervo(),725,181); addObject(new Roca(), 270, 290); addObject(new Cerca(), 370, 150); addObject(new Cerca(), 670, 280); addObject(new Agujero(), 170, 310); for(int i=0; i< 3; i++) addObject(new Moneda(),100+(i*posMoneda),250 - (i*posMoneda)); for(int i=0; i< 4; i++) addObject(new Moneda(),270,250 - (i*posMoneda)); for(int i=0; i< 3; i++) addObject(new Moneda(),500+(i*posMoneda),250 - (i*posMoneda)); addObject(new Sumo(), 700, 280); addObject(new NinjaM(), 570, 280); addObject(new NinjaM(), 500, 280); addObject(new Ladron(), 835, 280); }else if(Scroll == 2){ ninjaPosX = 40; ninjaPosY = 280; addObject(ninja, ninjaPosX ,ninjaPosY); addObject(new SaludL(),150,10); ninja.CambiaLetros(1); ninja.CambiaLetros(2); addObject(new Vida(),470,20); ninja.CambiaLetros(3); addObject(new Cuchillo(),570,20); addObject(new Cuervo(),725,142); addObject(new Cuervo(),512,60); addObject(new Roca(), 748, 290); addObject(new Cerca(), 170, 200); addObject(new Cerca(), 450, 150); addObject(new Agujero(), 650, 310); for(int i=0; i < 5; i++) addObject(new Moneda(),250 +(i*posMoneda) ,300); for(int i=0; i< 3; i++) addObject(new Moneda(),250+(i*posMoneda),250 - (i*posMoneda)); for(int i=0; i< 4; i++) addObject(new Moneda(),750,250 - (i*posMoneda)); for(int i=0; i< 3; i++) addObject(new Moneda(),600+(i*posMoneda),100 + (i*posMoneda)); addObject(new NinjaM(), 550, 280); addObject(new Ladron(), 835, 280); addObject(new Sumo(), 700, 280); } } /* * Metodo para cuando el jugador pierde el juego se muestra en pantalla un mensaje de Gameover */ public void gameOver(){ removeObjects(getObjects(null)); setBackground("gameOver.jpg"); Greenfoot.delay(200); preparaMenu(); } /* * Metodo para cuando el jugador gana el juego se muestra un mensaje de Ganaste */ public void ganaste(){ removeObjects(getObjects(null)); setBackground("ganaste.png"); ninjaPosX = 40; ninjaPosY = 280; addObject(ninja, ninjaPosX ,ninjaPosY); ninja.guardaPuntos(); Greenfoot.delay(200); preparaMenu(); } /* * Regresa el ninja(jugador principal */ public Ninja ninja(){ return ninja; } /* * prepara el menu incial de el juego */ public void preparaMenu(){ removeObjects(getObjects(null)); setBackground("Menu.png"); addObject(new Jugar(getWidth()/2,180), getWidth()/2, 180); addObject(new Ayuda( getWidth()/2,280), getWidth()/2, 280); addObject(new Records(getWidth()/4,280),getWidth()/4, 280); addObject(new Creditos(getWidth()/2 + getWidth()/4,280),getWidth()/2 + getWidth()/4, 280); } /* * Muestra la ayuda de el juego */ public void preparaAyuda(){ removeObjects(getObjects(null)); ayudaSig = 0; setBackground("AyudaM0.png"); addObject(new Atras(20,20),20,20); addObject(new Adelante(getWidth()-20,getHeight()-20),getWidth()-20,getHeight()-20); Greenfoot.delay(20); } /* * Muestra los creditos del el juego */ public void muestraCreditos(){ removeObjects(getObjects(null)); setBackground("CreditosM.png"); addObject(new Atras(20,20),20,20); Greenfoot.delay(20); } /* * Muestra los records de el juego */ public void muestraRecords(){ removeObjects(getObjects(null)); setBackground("RecordsM.png"); addObject(new Atras(20,20),20,20); addObject(new ScoreBoard(720,300),getWidth()/2,(getHeight()/2)); } /* * Metodo para recorrer las paginas de la ayuda */ public void siguientePagina(){ ayudaSig++; if(ayudaSig>=3) { preparaMenu(); return; } setBackground(new GreenfootImage("AyudaM"+ayudaSig+".png")); } }
Java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Cuchillo here. * * @author (your name) * @version (a version number or a date) */ public class Cuchillo extends Bonos { /** * Act - do whatever the Cuchillo wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { if(isTouching(Roca.class)){ this.setLocation(getX(), 250); } } }
Java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Ladrones here. * * @author (your name) * @version (a version number or a date) */ public class Ladrones extends Enemigos { /** * Act - do whatever the Ladrones wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { // Add your action code here. } }
Java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Ladron here. * * @author (your name) * @version (a version number or a date) */ public class Ladron extends Enemigos { private int Salud ; private int Speed; private int animationCounter; private final int NUM_IMAG = 4; private Ninja ninja; private boolean isDead; private GreenfootSound DagaEncajada; private final GreenfootImage[] RunLeft = new GreenfootImage[NUM_IMAG];//Arreglo de imagenes correr hacia la derecha private Cuchillo cuchillo; public Ladron (){ Salud = 100; Speed = 3; animationCounter = 0; isDead = false; for(int i = 0; i<NUM_IMAG; i++){ RunLeft[i] = new GreenfootImage("ladronC"+i+".png"); } DagaEncajada = new GreenfootSound("DagaEncajada.wav"); } /** * Act - do whatever the Ladron wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { /*Niveles mundo = (Niveles)this.getWorld(); ninja = mundo.ninja; Object obj = getObjectsInRange( 20 ,null); if(obj == ninja) */ if(!isDead){ mueveLeft(); checaLimite(); } checaColision(); } /** * Mueve Ladron hacia la Izquierda */ public void mueveLeft(){ setLocation (this.getX() - Speed, this.getY()); animationCounter ++; if(animationCounter < 4) setImage(RunLeft[0]); else if(animationCounter < 8) setImage(RunLeft[1]); else if(animationCounter < 12) setImage(RunLeft[2]); else if(animationCounter < 16) setImage(RunLeft[3]); else if(animationCounter == 16 ) animationCounter = 0; } public void checaLimite(){ if(getX() < -200) setLocation (getWorld().getWidth(), this.getY()); } public void checaColision(){ Niveles mundo = (Niveles)this.getWorld(); ninja = mundo.ninja; if(isTouching(Daga.class)){ DagaEncajada.play(); removeTouching(Daga.class); setLocation (this.getX() + 20, this.getY()); Salud -= 50; } if(isTouching(Onda.class)){ DagaEncajada.play(); removeTouching(Onda.class); setLocation (this.getX() + 20, this.getY()); Salud -= 50; } if(Salud <= 0){ ninja.aumentaPuntos(10); cuchillo = new Cuchillo(); mundo.addObject(cuchillo, this.getX(), this.getY()+10); getWorld().removeObject(this); isDead = true; } } }
Java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class DagaNM here. * * @author (your name) * @version (a version number or a date) */ public class DagaNM extends NinjaM { private boolean Dir; public DagaNM(boolean dir){ Dir = dir; } /** * Act - do whatever the Daga wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { move(); } private void move(){ if(!Dir) super.move(10); else { super.setRotation(180); super.move(10); } } }
Java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Moneda here. * * @author (your name) * @version (a version number or a date) */ public class Moneda extends Bonos { private int valor; private int animationCounter; private final GreenfootImage coinL = new GreenfootImage("coin.png"); private final GreenfootImage coinR = new GreenfootImage(coinL); public Moneda(){ animationCounter = 0; coinR.mirrorHorizontally(); } /** * Act - do whatever the Moneda wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { animacion(); //checaColision(); } public void animacion(){ animationCounter ++; if(animationCounter < 20) setImage(coinR); else if(animationCounter < 40) setImage(coinL); else if(animationCounter == 40) animationCounter = 0; } }
Java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Salud here. * * @author (your name) * @version (a version number or a date) */ public class SaludL extends Actor { private int NUM = 11; private final GreenfootImage[] Barra = new GreenfootImage[NUM]; private Ninja ninja; public SaludL(){ for(int i = 0; i<NUM; i++) Barra[i] = new GreenfootImage("BarraSalud"+i+".png"); } /** * Act - do whatever the Salud wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { Niveles mundo = (Niveles)this.getWorld(); ninja = mundo.ninja; int salud = ninja.rsalud(); switch(salud){ case 100: setImage(Barra[10]); break; case 90: setImage(Barra[9]); break; case 80: setImage(Barra[8]); break; case 70: setImage(Barra[7]); break; case 60: setImage(Barra[6]); break; case 50: setImage(Barra[5]); break; case 40: setImage(Barra[4]); break; case 30: setImage(Barra[3]); break; case 20: setImage(Barra[2]); break; case 10: setImage(Barra[1]); break; case 0: setImage(Barra[0]); break; } } }
Java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Agujero here. * * @author (your name) * @version (a version number or a date) */ public class Agujero extends Obstaculos { /** * Act - do whatever the Agujero wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { // Add your action code here. } }
Java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Vida here. * * @author (your name) * @version (a version number or a date) */ public class Vida extends Ninja { /** * Act - do whatever the Vida wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { // Add your action code here. } }
Java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Zumo here. * * @author (your name) * @version (a version number or a date) */ public class Zumo extends Enemigos { /** * Act - do whatever the Zumo wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { // Add your action code here. } }
Java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Enemigos here. * * @author (your name) * @version (a version number or a date) */ public class Enemigos extends Actor { /** * Act - do whatever the Enemigos wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { // Add your action code here. } }
Java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Onda here. * * @author (your name) * @version (a version number or a date) */ public class Onda extends Ninja { private boolean Dir; private int cont; public Onda(boolean dir){ Dir = dir; cont = 0; } public void act() { if(cont <15) move(); else getWorld().removeObject(this); } private void move(){ if(Dir) super.move(10); else { super.setRotation(180); super.move(10); } cont ++; } }
Java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Ninja here. * * @author (your name) * @version (a version number or a date) */ public class Ninja extends Actor { private boolean isKeyPressed; private boolean facingRight; private boolean isJumping; private boolean isLanceKnife; private boolean isDown; private boolean isAtack; private boolean isDead; private int iL = 0; private int TimeK = 0; protected int Salud; protected int Vidas; protected int Cuchillos; protected int Puntos; private int Speed; private int Scroll; private int Nivel; private int NivelAux; private int verticalSpeed = 0; private int acceleration = 1; private int animationCounter; private int animationDead; private int animationKnife; private int jumpDistance = 15; private int ninjaCentro; private int ninjaA; private Daga daga; private Onda onda; private final int NUM_IMAG = 4; private GreenfootSound golpeCerca; private GreenfootSound golpeadoCuervo; private final GreenfootImage muertoCerca = new GreenfootImage("ninjaMC.png"); private final GreenfootImage AtackRight = new GreenfootImage("ninjaE.png"); private final GreenfootImage AtackLeft = new GreenfootImage(AtackRight); private final GreenfootImage DuckingR = new GreenfootImage("ninjaA.png"); private final GreenfootImage DuckingL = new GreenfootImage(DuckingR); private final GreenfootImage LanceKR = new GreenfootImage("ninjaLC.png"); private final GreenfootImage LanceKL = new GreenfootImage(LanceKR); private final GreenfootImage ImagenNR = new GreenfootImage("ninja.PNG"); private final GreenfootImage ImagenNL = new GreenfootImage(ImagenNR); private final GreenfootImage JumpRight = new GreenfootImage("ninjaB0.png"); private final GreenfootImage JumpLeft = new GreenfootImage(JumpRight); private final GreenfootImage DownRight = new GreenfootImage("ninjaB1.png"); private final GreenfootImage DownLeft = new GreenfootImage(DownRight); private final GreenfootImage[] ImagensWR = new GreenfootImage[NUM_IMAG];//Arreglo de la imagenes de caminar Derecha de el jugador private final GreenfootImage[] ImagensWL = new GreenfootImage[NUM_IMAG];//Arreglo para las imagenes de caminar Izquierda de el jugador public Ninja(){ Salud = 100; Vidas = 3; Puntos = 0; Cuchillos = 5; Speed = 6; Scroll = 1; Nivel = 1; NivelAux = 1; animationCounter = 0; animationDead = 0; animationKnife = 0; facingRight = true; isJumping = false; isLanceKnife = false; isAtack = false; isDown = false; isDead = false; ImagenNL.mirrorHorizontally();//voltea imagen para ir hacia la izquierda JumpLeft.mirrorHorizontally();//voltea imagen para brincar hacia la Izquierda DownLeft.mirrorHorizontally();//Volte la imagen caer hacia la Izquierda LanceKL.mirrorHorizontally();//Voltea imagen hacia la izquierda lanza cuchillo DuckingL.mirrorHorizontally();//Voltea la imagen agachado hacia la Izquierda AtackLeft.mirrorHorizontally(); //voltea ninja cuando esta atacando hacia la Izquierda for(int i = 0; i<NUM_IMAG; i++) ImagensWR[i] = new GreenfootImage("ninjaC"+i+".png"); for(int i = 0; i<NUM_IMAG; i++){ ImagensWL[i] = new GreenfootImage(ImagensWR[i]); ImagensWL[i].mirrorHorizontally(); } golpeCerca = new GreenfootSound("golpeCerca.wav"); golpeadoCuervo = new GreenfootSound("puñetaso.wav"); ninjaCentro = getImage().getHeight() /2; ninjaA = DownRight.getHeight() / 2; } /** * Act - do whatever the Ninja wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { if(!isDead){ checaTeclas(); checaColiciones(); Limtes(); if(!checaSuelo()) fall(); else isJumping = false; }else IsDead(); } /** * Checa teclas y hace las acciones */ public void checaTeclas() { isKeyPressed = false; isDown = false; if((Greenfoot.isKeyDown("right") || Greenfoot.isKeyDown("d")) && (Greenfoot.isKeyDown("left") || Greenfoot.isKeyDown("a"))) { detenCaminado(); } else if(Greenfoot.isKeyDown("right") || Greenfoot.isKeyDown("d")) { animationCounter ++; walkHR(); isKeyPressed = true; facingRight = true; } else if(Greenfoot.isKeyDown("left") || Greenfoot.isKeyDown("a")){ animationCounter ++; walkHL(); isKeyPressed = true; facingRight = false; } if((Greenfoot.isKeyDown("up") || Greenfoot.isKeyDown("w")) && isJumping == false)//Brincar { isKeyPressed = true; jump(); } if((Greenfoot.isKeyDown("down") || Greenfoot.isKeyDown("s")) && isJumping == false) { isKeyPressed = true; isDown = true; down(); } if(Greenfoot.isKeyDown("r") && TimeK > 20 ) //Lanzar cuchillo { isKeyPressed = true; isLanceKnife = true; lanceKnife(); TimeK = 0; } if(Greenfoot.isKeyDown("e") && TimeK > 20 && !isJumping){// Atacar isKeyPressed = true; isAtack = true; TimeK = 0; } if(isAtack && !isLanceKnife){ atack(); }else if(isLanceKnife){ lancingKnife(); } else if(!isKeyPressed) { detenCaminado(); } if(TimeK <25)//Este if es para que la variable Time no tome valores muy altos TimeK ++;//Sirve para el retraso de el ataca y de el cuchillo } public void lancingKnife(){ animationKnife ++; if(animationKnife > 10){ isLanceKnife = false; animationKnife = 0; } if(facingRight) setImage(LanceKR); else setImage(LanceKL); } public void detenCaminado() { if(facingRight) setImage(ImagenNR); else setImage(ImagenNL); } /** * Mueve el ninja a la Izquierda y cambia la imagen */ public void walkHL(){ setLocation (this.getX() - Speed, this.getY()); if(isTouching(Roca.class) && getY() > 250 ){ setLocation (this.getX() + Speed, this.getY()); } if(animationCounter < 5) setImage(ImagensWL[0]); else if(animationCounter < 10) setImage(ImagensWL[1]); else if(animationCounter < 15) setImage(ImagensWL[2]); else if(animationCounter < 20) setImage(ImagensWL[3]); else if(animationCounter == 20 ) animationCounter = 0; } /** * Mueve el ninja a la Derecha y cambia sus imagenes */ public void walkHR(){ setLocation (this.getX() + Speed, this.getY()); if(isTouching(Roca.class) && getY() > 250 ){ setLocation (this.getX() - Speed, this.getY()); } if(animationCounter < 5) setImage(ImagensWR[0]); else if(animationCounter < 10) setImage(ImagensWR[1]); else if(animationCounter < 15) setImage(ImagensWR[2]); else if(animationCounter < 20) setImage(ImagensWR[3]); else if(animationCounter == 20 ) animationCounter = 0; } public void jump(){ verticalSpeed = verticalSpeed - jumpDistance; fall(); } public void fall(){ setLocation ( getX(), getY() + verticalSpeed); verticalSpeed = verticalSpeed + acceleration; isJumping = true; checaSuelo(); if (facingRight){ if(verticalSpeed > 0) setImage(DownRight); else setImage(JumpRight); } else{ if(verticalSpeed > 0) setImage(DownLeft); else setImage(JumpLeft); } } private boolean checaSuelo() { World mundo = getWorld(); if (getY() < mundo.getHeight()-40 && getOneObjectAtOffset (-17, ninjaCentro-5, Roca.class) == null && getOneObjectAtOffset (17, ninjaCentro-5, Roca.class) == null) { return false; // no esta tocando el suelo. } if ( getY() > mundo.getHeight() -40 /*|| getY() > 220 && getOneObjectAtOffset (-17, ninjaCentro-5, Roca.class) != null && getOneObjectAtOffset (17, ninjaCentro-5, Roca.class) != null*/) { setLocation( getX(), getY()-1); } verticalSpeed = 0; return true; } public void atack(){ animationCounter ++; if(animationCounter > 10){ Greenfoot.playSound("Espada.wav"); isAtack = false; animationCounter = 0; World world = this.getWorld(); onda = new Onda(facingRight); world.addObject(onda, this.getX(), this.getY()-5); } if(facingRight) setImage(AtackRight); else setImage(AtackLeft); } public void down(){ if(facingRight) setImage(DuckingR); else setImage(DuckingL); if(!isTouching(Roca.class)){ setLocation(getX(),296); } else setLocation(getX(),245); } public void lanceKnife(){ if(Cuchillos > 0){ World world = this.getWorld(); Greenfoot.playSound("Cuchillo.wav"); daga = new Daga(facingRight); world.addObject(daga, this.getX(), this.getY()-5); disminuyeCuchillos(); }else Greenfoot.playSound("NoCuchillos.wav"); } public void disminuyeVida(){ Vidas--; isDead = true; CambiaLetros(2); } public void aumentaVida(){ Greenfoot.playSound("vida.wav"); Vidas ++; CambiaLetros(2); } public void disminuyeSalud(int less){ Salud -= less; if(Salud < 0) disminuyeVida(); } public void disminuyeCuchillos(){ Cuchillos --; CambiaLetros(3); } public void disminuyePuntos(int puntos){ if(Puntos > 0 ){ Puntos -= puntos; CambiaLetros(1); } } public void aumentaPuntos(int puntos){ Puntos += puntos; CambiaLetros(1); } public void aumentaSalud(){ if(Salud <= 100) Salud += 20; else aumentaVida(); } public void aumentaCuchillos(int cuchillos){ Cuchillos += cuchillos; CambiaLetros(3); } public int rsalud(){ return Salud; } public void checaColiciones(){ Actor cuervo = getOneIntersectingObject(Cuervo.class); Actor cerca = getOneIntersectingObject(Cerca.class); Actor ninjaM = getOneIntersectingObject(NinjaM.class); Actor sumo = getOneIntersectingObject(Sumo.class); Actor agujero = getOneIntersectingObject(Agujero.class); if(cuervo != null){ golpeadoCuervo.play(); disminuyeSalud(10); if(cuervo.getX() > this.getX()) this.setLocation(getX()- 20,getY()); else this.setLocation(getX() + 20,getY()); } if(isTouching(Moneda.class) && iL > 10){ Greenfoot.playSound("coin.wav"); removeTouching(Moneda.class); aumentaPuntos(5); iL = 0; } if(isTouching(Cuchillo.class)){ Greenfoot.playSound("bonus.wav"); removeTouching(Cuchillo.class); aumentaCuchillos(5); } if(isTouching(Elixir.class)) { Greenfoot.playSound("bonus.wav"); removeTouching(Elixir.class); aumentaSalud(); } if(isTouching(Ladron.class)&& iL > 40){ disminuyePuntos(10); iL = 0; } if(iL < 50) iL ++; if(ninjaM != null){ Greenfoot.playSound("puñetasoM.wav"); if(ninjaM.getX() > this.getX()) this.setLocation(getX()- 100,getY()); else this.setLocation(getX() + 100,getY()); this.disminuyeSalud(20); } if(sumo != null){ Greenfoot.playSound("golpeSumo.wav"); if(sumo.getX() > this.getX()) this.setLocation(getX()- 100,getY()); else this.setLocation(getX() + 100,getY()); this.disminuyeSalud(30); } if(agujero != null){ Greenfoot.playSound("caer.WAV"); this.setLocation(getX() ,getY()+ 200); this.disminuyeVida(); } if(cerca != null){ golpeCerca.play(); this.setLocation(getX(),300); this.setImage(muertoCerca); disminuyeVida(); } } public void Limtes(){ Niveles mundo = (Niveles)this.getWorld(); if(NivelAux == 1){ if(this.getX()>mundo.getWidth()+20 && Scroll == 1){ Scroll = 2; mundo.preparaNivel1(Scroll); }else if (this.getX()>mundo.getWidth()+20 && Scroll == 2){ Scroll = 1; NivelAux = 2; } }else if (NivelAux == 2 ){ if( Nivel == 1 ){ Nivel = 2; mundo.iniciaNivel(Nivel); Scroll = 2; } if (this.getX()>mundo.getWidth()+20 && Scroll == 2){{ mundo.preparaNivel2(Scroll); Scroll = 1; } }else if(this.getX()>mundo.getWidth()+20 && Scroll == 1) NivelAux =3; }else if(NivelAux == 3 ){ if(Nivel == 2 ){ Nivel = 3; mundo.iniciaNivel(Nivel); Scroll = 2; } if (this.getX()>mundo.getWidth()+20 && Scroll == 2){{ mundo.preparaNivel3(Scroll); Scroll = 1; } }else if(this.getX()>mundo.getWidth()+20 && Scroll == 1) NivelAux =4; }else if(NivelAux == 4){ mundo.iniciaNivel(NivelAux); } } public void IsDead(){ Niveles mundo = (Niveles)this.getWorld(); if(Vidas > 0){ Salud = 0; if(animationDead > 30){ this.setLocation(40,280); isDead = false; Salud = 100; animationDead = 0; } animationDead ++; }else if(Vidas <= 0) mundo.iniciaNivel(-1); } public int ninjaX(){ return getX(); } public int ninjaY(){ return getY(); } public void CambiaLetros(int jug){ if(jug == 1 ){ Letrero nuevo = new Letrero("Puntos = " + Puntos, 1); getWorld().addObject(nuevo,400,20); }else if(jug == 2 ){ Letrero nuevo = new Letrero(" = " + Vidas, 2); getWorld().addObject(nuevo,500,20); }else if(jug == 3){ Letrero nuevo = new Letrero(" = " + Cuchillos, 3); getWorld().addObject(nuevo,600,20); } } public void guardaPuntos() { if (UserInfo.isStorageAvailable()) { UserInfo myInfo = UserInfo.getMyInfo(); if (Puntos > myInfo.getScore() || myInfo.getScore()==0) { myInfo.setScore(Puntos); myInfo.store(); // write back to server } } } }
Java
/** Automatically generated file. DO NOT MODIFY */ package android.support.v7.appcompat; public final class BuildConfig { public final static boolean DEBUG = true; }
Java
/* * Copyright (C) 2013 The Android Open Source Project * * 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 android; // Stub java file to make inclusion into some IDE's work. public final class UnusedStub { private UnusedStub() { } }
Java
/** Automatically generated file. DO NOT MODIFY */ package com.google.android.gms; public final class BuildConfig { public final static boolean DEBUG = true; }
Java
package org.vaadin.appfoundation.example; import java.io.File; import java.net.URL; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.vaadin.appfoundation.i18n.InternationalizationServlet; import org.vaadin.appfoundation.persistence.facade.FacadeFactory; public class DemoContextListener implements ServletContextListener { public void contextDestroyed(ServletContextEvent arg0) { } public void contextInitialized(ServletContextEvent arg0) { URL url = DemoApplication.class.getClassLoader().getResource( "translations.xml"); File file = new File(url.getPath()); InternationalizationServlet.loadTranslations(file); try { FacadeFactory.registerFacade(ExampleMockFacade.class, "default", true); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } System.setProperty("authentication.maxFailedLoginAttempts", "2"); } }
Java
package org.vaadin.appfoundation.example; public class MainView extends Page { private static final long serialVersionUID = -4129066221019915249L; public MainView() { super("main view"); } }
Java
package org.vaadin.appfoundation.example; import org.vaadin.appfoundation.authentication.data.User; import org.vaadin.appfoundation.authentication.util.PasswordUtil; import org.vaadin.appfoundation.view.ViewHandler; import com.vaadin.Application; import com.vaadin.service.ApplicationContext.TransactionListener; public class ExampleData implements TransactionListener { private static final long serialVersionUID = 5184835038248219005L; // Store this instance of the view handler in this thread local variable private static final ThreadLocal<ExampleData> instance = new ThreadLocal<ExampleData>(); private final Application application; private User user1; private User user2; public ExampleData(Application application) { instance.set(this); this.application = application; } /** * {@inheritDoc} */ public void transactionEnd(Application application, Object transactionData) { // Clear thread local instance at the end of the transaction if (this.application == application) { instance.set(null); } } /** * {@inheritDoc} */ public void transactionStart(Application application, Object transactionData) { // Set the thread local instance if (this.application == application) { instance.set(this); } } /** * Initializes the {@link ViewHandler} for the given {@link Application} * * @param application */ public static void initialize(Application application) { if (application == null) { throw new IllegalArgumentException("Application may not be null"); } ExampleData exampleData = new ExampleData(application); application.getContext().addTransactionListener(exampleData); } public static User getUser(Long id) { if (id == 1L) { if (instance.get().user1 == null) { instance.get().user1 = new User(); instance.get().user1.setUsername("demo"); instance.get().user1.setPassword(PasswordUtil .generateHashedPassword("demo123")); } return instance.get().user1; } else if (id == 2L) { if (instance.get().user2 == null) { instance.get().user2 = new User(); instance.get().user2.setUsername("demo2"); instance.get().user2.setPassword(PasswordUtil .generateHashedPassword("demo123")); } return instance.get().user2; } return null; } }
Java
package org.vaadin.appfoundation.example; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.net.URL; public class ExampleLoader { public static enum Examples { // Example code for the authentication module AUTHENTICATE_USER("examples/authenticate_user.txt"), AUTHENTICATE_CONTEXT_LISTENER( "examples/authentication_context_listener.txt"), AUTHENTICATE_INIT_MODULE("examples/authentication_init_module.txt"), AUTHENTICATE_GET_USER_INSTANCE( "examples/authentication_get_user_instance.txt"), AUTHENTICATE_LOGOUT_LISTENER( "examples/authentication_logout_listener.txt"), AUTHENTICATE_LOGOUT_BUTTON("examples/authentication_logout_button.txt"), AUTHENTICATE_CHANGE_PASSWORD( "examples/authentication_change_password.txt"), AUTHENTICATE_REGISTER_USER("examples/authentication_register.txt"), AUTHENTICATE_FETCH_USER("examples/authentication_fetch_user.txt"), AUTHENTICATE_STORE_USER("examples/authentication_store_user.txt"), AUTHENTICATE_GENERATE_HASHED_PASSWORD( "examples/authentication_generateHashedPassword.txt"), AUTHENTICATE_GET_MIN_PWD_LENGTH( "examples/authentication_getMinPasswordLength.txt"), AUTHENTICATE_PASSWORD_VALIDATORS( "examples/authentication_password_validators.txt"), AUTHENTICATE_PASSWORD_VALIDITY( "examples/authentication_password_validity.txt"), AUTHENTICATE_PASSWORD_VERIFICATION( "examples/authentication_verify_password.txt"), // Example code for the i18n module I18N_SERVLET("examples/i18n_configure_servlet.txt"), I18N_INIT_LANG("examples/i18n_init_lang.txt"), I18N_ORIGINAL_XML("examples/i18n_original_xml.txt"), I18N_UPDATED_XML("examples/i18n_updated_xml.txt"), I18N_FILE_UPDATER("examples/i18n_file_updater.txt"), I18N_LOAD_TRANSLATIONS("examples/i18n_load_translations.txt"), I18N_EXAMPLE_XML("examples/i18n_example_translations.txt"), I18N_GET_MSG_TEXT_FIELD("examples/i18n_getmsg_ex1.txt"), I18N_GET_MSG_WITH_PARAM("examples/i18n_getmsg_ex2.txt"), I18N_GET_MSG_VIA_LANG("examples/i18n_getmsg_ex3.txt"), I18N_CUSTOMER_POJO("examples/i18n_customer_pojo.txt"), I18N_CUSTOMER_POJO_TRANSLATIONS( "examples/i18n_customer_pojo_translations.txt"), I18N_FORM("examples/i18n_form.txt"), ; private final String fileName; private Examples(String fileName) { this.fileName = fileName; } public String getFileName() { return fileName; } } public static String getExample(Examples example) { URL url = ExampleLoader.class.getClassLoader().getResource( example.getFileName()); StringBuffer fileData = new StringBuffer(1000); try { BufferedReader reader = new BufferedReader(new FileReader(url .getPath())); char[] buf = new char[1024]; int numRead = 0; while ((numRead = reader.read(buf)) != -1) { String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); buf = new char[1024]; } reader.close(); return fileData.toString(); } catch (FileNotFoundException e) { return ""; } catch (IOException e) { return ""; } } }
Java
package org.vaadin.appfoundation.example.authorization; import org.vaadin.appfoundation.example.Page; public class Roles extends Page { private static final long serialVersionUID = -5911537891534815351L; public Roles() { super("roles text"); } }
Java
package org.vaadin.appfoundation.example.authorization; import org.vaadin.appfoundation.example.Page; public class PermissionManagers extends Page { private static final long serialVersionUID = -6274302806342638976L; public PermissionManagers() { super("permission managers text"); } }
Java
package org.vaadin.appfoundation.example.authorization; import org.vaadin.appfoundation.example.Page; public class RemovingPermissions extends Page { private static final long serialVersionUID = -8791692860237872670L; public RemovingPermissions() { super("removing permissions text"); } }
Java
package org.vaadin.appfoundation.example.authorization; import org.vaadin.appfoundation.example.Page; public class GrantingAccess extends Page { private static final long serialVersionUID = -3105399359073542039L; public GrantingAccess() { super("granting access text"); } }
Java
package org.vaadin.appfoundation.example.authorization; import org.vaadin.appfoundation.example.Page; public class MemPm extends Page { private static final long serialVersionUID = -8804477345384416181L; public MemPm() { super("mempm text"); } }
Java
package org.vaadin.appfoundation.example.authorization; import org.vaadin.appfoundation.example.Page; public class Resources extends Page { private static final long serialVersionUID = -3718212835159660181L; public Resources() { super("resources text"); } }
Java
package org.vaadin.appfoundation.example.authorization; import org.vaadin.appfoundation.example.Page; public class InitAuthorization extends Page { private static final long serialVersionUID = -7484360026836952388L; public InitAuthorization() { super("init authorization text"); } }
Java
package org.vaadin.appfoundation.example.authorization; import org.vaadin.appfoundation.example.Page; public class CheckingAccessRights extends Page { private static final long serialVersionUID = 4485783747750332903L; public CheckingAccessRights() { super("checking for access rights"); } }
Java
package org.vaadin.appfoundation.example.authorization; import org.vaadin.appfoundation.example.Page; public class AuthorizationIntro extends Page { private static final long serialVersionUID = 5662292822937928175L; public AuthorizationIntro() { super("intro to authorization text"); } }
Java
package org.vaadin.appfoundation.example.authorization; import org.vaadin.appfoundation.example.Page; public class DenyingAccess extends Page { private static final long serialVersionUID = 7082724989547758176L; public DenyingAccess() { super("denying access text"); } }
Java
package org.vaadin.appfoundation.example.authorization; import org.vaadin.appfoundation.example.Page; public class JPAPm extends Page { private static final long serialVersionUID = 5337991003614823677L; public JPAPm() { super("jpapm text"); } }
Java
package org.vaadin.appfoundation.example.view; import org.vaadin.appfoundation.example.Page; public class Views extends Page { private static final long serialVersionUID = -7650506914228979289L; public Views() { super("views text"); } }
Java
package org.vaadin.appfoundation.example.view; import org.vaadin.appfoundation.example.Page; public class ViewEvents extends Page { private static final long serialVersionUID = 8056163603161932812L; public ViewEvents() { super("view events text"); } }
Java
package org.vaadin.appfoundation.example.view; import org.vaadin.appfoundation.example.Page; public class ConfiguringView extends Page { private static final long serialVersionUID = 1602593248018609427L; public ConfiguringView() { super("configuring view module text"); } }
Java
package org.vaadin.appfoundation.example.view; import org.vaadin.appfoundation.example.Page; public class ViewHandlerExample extends Page { private static final long serialVersionUID = 3391814647955929447L; public ViewHandlerExample() { super("view handler example text"); } }
Java
package org.vaadin.appfoundation.example.view; import org.vaadin.appfoundation.example.Page; public class ViewFactories extends Page { private static final long serialVersionUID = -935187288659828886L; public ViewFactories() { super("view factories text"); } }
Java
package org.vaadin.appfoundation.example.view; import org.vaadin.appfoundation.example.Page; public class ViewIntro extends Page { private static final long serialVersionUID = -4225762553285921918L; public ViewIntro() { super("view module intro text"); } }
Java
package org.vaadin.appfoundation.example.view; import org.vaadin.appfoundation.example.Page; public class ViewContainerExample extends Page { private static final long serialVersionUID = -4180097923322032070L; public ViewContainerExample() { super("view container text"); } }
Java
package org.vaadin.appfoundation.example.authentication; import org.vaadin.appfoundation.example.ExampleLoader.Examples; import org.vaadin.appfoundation.example.components.CodeExample; import org.vaadin.appfoundation.i18n.Lang; import org.vaadin.appfoundation.view.AbstractView; import ys.wikiparser.WikiParser; import com.vaadin.ui.Label; import com.vaadin.ui.VerticalLayout; public class ConfiguringAuth extends AbstractView<VerticalLayout> { private static final long serialVersionUID = -3149135945432852122L; public ConfiguringAuth() { super(new VerticalLayout()); getContent().addComponent( new Label(WikiParser.renderXHTML(Lang .getMessage("configuring auth text")), Label.CONTENT_XHTML)); CodeExample contextListenerExample = new CodeExample( Examples.AUTHENTICATE_CONTEXT_LISTENER); contextListenerExample.setWidth("100%"); contextListenerExample.setDefaultCaption(Lang .getMessage("example for auth context listener")); getContent().addComponent(contextListenerExample); CodeExample initAuthModuleExample = new CodeExample( Examples.AUTHENTICATE_INIT_MODULE); initAuthModuleExample.setWidth("100%"); initAuthModuleExample.setDefaultCaption(Lang .getMessage("auth module init example")); getContent().addComponent(initAuthModuleExample); } @Override public void activated(Object... params) { // TODO Auto-generated method stub } @Override public void deactivated(Object... params) { // TODO Auto-generated method stub } }
Java
package org.vaadin.appfoundation.example.authentication; import javax.persistence.OptimisticLockException; import org.vaadin.appfoundation.authentication.LogoutEvent; import org.vaadin.appfoundation.authentication.LogoutListener; import org.vaadin.appfoundation.authentication.SessionHandler; import org.vaadin.appfoundation.authentication.data.User; import org.vaadin.appfoundation.authentication.exceptions.InvalidCredentialsException; import org.vaadin.appfoundation.authentication.exceptions.PasswordRequirementException; import org.vaadin.appfoundation.authentication.exceptions.PasswordsDoNotMatchException; import org.vaadin.appfoundation.authentication.exceptions.TooShortPasswordException; import org.vaadin.appfoundation.authentication.util.PasswordUtil; import org.vaadin.appfoundation.authentication.util.UserUtil; import org.vaadin.appfoundation.example.Page; import org.vaadin.appfoundation.example.ExampleLoader.Examples; import org.vaadin.appfoundation.persistence.facade.FacadeFactory; import com.vaadin.ui.Button; import com.vaadin.ui.FormLayout; import com.vaadin.ui.Label; import com.vaadin.ui.Layout; import com.vaadin.ui.Panel; import com.vaadin.ui.TextField; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Button.ClickListener; public class ChangePassword extends Page { private static final long serialVersionUID = 5204650511382347253L; private User currentUser; private Panel examplePanel = new Panel(); public ChangePassword() { super("change user password"); getContent().addComponent(examplePanel); addCodeExample(Examples.AUTHENTICATE_CHANGE_PASSWORD, "show code"); } private Layout buildPwdChangeForm() { FormLayout layout = new FormLayout(); // Create a label which we can use to give feedback to the user final Label feedbackLabel = new Label(); final Label logoutLabel = new Label(); SessionHandler.addListener(new LogoutListener() { @Override public void logout(LogoutEvent event) { logoutLabel .setValue("You entered the password incorrectly too many " + "times, so you would have now been logged out"); SessionHandler.setUser(event.getUser()); event.getUser().clearFailedPasswordChangeAttempts(); } }); // Create input fields for passwords final TextField currentPassword = new TextField("Current password"); currentPassword.setSecret(true); currentPassword.setNullRepresentation(""); final TextField newPassword = new TextField("New password"); newPassword.setSecret(true); newPassword.setNullRepresentation(""); final TextField newPasswordVerified = new TextField( "Verify new password"); newPasswordVerified.setSecret(true); newPasswordVerified.setNullRepresentation(""); // Add the save button Button saveBtn = new Button("Save", new ClickListener() { private static final long serialVersionUID = -5577423546946890721L; public void buttonClick(ClickEvent event) { logoutLabel.setValue(null); // Try to change the password when the button is clicked String password = (String) currentPassword.getValue(); String newPasswordStr = (String) newPassword.getValue(); String newPasswordStr2 = (String) newPasswordVerified .getValue(); try { UserUtil.changePassword(SessionHandler.get(), password, newPasswordStr, newPasswordStr2); } catch (InvalidCredentialsException e) { feedbackLabel.setValue("Current password was invalid!"); clearPwdFields(); return; } catch (TooShortPasswordException e) { feedbackLabel .setValue("New password was too short, the password " + "needs to be at least " + PasswordUtil.getMinPasswordLength() + " characters long."); clearPwdFields(); return; } catch (PasswordsDoNotMatchException e) { feedbackLabel .setValue("Password verification was incorrect"); clearPwdFields(); return; } catch (PasswordRequirementException e) { feedbackLabel .setValue("Password did not meet set requirements"); clearPwdFields(); return; } catch (OptimisticLockException e) { // IGNORE only in this example, because we don't care that // the password wasn't actually stored. } feedbackLabel.setValue("Password changed!"); clearPwdFields(); } private void clearPwdFields() { currentPassword.setValue(null); newPassword.setValue(null); newPasswordVerified.setValue(null); } }); layout.addComponent(logoutLabel); layout.addComponent(feedbackLabel); layout.addComponent(currentPassword); layout.addComponent(newPassword); layout.addComponent(newPasswordVerified); layout.addComponent(saveBtn); return layout; } @Override public void activated(Object... params) { currentUser = FacadeFactory.getFacade().find(User.class, 2L); currentUser.setPassword(PasswordUtil.generateHashedPassword("demo123")); examplePanel.removeAllComponents(); examplePanel.addComponent(buildPwdChangeForm()); SessionHandler.setUser(currentUser); } @Override public void deactivated(Object... params) { // TODO Auto-generated method stub } }
Java
package org.vaadin.appfoundation.example.authentication; import org.vaadin.appfoundation.example.ExampleLoader.Examples; import org.vaadin.appfoundation.example.components.CodeExample; import org.vaadin.appfoundation.i18n.Lang; import org.vaadin.appfoundation.view.AbstractView; import ys.wikiparser.WikiParser; import com.vaadin.ui.Label; import com.vaadin.ui.VerticalLayout; public class LogoutExample extends AbstractView<VerticalLayout> { private static final long serialVersionUID = 3319859864849238330L; public LogoutExample() { super(new VerticalLayout()); getContent() .addComponent( new Label(WikiParser.renderXHTML(Lang .getMessage("logging out a user")), Label.CONTENT_XHTML)); CodeExample logoutButtonExample = new CodeExample( Examples.AUTHENTICATE_LOGOUT_BUTTON); logoutButtonExample.setWidth("100%"); logoutButtonExample .setDefaultCaption(Lang.getMessage("logout example")); getContent().addComponent(logoutButtonExample); CodeExample logoutEventExample = new CodeExample( Examples.AUTHENTICATE_LOGOUT_LISTENER); logoutEventExample.setWidth("100%"); logoutEventExample.setDefaultCaption(Lang .getMessage("logout event example")); getContent().addComponent(logoutEventExample); } @Override public void activated(Object... params) { // TODO Auto-generated method stub } @Override public void deactivated(Object... params) { // TODO Auto-generated method stub } }
Java
package org.vaadin.appfoundation.example.authentication; import org.vaadin.appfoundation.authentication.SessionHandler; import org.vaadin.appfoundation.authentication.data.User; import org.vaadin.appfoundation.authentication.exceptions.AccountLockedException; import org.vaadin.appfoundation.authentication.exceptions.InvalidCredentialsException; import org.vaadin.appfoundation.authentication.util.AuthenticationUtil; import org.vaadin.appfoundation.example.ExampleLoader.Examples; import org.vaadin.appfoundation.example.components.CodeExample; import org.vaadin.appfoundation.i18n.Lang; import org.vaadin.appfoundation.persistence.facade.FacadeFactory; import org.vaadin.appfoundation.view.AbstractView; import ys.wikiparser.WikiParser; import com.vaadin.ui.Button; import com.vaadin.ui.FormLayout; import com.vaadin.ui.Label; import com.vaadin.ui.Layout; import com.vaadin.ui.Panel; import com.vaadin.ui.TextField; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Button.ClickListener; public class UserAuth extends AbstractView<VerticalLayout> { private static final long serialVersionUID = 3319859864849238330L; private Panel examplePanel; public UserAuth() { super(new VerticalLayout()); getContent().addComponent( new Label(WikiParser.renderXHTML(Lang .getMessage("text for auth a user")), Label.CONTENT_XHTML)); CodeExample example = new CodeExample(Examples.AUTHENTICATE_USER); example.setWidth("100%"); initExamplePanel(); getContent().addComponent(examplePanel); getContent().addComponent(example); } private void initExamplePanel() { examplePanel = new Panel(); } private Layout buildLoginForm() { FormLayout layout = new FormLayout(); // Create a label which we can use to give feedback to the user final Label feedbackLabel = new Label(); // Create input fields for username and password final TextField usernameField = new TextField("Username"); final TextField passwordField = new TextField("Password"); passwordField.setSecret(true); // Add the login button Button login = new Button("Login", new ClickListener() { private static final long serialVersionUID = -5577423546946890721L; public void buttonClick(ClickEvent event) { // Try to log in the user when the button is clicked String username = (String) usernameField.getValue(); String password = (String) passwordField.getValue(); try { loggedInAs(AuthenticationUtil.authenticate(username, password)); } catch (InvalidCredentialsException e) { feedbackLabel .setValue("Either username or password was wrong"); } catch (AccountLockedException e) { feedbackLabel.setValue("The given account has been locked"); } } }); layout.addComponent(feedbackLabel); layout.addComponent(usernameField); layout.addComponent(passwordField); layout.addComponent(login); return layout; } @Override public void activated(Object... params) { User user = FacadeFactory.getFacade().find(User.class, 1L); if (user.isAccountLocked()) { user.setAccountLocked(false); } refreshExamplePanel(); } @Override public void deactivated(Object... params) { // TODO Auto-generated method stub } private void loggedInAs(User user) { VerticalLayout layout = new VerticalLayout(); layout.addComponent(new Label("You are now logged in as the user " + user.getUsername())); layout.addComponent(new Button("Click here to log out", new ClickListener() { private static final long serialVersionUID = 4067453946827830672L; @Override public void buttonClick(ClickEvent event) { SessionHandler.logout(); refreshExamplePanel(); } })); examplePanel.removeAllComponents(); examplePanel.addComponent(layout); } private void refreshExamplePanel() { examplePanel.removeAllComponents(); examplePanel.addComponent(buildLoginForm()); } }
Java
package org.vaadin.appfoundation.example.authentication; import org.vaadin.appfoundation.i18n.Lang; import org.vaadin.appfoundation.view.AbstractView; import ys.wikiparser.WikiParser; import com.vaadin.ui.Label; import com.vaadin.ui.VerticalLayout; public class AuthIntro extends AbstractView<VerticalLayout> { private static final long serialVersionUID = 3319859864849238330L; public AuthIntro() { super(new VerticalLayout()); getContent().addComponent( new Label(WikiParser.renderXHTML(Lang .getMessage("intro text to auth module")), Label.CONTENT_XHTML)); } @Override public void activated(Object... params) { // TODO Auto-generated method stub } @Override public void deactivated(Object... params) { // TODO Auto-generated method stub } }
Java
package org.vaadin.appfoundation.example.authentication; import org.vaadin.appfoundation.example.ExampleLoader.Examples; import org.vaadin.appfoundation.example.components.CodeExample; import org.vaadin.appfoundation.i18n.Lang; import org.vaadin.appfoundation.view.AbstractView; import ys.wikiparser.WikiParser; import com.vaadin.ui.Label; import com.vaadin.ui.VerticalLayout; public class GettingUserInstance extends AbstractView<VerticalLayout> { private static final long serialVersionUID = 3319859864849238330L; public GettingUserInstance() { super(new VerticalLayout()); getContent().addComponent( new Label(WikiParser.renderXHTML(Lang .getMessage("getting user instance")), Label.CONTENT_XHTML)); CodeExample getUserInstanceExample = new CodeExample( Examples.AUTHENTICATE_GET_USER_INSTANCE); getUserInstanceExample.setWidth("100%"); getContent().addComponent(getUserInstanceExample); } @Override public void activated(Object... params) { // TODO Auto-generated method stub } @Override public void deactivated(Object... params) { // TODO Auto-generated method stub } }
Java
package org.vaadin.appfoundation.example.authentication; import org.vaadin.appfoundation.example.Page; import org.vaadin.appfoundation.example.ExampleLoader.Examples; public class StoreUser extends Page { private static final long serialVersionUID = 1531144454612314170L; public StoreUser() { super("storing a user object"); addCodeExample(Examples.AUTHENTICATE_STORE_USER, "show code"); } }
Java
package org.vaadin.appfoundation.example.authentication; import org.vaadin.appfoundation.authentication.util.PasswordUtil; import org.vaadin.appfoundation.example.Page; import org.vaadin.appfoundation.example.ExampleLoader.Examples; import com.vaadin.data.Validator; import com.vaadin.data.Property.ValueChangeEvent; import com.vaadin.data.Property.ValueChangeListener; import com.vaadin.data.Validator.InvalidValueException; import com.vaadin.ui.TextField; public class PasswordUtilityMethods extends Page { private static final long serialVersionUID = 3319859864849238330L; public PasswordUtilityMethods() { super("password utility methods"); addWikiText("generateHashedPassword"); addCodeExample(Examples.AUTHENTICATE_GENERATE_HASHED_PASSWORD, "show code"); addWikiText("getMinPasswordLength"); addCodeExample(Examples.AUTHENTICATE_GET_MIN_PWD_LENGTH, "show code"); addWikiText("password validators"); getContent().addComponent(buildPasswordTextField()); addCodeExample(Examples.AUTHENTICATE_PASSWORD_VALIDATORS, "show code"); addWikiText("password validity"); addCodeExample(Examples.AUTHENTICATE_PASSWORD_VALIDITY, "show code"); addWikiText("password verification"); addCodeExample(Examples.AUTHENTICATE_PASSWORD_VERIFICATION, "show code"); } private TextField buildPasswordTextField() { final TextField password = new TextField("Password"); password.setSecret(true); password.setNullRepresentation(""); for (Validator validator : PasswordUtil.getValidators()) { password.addValidator(validator); } // Set the password field to immediate password.setImmediate(true); // Validate the password right after it has been changed password.addListener(new ValueChangeListener() { private static final long serialVersionUID = 1666908198186227437L; @Override public void valueChange(ValueChangeEvent event) { try { password.validate(); } catch (InvalidValueException e) { // IGNORE } } }); return password; } }
Java
package org.vaadin.appfoundation.example.authentication; import org.vaadin.appfoundation.authentication.data.User; import org.vaadin.appfoundation.authentication.exceptions.PasswordRequirementException; import org.vaadin.appfoundation.authentication.exceptions.PasswordsDoNotMatchException; import org.vaadin.appfoundation.authentication.exceptions.TooShortPasswordException; import org.vaadin.appfoundation.authentication.exceptions.TooShortUsernameException; import org.vaadin.appfoundation.authentication.exceptions.UsernameExistsException; import org.vaadin.appfoundation.authentication.util.UserUtil; import org.vaadin.appfoundation.example.Page; import org.vaadin.appfoundation.example.ExampleLoader.Examples; import org.vaadin.appfoundation.persistence.facade.FacadeFactory; import com.vaadin.ui.Button; import com.vaadin.ui.FormLayout; import com.vaadin.ui.Label; import com.vaadin.ui.Layout; import com.vaadin.ui.Panel; import com.vaadin.ui.TextField; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.Window.Notification; public class RegisterUser extends Page { private static final long serialVersionUID = 3319859864849238330L; private Panel examplePanel = new Panel(); public RegisterUser() { super("registering a user"); getContent().addComponent(examplePanel); addCodeExample(Examples.AUTHENTICATE_REGISTER_USER, "show code"); } private Layout buildRegisterForm() { FormLayout layout = new FormLayout(); final Label feedbackLabel = new Label(); layout.addComponent(feedbackLabel); final TextField username = new TextField("Username"); username.setNullRepresentation(""); layout.addComponent(username); final TextField password = new TextField("Password"); password.setNullRepresentation(""); password.setSecret(true); layout.addComponent(password); final TextField verifyPassword = new TextField("Verify password"); verifyPassword.setNullRepresentation(""); verifyPassword.setSecret(true); layout.addComponent(verifyPassword); final TextField realName = new TextField("Real name"); realName.setNullRepresentation(""); layout.addComponent(realName); final TextField email = new TextField("Email address"); email.setNullRepresentation(""); layout.addComponent(email); Button registerButton = new Button("Register", new ClickListener() { private static final long serialVersionUID = 9048069425045731789L; @Override public void buttonClick(ClickEvent event) { try { User user = UserUtil.registerUser((String) username .getValue(), (String) password.getValue(), (String) verifyPassword.getValue()); // user successfully registered user.setName((String) realName.getValue()); user.setEmail((String) email.getValue()); // The user pojo needs to be stored as we've added the name // and email address as additional information FacadeFactory.getFacade().store(user); getApplication().getMainWindow().showNotification( "User registered", Notification.TYPE_HUMANIZED_MESSAGE); examplePanel.removeAllComponents(); examplePanel.addComponent(buildRegisterForm()); } catch (TooShortPasswordException e) { feedbackLabel .setValue("Password is too short, it needs to be at least " + UserUtil.getMinPasswordLength() + " characters long"); } catch (TooShortUsernameException e) { feedbackLabel .setValue("Username is too short, it needs to be at least " + UserUtil.getMinUsernameLength() + " characters long"); } catch (PasswordsDoNotMatchException e) { feedbackLabel.setValue("Password verification has failed"); } catch (UsernameExistsException e) { feedbackLabel .setValue("The chosen username already exists, please pick another one"); } catch (PasswordRequirementException e) { feedbackLabel .setValue("Password does not meet the set requirements"); } password.setValue(null); verifyPassword.setValue(null); } }); layout.addComponent(registerButton); return layout; } @Override public void activated(Object... params) { examplePanel.removeAllComponents(); examplePanel.addComponent(buildRegisterForm()); } }
Java
package org.vaadin.appfoundation.example.authentication; import org.vaadin.appfoundation.example.Page; import org.vaadin.appfoundation.example.ExampleLoader.Examples; public class FetchUser extends Page { private static final long serialVersionUID = 3336970179429259887L; public FetchUser() { super("fetching a user object"); addCodeExample(Examples.AUTHENTICATE_FETCH_USER, "show code"); } }
Java
package org.vaadin.appfoundation.example.components; import org.vaadin.appfoundation.example.ExampleLoader; import org.vaadin.appfoundation.example.ExampleLoader.Examples; import org.vaadin.appfoundation.i18n.Lang; import org.vaadin.codelabel.CodeLabel; import org.vaadin.henrik.drawer.Drawer; public class CodeExample extends Drawer { private static final long serialVersionUID = 981189256494004603L; public CodeExample(Examples example) { super(Lang.getMessage("show code"), null); CodeLabel codeExample = new CodeLabel(); codeExample.setValue(ExampleLoader.getExample(example)); setDrawerComponent(codeExample); } }
Java
package org.vaadin.appfoundation.example.components; import org.vaadin.appfoundation.view.AbstractView; import org.vaadin.appfoundation.view.View; import org.vaadin.appfoundation.view.ViewContainer; import org.vaadin.appfoundation.view.ViewHandler; import com.vaadin.ui.Component; import com.vaadin.ui.Panel; public class MainArea extends AbstractView<Panel> implements ViewContainer { private static final long serialVersionUID = 9010669373711637452L; private View currentView; public MainArea() { super(new Panel()); getContent().setSizeFull(); getContent().addComponent(ViewHandler.getUriFragmentUtil()); } /** * {@inheritDoc} */ @Override public void activated(Object... params) { // Do nothing } /** * {@inheritDoc} */ @Override public void deactivated(Object... params) { // Do nothing } /** * {@inheritDoc} */ public void activate(View view) { if (currentView == null) { getContent().addComponent((Component) view); } else { getContent().replaceComponent((Component) currentView, (Component) view); } currentView = view; } /** * {@inheritDoc} */ public void deactivate(View view) { if (currentView != null) { getContent().removeComponent((Component) view); } currentView = null; } }
Java
package org.vaadin.appfoundation.example; import java.util.Locale; import org.vaadin.appfoundation.authentication.SessionHandler; import org.vaadin.appfoundation.i18n.Lang; import org.vaadin.appfoundation.view.ViewHandler; import com.vaadin.Application; import com.vaadin.ui.Window; public class DemoApplication extends Application { private static final long serialVersionUID = 1L; private Window mainWindow; @Override public void init() { Lang.initialize(this); Lang.setLocale(Locale.ENGLISH); ViewHandler.initialize(this); SessionHandler.initialize(this); ExampleData.initialize(this); mainWindow = new MainWindow(); mainWindow.setSizeFull(); setMainWindow(mainWindow); } }
Java
package org.vaadin.appfoundation.example.persistence; import org.vaadin.appfoundation.example.Page; public class RemovingData extends Page { private static final long serialVersionUID = 2858026847696773764L; public RemovingData() { super("removing data text"); } }
Java
package org.vaadin.appfoundation.example.persistence; import org.vaadin.appfoundation.example.Page; public class StoringData extends Page { private static final long serialVersionUID = -4227203122303296952L; public StoringData() { super("storing data text"); } }
Java
package org.vaadin.appfoundation.example.persistence; import org.vaadin.appfoundation.example.Page; public class CreatingPojos extends Page { private static final long serialVersionUID = -8065190889615168139L; public CreatingPojos() { super("creating pojos text"); } }
Java
package org.vaadin.appfoundation.example.persistence; import org.vaadin.appfoundation.example.Page; public class ConfiguringPersistence extends Page { private static final long serialVersionUID = 8584529931203561701L; public ConfiguringPersistence() { super("configuring persistence module text"); } }
Java
package org.vaadin.appfoundation.example.persistence; import org.vaadin.appfoundation.example.Page; public class FacadeFactoryExamples extends Page { private static final long serialVersionUID = 2091504573134600933L; public FacadeFactoryExamples() { super("facade factory exmaple text"); } }
Java
package org.vaadin.appfoundation.example.persistence; import org.vaadin.appfoundation.example.Page; public class FetchingData extends Page { private static final long serialVersionUID = -8312944787394716728L; public FetchingData() { super("fetching data text"); } }
Java
package org.vaadin.appfoundation.example.persistence; import org.vaadin.appfoundation.example.Page; public class PersistenceIntro extends Page { private static final long serialVersionUID = -247122143360422499L; public PersistenceIntro() { super("persistence module intro text"); } }
Java
package org.vaadin.appfoundation.example; import java.util.HashMap; import java.util.Map; import org.vaadin.appfoundation.example.authentication.AuthIntro; import org.vaadin.appfoundation.example.authentication.ChangePassword; import org.vaadin.appfoundation.example.authentication.ConfiguringAuth; import org.vaadin.appfoundation.example.authentication.FetchUser; import org.vaadin.appfoundation.example.authentication.GettingUserInstance; import org.vaadin.appfoundation.example.authentication.LogoutExample; import org.vaadin.appfoundation.example.authentication.PasswordUtilityMethods; import org.vaadin.appfoundation.example.authentication.RegisterUser; import org.vaadin.appfoundation.example.authentication.StoreUser; import org.vaadin.appfoundation.example.authentication.UserAuth; import org.vaadin.appfoundation.example.authorization.AuthorizationIntro; import org.vaadin.appfoundation.example.authorization.CheckingAccessRights; import org.vaadin.appfoundation.example.authorization.DenyingAccess; import org.vaadin.appfoundation.example.authorization.GrantingAccess; import org.vaadin.appfoundation.example.authorization.InitAuthorization; import org.vaadin.appfoundation.example.authorization.JPAPm; import org.vaadin.appfoundation.example.authorization.MemPm; import org.vaadin.appfoundation.example.authorization.PermissionManagers; import org.vaadin.appfoundation.example.authorization.RemovingPermissions; import org.vaadin.appfoundation.example.authorization.Resources; import org.vaadin.appfoundation.example.authorization.Roles; import org.vaadin.appfoundation.example.components.MainArea; import org.vaadin.appfoundation.example.i18n.ConfigureAndIniI18n; import org.vaadin.appfoundation.example.i18n.FieldTranslations; import org.vaadin.appfoundation.example.i18n.GettingMessages; import org.vaadin.appfoundation.example.i18n.I18nIntro; import org.vaadin.appfoundation.example.i18n.TranslationsFile; import org.vaadin.appfoundation.example.i18n.UpdatingTranslationsFile; import org.vaadin.appfoundation.example.persistence.ConfiguringPersistence; import org.vaadin.appfoundation.example.persistence.CreatingPojos; import org.vaadin.appfoundation.example.persistence.FacadeFactoryExamples; import org.vaadin.appfoundation.example.persistence.FetchingData; import org.vaadin.appfoundation.example.persistence.PersistenceIntro; import org.vaadin.appfoundation.example.persistence.RemovingData; import org.vaadin.appfoundation.example.persistence.StoringData; import org.vaadin.appfoundation.example.view.ConfiguringView; import org.vaadin.appfoundation.example.view.ViewContainerExample; import org.vaadin.appfoundation.example.view.ViewEvents; import org.vaadin.appfoundation.example.view.ViewFactories; import org.vaadin.appfoundation.example.view.ViewHandlerExample; import org.vaadin.appfoundation.example.view.ViewIntro; import org.vaadin.appfoundation.example.view.Views; import org.vaadin.appfoundation.i18n.Lang; import org.vaadin.appfoundation.view.View; import org.vaadin.appfoundation.view.ViewContainer; import org.vaadin.appfoundation.view.ViewHandler; import com.vaadin.data.Item; import com.vaadin.data.Property.ValueChangeEvent; import com.vaadin.data.Property.ValueChangeListener; import com.vaadin.ui.Accordion; import com.vaadin.ui.SplitPanel; import com.vaadin.ui.Tree; import com.vaadin.ui.Window; import com.vaadin.ui.TabSheet.Tab; public class MainWindow extends Window implements ViewContainer, ValueChangeListener { private static final long serialVersionUID = -7336305153060921847L; private SplitPanel splitPanel; private MainArea mainArea; private Accordion menu; private Tree authModuleTree; private Tree authorizationModuleTree; private Tree i18nModuleTree; private Tree persistenceModuleTree; private Tree viewModuleTree; private Map<Object, Tree> viewToTree = new HashMap<Object, Tree>(); public MainWindow() { setCaption(Lang.getMessage("application foundation")); buildMainLayout(); buildAuthenticationModule(); buildAuthorizationModule(); buildI18nModule(); buildPersistenceModule(); buildViewModule(); ViewHandler.addView(MainView.class, this); ViewHandler.activateView(MainView.class); } private void buildMainLayout() { splitPanel = new SplitPanel(); menu = new Accordion(); mainArea = new MainArea(); splitPanel.addComponent(menu); splitPanel.addComponent(mainArea); splitPanel.setOrientation(SplitPanel.ORIENTATION_HORIZONTAL); splitPanel.setSizeFull(); splitPanel.setSplitPosition(250, SplitPanel.UNITS_PIXELS); setContent(splitPanel); } private void buildAuthenticationModule() { initAuthTree(); addAuthViews(); Tab tab = menu.addTab(authModuleTree); tab.setCaption(Lang.getMessage("auth module")); } private void buildAuthorizationModule() { initAuthorizationTree(); addAuthorizationViews(); Tab tab = menu.addTab(authorizationModuleTree); tab.setCaption(Lang.getMessage("authorization")); } private void buildI18nModule() { initI18nTree(); addI18nViews(); Tab tab = menu.addTab(i18nModuleTree); tab.setCaption(Lang.getMessage("i18n")); } private void buildPersistenceModule() { initPersistenceTree(); addPersistenceViews(); Tab tab = menu.addTab(persistenceModuleTree); tab.setCaption(Lang.getMessage("persistence")); } private void buildViewModule() { initViewTree(); addViewViews(); Tab tab = menu.addTab(viewModuleTree); tab.setCaption(Lang.getMessage("view module")); } private void initAuthTree() { authModuleTree = new Tree(); prepareTree(authModuleTree); } private void initAuthorizationTree() { authorizationModuleTree = new Tree(); prepareTree(authorizationModuleTree); } private void initI18nTree() { i18nModuleTree = new Tree(); prepareTree(i18nModuleTree); } private void initPersistenceTree() { persistenceModuleTree = new Tree(); prepareTree(persistenceModuleTree); } private void initViewTree() { viewModuleTree = new Tree(); prepareTree(viewModuleTree); } private void prepareTree(Tree tree) { tree.addContainerProperty("name", String.class, null); tree.setItemCaptionPropertyId("name"); tree.addListener(this); tree.setImmediate(true); } private void addAuthViews() { addViewToModule(authModuleTree, AuthIntro.class, "auth intro", "auth-intro"); addViewToModule(authModuleTree, ConfiguringAuth.class, "configuring auth", "auth-config"); addViewToModule(authModuleTree, UserAuth.class, "auth a user", "auth-authenticate"); addViewToModule(authModuleTree, GettingUserInstance.class, "getting user instance caption", "get-user-instance"); addViewToModule(authModuleTree, LogoutExample.class, "logging out a user caption", "logout"); addViewToModule(authModuleTree, ChangePassword.class, "change password", "change-password"); addViewToModule(authModuleTree, RegisterUser.class, "register user", "register-user"); addViewToModule(authModuleTree, FetchUser.class, "fetching users", "fetch-user"); addViewToModule(authModuleTree, StoreUser.class, "storing users", "store-user"); addViewToModule(authModuleTree, PasswordUtilityMethods.class, "password util", "password-util"); } private void addAuthorizationViews() { addViewToModule(authorizationModuleTree, AuthorizationIntro.class, "intro to authorization", "authorization-intro"); addViewToModule(authorizationModuleTree, Resources.class, "resources", "resources"); addViewToModule(authorizationModuleTree, Roles.class, "roles", "roles"); addViewToModule(authorizationModuleTree, PermissionManagers.class, "permission managers", "permission-managers"); addViewToModule(authorizationModuleTree, JPAPm.class, "jpapm", "jpa-permission-managers"); addViewToModule(authorizationModuleTree, MemPm.class, "mempm", "mem-permission-managers"); addViewToModule(authorizationModuleTree, InitAuthorization.class, "init authorization", "init-authorization"); addViewToModule(authorizationModuleTree, GrantingAccess.class, "granting access", "granting-access"); addViewToModule(authorizationModuleTree, DenyingAccess.class, "denying access", "denying-access"); addViewToModule(authorizationModuleTree, CheckingAccessRights.class, "checking for access rights", "checking-access"); addViewToModule(authorizationModuleTree, RemovingPermissions.class, "removing permissions", "removing-permissions"); } private void addI18nViews() { addViewToModule(i18nModuleTree, I18nIntro.class, "i18n intro", "i18n-intro"); addViewToModule(i18nModuleTree, TranslationsFile.class, "translations file", "translations"); addViewToModule(i18nModuleTree, UpdatingTranslationsFile.class, "updating translations file", "updating-translations"); addViewToModule(i18nModuleTree, ConfigureAndIniI18n.class, "configure i18n", "i18n-config"); addViewToModule(i18nModuleTree, GettingMessages.class, "getting messages", "getmsg"); addViewToModule(i18nModuleTree, FieldTranslations.class, "field translations", "i18n-forms"); } private void addPersistenceViews() { addViewToModule(persistenceModuleTree, PersistenceIntro.class, "persistence module intro", "persistence-intro"); addViewToModule(persistenceModuleTree, ConfiguringPersistence.class, "configuring persistence module", "persistence-config"); addViewToModule(persistenceModuleTree, FacadeFactoryExamples.class, "facade factory exmaple", "facadefactory"); addViewToModule(persistenceModuleTree, CreatingPojos.class, "creating pojos", "creating-pojos"); addViewToModule(persistenceModuleTree, FetchingData.class, "fetching data", "fetching-data"); addViewToModule(persistenceModuleTree, StoringData.class, "storing data", "storing-data"); addViewToModule(persistenceModuleTree, RemovingData.class, "removing data", "removing-data"); } private void addViewViews() { addViewToModule(viewModuleTree, ViewIntro.class, "view module intro", "view-intro"); addViewToModule(viewModuleTree, ConfiguringView.class, "configuring view module", "view-config"); addViewToModule(viewModuleTree, Views.class, "views", "views"); addViewToModule(viewModuleTree, ViewContainerExample.class, "view container", "view-container"); addViewToModule(viewModuleTree, ViewEvents.class, "view events", "view-events"); addViewToModule(viewModuleTree, ViewHandlerExample.class, "view handler example", "viewhandler"); addViewToModule(viewModuleTree, ViewFactories.class, "view factories", "viewfactories"); } private void addViewToModule(Tree tree, Class<? extends View> c, String captionTuid, String uri) { ViewHandler.addView(c, this); ViewHandler.addUri(uri, c); viewToTree.put(c, tree); Item item = tree.addItem(c); item.getItemProperty("name").setValue(Lang.getMessage(captionTuid)); } public void activate(View view) { mainArea.activate(view); Tree tree = viewToTree.get(view.getClass()); if (tree != null) { menu.setSelectedTab(tree); tree.select(view.getClass()); } } public void deactivate(View view) { mainArea.deactivate(view); } public void valueChange(ValueChangeEvent event) { if (event.getProperty().getValue() != null) { ViewHandler.activateView(event.getProperty().getValue(), true); } } }
Java
package org.vaadin.appfoundation.example.i18n; import org.vaadin.appfoundation.example.Page; import org.vaadin.appfoundation.example.ExampleLoader.Examples; public class ConfigureAndIniI18n extends Page { private static final long serialVersionUID = -2316783633541238871L; public ConfigureAndIniI18n() { super("configure i18n text"); addCodeExample(Examples.I18N_SERVLET, "show code"); addCodeExample(Examples.I18N_INIT_LANG, "show code"); } }
Java
package org.vaadin.appfoundation.example.i18n; import org.vaadin.appfoundation.example.Page; public class I18nIntro extends Page { private static final long serialVersionUID = -8458896728089293287L; public I18nIntro() { super("i18n intro text"); } }
Java
package org.vaadin.appfoundation.example.i18n.data; import org.vaadin.appfoundation.i18n.FieldTranslation; public class Customer { @FieldTranslation(tuid = "name") private String name; @FieldTranslation(tuid = "email") private String email; @FieldTranslation(tuid = "phone") private String phone; public void setName(String name) { this.name = name; } public String getName() { return name; } public void setEmail(String email) { this.email = email; } public String getEmail() { return email; } public void setPhone(String phone) { this.phone = phone; } public String getPhone() { return phone; } }
Java
package org.vaadin.appfoundation.example.i18n; import org.vaadin.appfoundation.example.Page; import org.vaadin.appfoundation.example.ExampleLoader.Examples; public class UpdatingTranslationsFile extends Page { private static final long serialVersionUID = -4620887553412342431L; public UpdatingTranslationsFile() { super("updating translations file text"); addCodeExample(Examples.I18N_ORIGINAL_XML, "update trans file code 1 caption"); addWikiText("updating translations file text2"); addCodeExample(Examples.I18N_FILE_UPDATER, "update trans file code 2 caption"); addWikiText("updating translations file text3"); addCodeExample(Examples.I18N_UPDATED_XML, "update trans file code 3 caption"); addWikiText("updating translations file text4"); addCodeExample(Examples.I18N_LOAD_TRANSLATIONS, "update trans file code 4 caption"); } }
Java
package org.vaadin.appfoundation.example.i18n; import org.vaadin.appfoundation.example.Page; public class TranslationsFile extends Page { private static final long serialVersionUID = 7919159338285917176L; public TranslationsFile() { super("translations file text"); } }
Java
package org.vaadin.appfoundation.example.i18n; import java.util.Locale; import org.vaadin.appfoundation.example.Page; import org.vaadin.appfoundation.example.ExampleLoader.Examples; import org.vaadin.appfoundation.example.i18n.data.Customer; import org.vaadin.appfoundation.i18n.I18nForm; import org.vaadin.appfoundation.i18n.Lang; import com.vaadin.data.Item; import com.vaadin.data.Property.ValueChangeEvent; import com.vaadin.data.Property.ValueChangeListener; import com.vaadin.data.util.BeanItem; import com.vaadin.ui.Panel; import com.vaadin.ui.Select; public class FieldTranslations extends Page { private static final long serialVersionUID = 2329869742045540584L; public FieldTranslations() { super("field translations text"); addCodeExample(Examples.I18N_CUSTOMER_POJO, "customer pojo"); addCodeExample(Examples.I18N_CUSTOMER_POJO_TRANSLATIONS, "customer pojo translations"); addWikiText("field translations text2"); addForm(); addCodeExample(Examples.I18N_FORM, "show code"); } private void addForm() { Panel panel = new Panel(); final Customer customer = new Customer(); customer.setName("John Doe"); customer.setPhone("+123 456 7890"); customer.setEmail("john@some.site"); final I18nForm form = new I18nForm(Customer.class); Select select = new Select(); select.addContainerProperty("name", String.class, null); select.setItemCaptionPropertyId("name"); Item item = select.addItem("en"); item.getItemProperty("name").setValue(Lang.getMessage("en language")); item = select.addItem("de"); item.getItemProperty("name").setValue(Lang.getMessage("de language")); select.setImmediate(true); select.addListener(new ValueChangeListener() { private static final long serialVersionUID = -1667702475800410396L; @Override public void valueChange(ValueChangeEvent event) { Object value = event.getProperty().getValue(); Lang.setLocale(value.equals("en") ? Locale.ENGLISH : Locale.GERMAN); BeanItem<Customer> customerItem = new BeanItem<Customer>( customer); form.setItemDataSource(customerItem); Lang.setLocale(Locale.ENGLISH); } }); select.select("en"); panel.addComponent(select); panel.addComponent(form); getContent().addComponent(panel); } }
Java
package org.vaadin.appfoundation.example.i18n; import org.vaadin.appfoundation.example.Page; import org.vaadin.appfoundation.example.ExampleLoader.Examples; public class GettingMessages extends Page { private static final long serialVersionUID = 987190244067153965L; public GettingMessages() { super("getting messages text"); addCodeExample(Examples.I18N_EXAMPLE_XML, "example translation xml"); addWikiText("getting messages text2"); addCodeExample(Examples.I18N_GET_MSG_TEXT_FIELD, "show code"); addWikiText("getting messages text3"); addCodeExample(Examples.I18N_GET_MSG_WITH_PARAM, "show code"); addWikiText("getting messages text4"); addCodeExample(Examples.I18N_GET_MSG_VIA_LANG, "show code"); } }
Java
package org.vaadin.appfoundation.example; import org.vaadin.appfoundation.example.ExampleLoader.Examples; import org.vaadin.appfoundation.example.components.CodeExample; import org.vaadin.appfoundation.i18n.Lang; import org.vaadin.appfoundation.view.AbstractView; import ys.wikiparser.WikiParser; import com.vaadin.ui.Label; import com.vaadin.ui.VerticalLayout; public abstract class Page extends AbstractView<VerticalLayout> { private static final long serialVersionUID = 7964249978981814597L; public Page(String tuid) { super(new VerticalLayout()); addWikiText(tuid); } protected void addCodeExample(Examples example, String captionTuid) { CodeExample codeExample = new CodeExample(example); codeExample.setWidth("100%"); if (captionTuid != null) { codeExample.setDefaultCaption(Lang.getMessage(captionTuid)); } getContent().addComponent(codeExample); } protected void addWikiText(String tuid) { getContent().addComponent( new Label(WikiParser.renderXHTML(Lang.getMessage(tuid)), Label.CONTENT_XHTML)); } @Override public void activated(Object... params) { // TODO Auto-generated method stub } @Override public void deactivated(Object... params) { // TODO Auto-generated method stub } }
Java
package MODELO; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Iterator; import java.util.List; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JEditorPane; public class ModeloCategoria extends Conexion{ private String codigo; private String descripcion; private String status; public ModeloCategoria() { super(); } public boolean registar(){ getConexion(); boolean sw= false; String tira="INSERT INTO Categoria (codigo, descripcion, status) VALUES(?,?,?)"; try { PreparedStatement stam = generarPreparedStatement(tira); stam.setString(1, getCodigo()); stam.setString(2, getDescripcion().toUpperCase()); stam.setString(3, getStatus()); ejecutarPrepare(stam); sw= true; } catch (SQLException ex) { Logger.getLogger(ModeloCategoria.class.getName()).log(Level.SEVERE, null, ex); } return sw; } public boolean consultar(){ getConexion(); boolean sw= false; String tira="SELECT * FROM Categoria WHERE codigo=? AND status='A'"; try { PreparedStatement stam = generarPreparedStatement(tira); stam.setString(1, getCodigo()); ResultSet rs= consultarPrepare(stam); if (rs.next()){ sw = true; setDescripcion(rs.getString("descripcion")); setCodigo(rs.getString("codigo")); setStatus(rs.getString("status")); } } catch (SQLException ex) { Logger.getLogger(ModeloCategoria.class.getName()).log(Level.SEVERE, null, ex); } return sw; } public boolean actualizar(){ getConexion(); boolean sw = false; String tira="UPDATE Categoria SET descripcion =? WHERE codigo=? AND status = 'A'"; try{ PreparedStatement stam = generarPreparedStatement(tira); stam.setString(1,getDescripcion()); stam.setString(2, getCodigo()); ejecutarPrepare(stam); sw = true; } catch (SQLException ex) { Logger.getLogger(ModeloCategoria.class.getName()).log(Level.SEVERE, null, ex); } return sw; } public Vector<ModeloCategoria> listar(){ Vector<ModeloCategoria> v = new Vector<ModeloCategoria>(); String tira="SELECT * FROM Categoria WHERE status='A'"; getConexion(); try { ResultSet rs = getConexion().createStatement().executeQuery(tira); while (rs.next()){ ModeloCategoria i = new ModeloCategoria(); i.setDescripcion(rs.getString("descripcion")); i.setCodigo(rs.getString("codigo")); i.setStatus(rs.getString("status")); v.add(i); } } catch (SQLException ex) { Logger.getLogger(ModeloCategoria.class.getName()).log(Level.SEVERE, null, ex); } return v; } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
Java
package MODELO; import java.lang.String; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; public class ModeloProducto extends Conexion{ private String codigo; private String cod_categoria; private String descripcion; private String status; private double precio; public ModeloProducto(){ super(); } public boolean registar(){ getConexion(); boolean sw = false; String tira="INSERT INTO Producto (codigo, Cod_Categoria, descripcion, precio, status ) VALUES(?,?,?,?,?)"; try { PreparedStatement stam = generarPreparedStatement(tira); stam.setString(1, getCodigo()); stam.setString(2, getCod_categoria()); stam.setString(3, getDescripcion().toLowerCase()); stam.setDouble(4, getPrecio()); stam.setString(5, getStatus()); ejecutarPrepare(stam); sw = true; } catch (SQLException ex) { Logger.getLogger(ModeloProducto.class.getName()).log(Level.SEVERE, null, ex); } return sw; } public void registarIngredientes(Vector<String> codigos,Vector<Double> cantidades){ getConexion(); for (int i = 0; i < cantidades.size(); i++){ String sql="INSERT INTO IngredienteXProducto (cod_ing, cod_pro, cantidad, status) VALUES(?,?,?,'A')"; try { PreparedStatement stam = generarPreparedStatement(sql); stam.setString(1, codigos.elementAt(i)); stam.setString(2,getCodigo()); stam.setDouble(3, cantidades.elementAt(i)); ejecutarPrepare(stam); } catch (SQLException ex) { Logger.getLogger(ModeloProducto.class.getName()).log(Level.SEVERE, null, ex); } } } public Vector<ModeloProducto> listar(){ Vector<ModeloProducto> v = new Vector<ModeloProducto>(); String tira="SELECT * FROM Producto WHERE status='A'"; getConexion(); try { ResultSet rs = consultar(tira); while (rs.next()){ ModeloProducto i = new ModeloProducto(); i.setDescripcion(rs.getString("descripcion")); i.setCodigo(rs.getString("codigo")); i.setPrecio(rs.getFloat("precio")); i.setStatus(rs.getString("status")); i.setCod_categoria(rs.getString("cod_categoria")); v.add(i); } } catch (SQLException ex) { Logger.getLogger(ModeloProducto.class.getName()).log(Level.SEVERE, null, ex); } return v; } public Vector<String []> ingredientesMasUsados(boolean orden){ Vector<String []> v = new Vector<String []>(); String tira="SELECT cantidades , descripcion , codigo FROM Ingrediente,(SELECT SUM(cantidad) AS cantidades,cod_ing AS cod_TablaAux FROM IngredientexProducto GROUP BY cod_ing) TablaAux WHERE Ingrediente.codigo=TablaAux.cod_TablaAux ORDER BY cantidades "; if(orden) tira+= "asc"; else tira+= "desc"; getConexion(); try { ResultSet rs = consultar(tira); while (rs.next()){ String [] s = {rs.getString(2), ""+rs.getDouble(1)}; v.add(s); } } catch (SQLException ex) { Logger.getLogger(ModeloProducto.class.getName()).log(Level.SEVERE, null, ex); } return v; } public Vector<String []> listarVentas(boolean orden){ Vector<String []> v = new Vector<String []>(); String tira="SELECT descripcion, (precio*TablaAux.cantidades), TablaAux.cantidades, codigo FROM Producto, (SELECT sum(ProductoXOrden.cantidad) as cantidades, ProductoXOrden.cod_pro AS cod_TablaAux FROM ProductoXOrden GROUP BY ProductoXOrden.cod_pro) TablaAux WHERE TablaAux.cod_TablaAux=codigo AND status='A' ORDER BY(TablaAux.cantidades,(precio*TablaAux.cantidades)) "; if(orden) tira+= "asc"; else tira+= "desc"; getConexion(); try{ ResultSet rs= consultar(tira); while (rs.next()){ String [] s = new String [] {rs.getString(1), ""+rs.getDouble(2), ""+rs.getDouble(3), rs.getString(4)}; v.add(s); } } catch (SQLException ex) { Logger.getLogger(ModeloProducto.class.getName()).log(Level.SEVERE, null, ex); } return v; } public boolean revisarStockIngredientes(int cantidad){ Vector<ModeloIngrediente> v = new Vector<ModeloIngrediente>(); Vector<Double> d = new Vector<Double>(); String tira="SELECT Ingrediente.codigo,IngredientexProducto.cantidad FROM Ingrediente,IngredientexProducto,Producto WHERE Ingrediente.status='A' AND Producto.status='A' AND Ingrediente.codigo=IngredientexProducto.cod_ing AND Producto.codigo=IngredientexProducto.cod_pro AND Producto.codigo=?"; getConexion(); try{ PreparedStatement stam = generarPreparedStatement(tira); stam.setString(1, getCodigo()); ResultSet rs =consultarPrepare(stam); while(rs.next()){ ModeloIngrediente i = new ModeloIngrediente(); i.setCodigo(rs.getString(1)); d.add(rs.getDouble(2)); v.add(i); } } catch (SQLException ex) { Logger.getLogger(ModeloIngrediente.class.getName()).log(Level.SEVERE, null, ex); } for (int i = 0; i < v.size(); i++) if(!(v.elementAt(i).revisarStock(d.elementAt(i)*cantidad))){ return false; } return true; } public void actualizarStockIngredientes(){ Vector<ModeloIngrediente> v = new Vector<ModeloIngrediente>(); Vector<Double> d = new Vector<Double>(); String tira="SELECT Ingrediente.codigo,IngredientexProducto.cantidad FROM Ingrediente,IngredientexProducto,Producto WHERE Ingrediente.status='A' AND Producto.status='A' AND Ingrediente.codigo=IngredientexProducto.cod_ing AND Producto.codigo=IngredientexProducto.cod_pro AND Producto.codigo=?"; getConexion(); try{ PreparedStatement stam = generarPreparedStatement(tira); stam.setString(1, getCodigo()); ResultSet rs =consultarPrepare(stam); while(rs.next()){ ModeloIngrediente i = new ModeloIngrediente(); i.setCodigo(rs.getString(1)); d.add(rs.getDouble(2)); v.add(i); } } catch (SQLException ex) { Logger.getLogger(ModeloIngrediente.class.getName()).log(Level.SEVERE, null, ex); } for (int i = 0; i < v.size(); i++){ v.elementAt(i).consultar(); v.elementAt(i).setStock(v.elementAt(i).getStock()-d.elementAt(i)); v.elementAt(i).restarStock(); } } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public String getCod_categoria() { return cod_categoria; } public void setCod_categoria(String cod_categoria) { this.cod_categoria = cod_categoria; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public double getPrecio() { return precio; } public void setPrecio(double precio) { this.precio = precio; } }
Java
package MODELO; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import MODELO.ModeloIngrediente; public class ModeloIngrediente extends Conexion { private String codigo; private String descripcion; private String status; private double stock; public ModeloIngrediente() { super(); } public boolean registar(){ getConexion(); boolean sw = false; String tira="INSERT INTO Ingrediente (codigo, descripcion, stock, status) VALUES(?,?,?,?)"; try { PreparedStatement stam = generarPreparedStatement(tira); stam.setString(1, getCodigo()); stam.setString(2, getDescripcion().toUpperCase()); stam.setDouble(3, getStock()); stam.setString(4, getStatus()); ejecutarPrepare(stam); sw= true; } catch (SQLException ex) { Logger.getLogger(ModeloCategoria.class.getName()).log(Level.SEVERE, null, ex); } return sw; } public boolean actualizar(){ getConexion(); boolean sw = false; String tira="UPDATE Ingrediente SET stock =? WHERE codigo=? AND status = 'A'"; try { PreparedStatement stam = generarPreparedStatement(tira); stam.setString(2, getCodigo()); stam.setDouble(1, getStock()); ejecutarPrepare(stam); sw= true; } catch (SQLException ex) { Logger.getLogger(ModeloIngrediente.class.getName()).log(Level.SEVERE, null, ex); } return sw; } public boolean consultar(){ getConexion(); boolean sw = false; String tira="SELECT * FROM Ingrediente WHERE codigo=? AND status='A'"; try { PreparedStatement stam = generarPreparedStatement(tira); stam.setString(1, getCodigo()); ResultSet rs= consultarPrepare(stam); if (rs.next()){ sw = true; setDescripcion(rs.getString("descripcion")); setCodigo(rs.getString("codigo")); setStatus(rs.getString("status")); setStock(rs.getFloat("stock")); } } catch (SQLException ex) { Logger.getLogger(ModeloIngrediente.class.getName()).log(Level.SEVERE, null, ex); } return sw; } public Vector<ModeloIngrediente> listar(){ Vector<ModeloIngrediente> v = new Vector<ModeloIngrediente>(); String tira="SELECT * FROM Ingrediente WHERE status='A'"; getConexion(); try { ResultSet rs= consultar(tira); while (rs.next()){ ModeloIngrediente i = new ModeloIngrediente(); i.setDescripcion(rs.getString("descripcion")); i.setCodigo(rs.getString("codigo")); i.setStatus(rs.getString("status")); i.setStock(rs.getFloat("stock")); v.add(i); } } catch (SQLException ex) { Logger.getLogger(ModeloIngrediente.class.getName()).log(Level.SEVERE, null, ex); } return v; } public boolean revisarStock(double porcion){ consultar(); if((getStock()-porcion)>=0) return true; else return false; } public void restarStock(){ getConexion(); String tira="UPDATE Ingrediente SET stock =? WHERE codigo=? AND status = 'A'"; try { PreparedStatement stam = generarPreparedStatement(tira); stam.setString(2, getCodigo()); stam.setDouble(1, getStock()); ejecutarPrepare(stam); } catch (SQLException ex) { Logger.getLogger(ModeloIngrediente.class.getName()).log(Level.SEVERE, null, ex); } } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public double getStock() { return stock; } public void setStock(double stock) { this.stock = stock; } }
Java
package MODELO; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; public class ModeloOrden extends Conexion{ private String codigo, cedula, nombre, status; private double total; public ModeloOrden() { super(); } public boolean registar(){ boolean sw = false; getConexion(); String tira="INSERT INTO Orden (codigo, cedula, nombre, total ,status ) VALUES(?,?,?,?,?)"; try { PreparedStatement stam = generarPreparedStatement(tira); stam.setString(1, getCodigo()); stam.setString(2, getCedula()); stam.setString(3, getNombre()); stam.setDouble(4, getTotal()); stam.setString(5, getStatus()); ejecutarPrepare(stam); sw = true; } catch (SQLException ex) { Logger.getLogger(ModeloProducto.class.getName()).log(Level.SEVERE, null, ex); } return sw; } public void registarProductos(Vector<String> codigos,Vector<Double> cantidades){ getConexion(); for (int i = 0; i < codigos.size(); i++) { String tira="INSERT INTO ProductoxOrden (cod_ord, cod_pro, cantidad ) VALUES(?,?,?)"; try { PreparedStatement stam = generarPreparedStatement(tira); stam.setString(1, getCodigo()); stam.setString(2,codigos.elementAt(i)); stam.setDouble(3, cantidades.elementAt(i)); ejecutarPrepare(stam); } catch (SQLException ex) { Logger.getLogger(ModeloOrden.class.getName()).log(Level.SEVERE, null, ex); } } } public Vector<String []> listarProductos(){ Vector<String []> v = new Vector<String []>(); getConexion(); String sql="SELECT Producto.descripcion , ProductoXOrden.cantidad FROM Producto,ProductoXOrden,Orden WHERE Orden.status='A' AND Producto.status='A' AND Producto.codigo=ProductoXOrden.cod_pro AND Orden.codigo=ProductoXOrden.cod_ord AND Orden.codigo=?"; try { PreparedStatement stam = generarPreparedStatement(sql); stam.setString(1, getCodigo()); ResultSet rs= consultarPrepare(stam); while (rs.next()){ String [] s = new String [] {rs.getString(1), ""+rs.getDouble(2)}; v.add(s); } } catch (SQLException ex) { Logger.getLogger(ModeloProducto.class.getName()).log(Level.SEVERE, null, ex); } return v; } public int contarOrdenes(){ getConexion(); String sql="SELECT COUNT(*) from Orden WHERE status='A'"; try { ResultSet rs = consultar(sql); while (rs.next()){ return rs.getInt(1)+1; } } catch (SQLException ex) { Logger.getLogger(ModeloProducto.class.getName()).log(Level.SEVERE, null, ex); } return 0; } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public String getCedula() { return cedula; } public void setCedula(String cedula) { this.cedula = cedula; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public double getTotal() { return total; } public void setTotal(double total) { this.total = total; } }
Java
package MODELO; import java.sql.*; import java.util.logging.Level; import java.util.logging.Logger; import MODELO.Conexion; public class Conexion { // La descripcion del driver de la BD private static String driver = "org.postgresql.Driver"; // La direccion URL de la BD private static String url = "jdbc:postgresql://localhost:5432/"; // El nombre de la BD private static String bd = "BD3-9"; // EL login del usuario para conectarse al servidor de BD private static String usuario = "SISTEMAS"; // EL password del usuario para conectarse al servidor de BD private static String password = "654321"; private static Connection conexion; /** * Metodo utilizado para Obtener una conexion a BD * @return Un objeto tipo Connection que representa una conexion a la BD */ protected static Connection getConexion() { try{ if (conexion == null || conexion.isClosed()) { // Cargo el driver en memoria Class.forName(driver); // Establezco la conexion conexion=DriverManager.getConnection(url+bd,usuario,password); } } catch(SQLException e){ e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return conexion; } /** * Metodo consultar * @param String tiraSQL * @return ResultSet */ public static ResultSet consultar(String tiraSQL) { getConexion(); ResultSet resultado = null; try { Statement sentencia= conexion.createStatement(); resultado = sentencia.executeQuery(tiraSQL); } catch(Exception e) { e.printStackTrace(); } try { conexion.close(); } catch( SQLException e ) { e.printStackTrace(); } return resultado; } /** * Metodo ejecutar * @param String TiraSQL * @return boolean */ public static boolean ejecutar(String tiraSQL) { getConexion(); boolean ok = false; try { Statement sentencia = conexion.createStatement(); int i = sentencia.executeUpdate(tiraSQL); if (i > 0) { ok = true; } sentencia.close (); } catch(Exception e) { e.printStackTrace(); } try { conexion.close(); } catch( SQLException e ) { e.printStackTrace(); } return ok; } public static ResultSet consultarPrepare(PreparedStatement statement) { getConexion(); ResultSet resultado = null; try { resultado = statement.executeQuery(); } catch(Exception e) { e.printStackTrace(); } try { conexion.close(); } catch( SQLException e ) { e.printStackTrace(); } return resultado; } /** * Metodo ejecutar * @param String TiraSQL * @return boolean */ public static boolean ejecutarPrepare(PreparedStatement statement) { getConexion(); boolean ok = false; try { int i = statement.executeUpdate(); if (i > 0) { ok = true; } } catch(Exception e) { e.printStackTrace(); } try { conexion.close(); } catch( SQLException e ) { e.printStackTrace(); } return ok; } protected PreparedStatement generarPreparedStatement(String sql){ PreparedStatement statement = null; try { statement = conexion.prepareStatement(sql); } catch (SQLException ex) { Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex); } return statement; } }
Java
import CONTROLADOR.ControladorMenuPrincipal; import VISTA.MenuPrincipal; /* Integrantes: Lilianny Rodriguez C.I.: 19.323.400 Jose Leonardo Jerez C.I.: */ public class Principal { public static void main(String[] args) { new ControladorMenuPrincipal(); } }
Java