code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
package com.ch_linghu.fanfoudroid.ui.module; import android.widget.ListAdapter; public interface TweetAdapter extends ListAdapter { void refresh(); }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/ui/module/TweetAdapter.java
Java
asf20
153
package com.ch_linghu.fanfoudroid; import java.text.MessageFormat; import java.util.List; import android.content.Intent; import android.os.Bundle; import com.ch_linghu.fanfoudroid.fanfou.Paging; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.ui.base.UserArrayBaseActivity; import com.ch_linghu.fanfoudroid.R; public class FollowersActivity extends UserArrayBaseActivity { private static final String TAG = "FollowersActivity"; private String userId; private String userName; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FOLLOWERS"; private static final String USER_ID = "userId"; private static final String USER_NAME = "userName"; private int currentPage = 1; @Override protected boolean _onCreate(Bundle savedInstanceState) { if (super._onCreate(savedInstanceState)) { Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null) { this.userId = extras.getString(USER_ID); this.userName = extras.getString(USER_NAME); } else { // 获取登录用户id userId = TwitterApplication.getMyselfId(false); userName = TwitterApplication.getMyselfName(false); } String myself = TwitterApplication.getMyselfId(false); if (getUserId() == myself) { mNavbar.setHeaderTitle(MessageFormat.format( getString(R.string.profile_followers_count_title), "我")); } else { mNavbar.setHeaderTitle(MessageFormat.format( getString(R.string.profile_followers_count_title), userName)); } return true; } else { return false; } } public static Intent createIntent(String userId, String userName) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra(USER_ID, userId); intent.putExtra(USER_NAME, userName); return intent; } @Override public Paging getNextPage() { currentPage += 1; return new Paging(currentPage); } @Override protected String getUserId() { return this.userId; } @Override public Paging getCurrentPage() { currentPage = 1; return new Paging(this.currentPage); } @Override protected List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers( String userId, Paging page) throws HttpException { return getApi().getFollowersList(userId, page); } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/FollowersActivity.java
Java
asf20
2,322
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.Menu; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.db.StatusTable; import com.ch_linghu.fanfoudroid.fanfou.Paging; import com.ch_linghu.fanfoudroid.fanfou.Status; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity; import com.ch_linghu.fanfoudroid.R; public class MentionActivity extends TwitterCursorBaseActivity { private static final String TAG = "MentionActivity"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.REPLIES"; static final int DIALOG_WRITE_ID = 0; public static Intent createIntent(Context context) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); return intent; } public static Intent createNewTaskIntent(Context context) { Intent intent = createIntent(context); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); return intent; } @Override protected boolean _onCreate(Bundle savedInstanceState) { if (super._onCreate(savedInstanceState)) { mNavbar.setHeaderTitle("@提到我的"); return true; } else { return false; } } @Override public boolean onCreateOptionsMenu(Menu menu) { return super.onCreateOptionsMenu(menu); } @Override protected Cursor fetchMessages() { return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_MENTION); } @Override protected void markAllRead() { getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_MENTION); } @Override protected String getActivityTitle() { return getResources().getString(R.string.page_title_mentions); } // for Retrievable interface @Override public String fetchMaxId() { return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_MENTION); } @Override public List<Status> getMessageSinceId(String maxId) throws HttpException { if (maxId != null) { return getApi().getMentions(new Paging(maxId)); } else { return getApi().getMentions(); } } @Override public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) { return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_MENTION, isUnread); } @Override public String fetchMinId() { return getDb().fetchMinTweetId(getUserId(), StatusTable.TYPE_MENTION); } @Override public List<Status> getMoreMessageFromId(String minId) throws HttpException { Paging paging = new Paging(1, 20); paging.setMaxId(minId); return getApi().getMentions(paging); } @Override public int getDatabaseType() { return StatusTable.TYPE_MENTION; } @Override public String getUserId() { return TwitterApplication.getMyselfId(false); } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/MentionActivity.java
Java
asf20
3,471
package com.ch_linghu.fanfoudroid.http; /** * HTTP StatusCode is not 200 */ public class HttpException extends Exception { private int statusCode = -1; public HttpException(String msg) { super(msg); } public HttpException(Exception cause) { super(cause); } public HttpException(String msg, int statusCode) { super(msg); this.statusCode = statusCode; } public HttpException(String msg, Exception cause) { super(msg, cause); } public HttpException(String msg, Exception cause, int statusCode) { super(msg, cause); this.statusCode = statusCode; } public int getStatusCode() { return this.statusCode; } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/http/HttpException.java
Java
asf20
640
package com.ch_linghu.fanfoudroid.http; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.zip.GZIPInputStream; import javax.net.ssl.SSLHandshakeException; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.HttpVersion; import org.apache.http.NoHttpResponseException; import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthState; import org.apache.http.auth.Credentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.protocol.ClientContext; import org.apache.http.conn.params.ConnManagerParams; import org.apache.http.conn.params.ConnRoutePNames; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.entity.HttpEntityWrapper; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HttpContext; import android.util.Log; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.fanfou.Configuration; import com.ch_linghu.fanfoudroid.fanfou.RefuseError; import com.ch_linghu.fanfoudroid.util.DebugTimer; /** * Wrap of org.apache.http.impl.client.DefaultHttpClient * * @author lds * */ public class HttpClient { private static final String TAG = "HttpClient"; private final static boolean DEBUG = Configuration.getDebug(); /** OK: Success! */ public static final int OK = 200; /** Not Modified: There was no new data to return. */ public static final int NOT_MODIFIED = 304; /** * Bad Request: The request was invalid. An accompanying error message will * explain why. This is the status code will be returned during rate * limiting. */ public static final int BAD_REQUEST = 400; /** Not Authorized: Authentication credentials were missing or incorrect. */ public static final int NOT_AUTHORIZED = 401; /** * Forbidden: The request is understood, but it has been refused. An * accompanying error message will explain why. */ public static final int FORBIDDEN = 403; /** * Not Found: The URI requested is invalid or the resource requested, such * as a user, does not exists. */ public static final int NOT_FOUND = 404; /** * Not Acceptable: Returned by the Search API when an invalid format is * specified in the request. */ public static final int NOT_ACCEPTABLE = 406; /** * Internal Server Error: Something is broken. Please post to the group so * the Weibo team can investigate. */ public static final int INTERNAL_SERVER_ERROR = 500; /** Bad Gateway: Weibo is down or being upgraded. */ public static final int BAD_GATEWAY = 502; /** * Service Unavailable: The Weibo servers are up, but overloaded with * requests. Try again later. The search and trend methods use this to * indicate when you are being rate limited. */ public static final int SERVICE_UNAVAILABLE = 503; private static final int CONNECTION_TIMEOUT_MS = 30 * 1000; private static final int SOCKET_TIMEOUT_MS = 30 * 1000; public static final int RETRIEVE_LIMIT = 20; public static final int RETRIED_TIME = 3; private static final String SERVER_HOST = "api.fanfou.com"; private DefaultHttpClient mClient; private AuthScope mAuthScope; private BasicHttpContext localcontext; private String mUserId; private String mPassword; private static boolean isAuthenticationEnabled = false; public HttpClient() { prepareHttpClient(); } /** * @param user_id * auth user * @param password * auth password */ public HttpClient(String user_id, String password) { prepareHttpClient(); setCredentials(user_id, password); } /** * Empty the credentials */ public void reset() { setCredentials("", ""); } /** * @return authed user id */ public String getUserId() { return mUserId; } /** * @return authed user password */ public String getPassword() { return mPassword; } /** * @param hostname * the hostname (IP or DNS name) * @param port * the port number. -1 indicates the scheme default port. * @param scheme * the name of the scheme. null indicates the default scheme */ public void setProxy(String host, int port, String scheme) { HttpHost proxy = new HttpHost(host, port, scheme); mClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } public void removeProxy() { mClient.getParams().removeParameter(ConnRoutePNames.DEFAULT_PROXY); } private void enableDebug() { Log.d(TAG, "enable apache.http debug"); java.util.logging.Logger.getLogger("org.apache.http").setLevel( java.util.logging.Level.FINEST); java.util.logging.Logger.getLogger("org.apache.http.wire").setLevel( java.util.logging.Level.FINER); java.util.logging.Logger.getLogger("org.apache.http.headers").setLevel( java.util.logging.Level.OFF); /* * System.setProperty("log.tag.org.apache.http", "VERBOSE"); * System.setProperty("log.tag.org.apache.http.wire", "VERBOSE"); * System.setProperty("log.tag.org.apache.http.headers", "VERBOSE"); * * 在这里使用System.setProperty设置不会生效, 原因不明, 必须在终端上输入以下命令方能开启http调试信息: > adb * shell setprop log.tag.org.apache.http VERBOSE > adb shell setprop * log.tag.org.apache.http.wire VERBOSE > adb shell setprop * log.tag.org.apache.http.headers VERBOSE */ } /** * Setup DefaultHttpClient * * Use ThreadSafeClientConnManager. * */ private void prepareHttpClient() { if (DEBUG) { enableDebug(); } // Create and initialize HTTP parameters HttpParams params = new BasicHttpParams(); ConnManagerParams.setMaxTotalConnections(params, 10); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // Create and initialize scheme registry SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory .getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory .getSocketFactory(), 443)); // Create an HttpClient with the ThreadSafeClientConnManager. ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager( params, schemeRegistry); mClient = new DefaultHttpClient(cm, params); // Setup BasicAuth BasicScheme basicScheme = new BasicScheme(); mAuthScope = new AuthScope(SERVER_HOST, AuthScope.ANY_PORT); // mClient.setAuthSchemes(authRegistry); mClient.setCredentialsProvider(new BasicCredentialsProvider()); // Generate BASIC scheme object and stick it to the local // execution context localcontext = new BasicHttpContext(); localcontext.setAttribute("preemptive-auth", basicScheme); // first request interceptor mClient.addRequestInterceptor(preemptiveAuth, 0); // Support GZIP mClient.addResponseInterceptor(gzipResponseIntercepter); // TODO: need to release this connection in httpRequest() // cm.releaseConnection(conn, validDuration, timeUnit); // httpclient.getConnectionManager().shutdown(); } /** * HttpRequestInterceptor for DefaultHttpClient */ private static HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() { @Override public void process(final HttpRequest request, final HttpContext context) { AuthState authState = (AuthState) context .getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context .getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } } }; private static HttpResponseInterceptor gzipResponseIntercepter = new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext context) throws org.apache.http.HttpException, IOException { HttpEntity entity = response.getEntity(); Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response .getEntity())); return; } } } } }; static class GzipDecompressingEntity extends HttpEntityWrapper { public GzipDecompressingEntity(final HttpEntity entity) { super(entity); } @Override public InputStream getContent() throws IOException, IllegalStateException { // the wrapped entity's getContent() decides about repeatability InputStream wrappedin = wrappedEntity.getContent(); return new GZIPInputStream(wrappedin); } @Override public long getContentLength() { // length of ungzipped content is not known return -1; } } /** * Setup Credentials for HTTP Basic Auth * * @param username * @param password */ public void setCredentials(String username, String password) { mUserId = username; mPassword = password; mClient.getCredentialsProvider().setCredentials(mAuthScope, new UsernamePasswordCredentials(username, password)); isAuthenticationEnabled = true; } public Response post(String url, ArrayList<BasicNameValuePair> postParams, boolean authenticated) throws HttpException { if (null == postParams) { postParams = new ArrayList<BasicNameValuePair>(); } return httpRequest(url, postParams, authenticated, HttpPost.METHOD_NAME); } public Response post(String url, ArrayList<BasicNameValuePair> params) throws HttpException { return httpRequest(url, params, false, HttpPost.METHOD_NAME); } public Response post(String url, boolean authenticated) throws HttpException { return httpRequest(url, null, authenticated, HttpPost.METHOD_NAME); } public Response post(String url) throws HttpException { return httpRequest(url, null, false, HttpPost.METHOD_NAME); } public Response post(String url, File file) throws HttpException { return httpRequest(url, null, file, false, HttpPost.METHOD_NAME); } /** * POST一个文件 * * @param url * @param file * @param authenticate * @return * @throws HttpException */ public Response post(String url, File file, boolean authenticate) throws HttpException { return httpRequest(url, null, file, authenticate, HttpPost.METHOD_NAME); } public Response get(String url, ArrayList<BasicNameValuePair> params, boolean authenticated) throws HttpException { return httpRequest(url, params, authenticated, HttpGet.METHOD_NAME); } public Response get(String url, ArrayList<BasicNameValuePair> params) throws HttpException { return httpRequest(url, params, false, HttpGet.METHOD_NAME); } public Response get(String url) throws HttpException { return httpRequest(url, null, false, HttpGet.METHOD_NAME); } public Response get(String url, boolean authenticated) throws HttpException { return httpRequest(url, null, authenticated, HttpGet.METHOD_NAME); } public Response httpRequest(String url, ArrayList<BasicNameValuePair> postParams, boolean authenticated, String httpMethod) throws HttpException { return httpRequest(url, postParams, null, authenticated, httpMethod); } /** * Execute the DefaultHttpClient * * @param url * target * @param postParams * @param file * can be NULL * @param authenticated * need or not * @param httpMethod * HttpPost.METHOD_NAME HttpGet.METHOD_NAME * HttpDelete.METHOD_NAME * @return Response from server * @throws HttpException * 此异常包装了一系列底层异常 <br /> * <br /> * 1. 底层异常, 可使用getCause()查看: <br /> * <li>URISyntaxException, 由`new URI` 引发的.</li> <li>IOException, * 由`createMultipartEntity` 或 `UrlEncodedFormEntity` 引发的.</li> * <li>IOException和ClientProtocolException, * 由`HttpClient.execute` 引发的.</li><br /> * * 2. 当响应码不为200时报出的各种子类异常: <li>HttpRequestException, * 通常发生在请求的错误,如请求错误了 网址导致404等, 抛出此异常, 首先检查request log, * 确认不是人为错误导致请求失败</li> <li>HttpAuthException, 通常发生在Auth失败, * 检查用于验证登录的用户名/密码/KEY等</li> <li>HttpRefusedException, * 通常发生在服务器接受到请求, 但拒绝请求, 可是多种原因, 具体原因 服务器会返回拒绝理由, * 调用HttpRefusedException#getError#getMessage查看</li> <li> * HttpServerException, 通常发生在服务器发生错误时, 检查服务器端是否在正常提供服务</li> <li> * HttpException, 其他未知错误.</li> */ public Response httpRequest(String url, ArrayList<BasicNameValuePair> postParams, File file, boolean authenticated, String httpMethod) throws HttpException { Log.d(TAG, "Sending " + httpMethod + " request to " + url); if (TwitterApplication.DEBUG) { DebugTimer.betweenStart("HTTP"); } URI uri = createURI(url); HttpResponse response = null; Response res = null; HttpUriRequest method = null; // Create POST, GET or DELETE METHOD method = createMethod(httpMethod, uri, file, postParams); // Setup ConnectionParams, Request Headers SetupHTTPConnectionParams(method); // Execute Request try { response = mClient.execute(method, localcontext); res = new Response(response); } catch (ClientProtocolException e) { Log.e(TAG, e.getMessage(), e); throw new HttpException(e.getMessage(), e); } catch (IOException ioe) { throw new HttpException(ioe.getMessage(), ioe); } if (response != null) { int statusCode = response.getStatusLine().getStatusCode(); // It will throw a weiboException while status code is not 200 HandleResponseStatusCode(statusCode, res); } else { Log.e(TAG, "response is null"); } if (TwitterApplication.DEBUG) { DebugTimer.betweenEnd("HTTP"); } return res; } /** * CreateURI from URL string * * @param url * @return request URI * @throws HttpException * Cause by URISyntaxException */ private URI createURI(String url) throws HttpException { URI uri; try { uri = new URI(url); } catch (URISyntaxException e) { Log.e(TAG, e.getMessage(), e); throw new HttpException("Invalid URL."); } return uri; } /** * 创建可带一个File的MultipartEntity * * @param filename * 文件名 * @param file * 文件 * @param postParams * 其他POST参数 * @return 带文件和其他参数的Entity * @throws UnsupportedEncodingException */ private MultipartEntity createMultipartEntity(String filename, File file, ArrayList<BasicNameValuePair> postParams) throws UnsupportedEncodingException { MultipartEntity entity = new MultipartEntity(); // Don't try this. Server does not appear to support chunking. // entity.addPart("media", new InputStreamBody(imageStream, "media")); entity.addPart(filename, new FileBody(file)); for (BasicNameValuePair param : postParams) { entity.addPart(param.getName(), new StringBody(param.getValue())); } return entity; } /** * Setup HTTPConncetionParams * * @param method */ private void SetupHTTPConnectionParams(HttpUriRequest method) { HttpConnectionParams.setConnectionTimeout(method.getParams(), CONNECTION_TIMEOUT_MS); HttpConnectionParams .setSoTimeout(method.getParams(), SOCKET_TIMEOUT_MS); mClient.setHttpRequestRetryHandler(requestRetryHandler); method.addHeader("Accept-Encoding", "gzip, deflate"); method.addHeader("Accept-Charset", "UTF-8,*;q=0.5"); } /** * Create request method, such as POST, GET, DELETE * * @param httpMethod * "GET","POST","DELETE" * @param uri * 请求的URI * @param file * 可为null * @param postParams * POST参数 * @return httpMethod Request implementations for the various HTTP methods * like GET and POST. * @throws HttpException * createMultipartEntity 或 UrlEncodedFormEntity引发的IOException */ private HttpUriRequest createMethod(String httpMethod, URI uri, File file, ArrayList<BasicNameValuePair> postParams) throws HttpException { HttpUriRequest method; if (httpMethod.equalsIgnoreCase(HttpPost.METHOD_NAME)) { // POST METHOD HttpPost post = new HttpPost(uri); // See this: // http://groups.google.com/group/twitter-development-talk/browse_thread/thread/e178b1d3d63d8e3b post.getParams().setBooleanParameter( "http.protocol.expect-continue", false); try { HttpEntity entity = null; if (null != file) { entity = createMultipartEntity("photo", file, postParams); post.setEntity(entity); } else if (null != postParams) { entity = new UrlEncodedFormEntity(postParams, HTTP.UTF_8); } post.setEntity(entity); } catch (IOException ioe) { throw new HttpException(ioe.getMessage(), ioe); } method = post; } else if (httpMethod.equalsIgnoreCase(HttpDelete.METHOD_NAME)) { method = new HttpDelete(uri); } else { method = new HttpGet(uri); } return method; } /** * 解析HTTP错误码 * * @param statusCode * @return */ private static String getCause(int statusCode) { String cause = null; switch (statusCode) { case NOT_MODIFIED: break; case BAD_REQUEST: cause = "The request was invalid. An accompanying error message will explain why. This is the status code will be returned during rate limiting."; break; case NOT_AUTHORIZED: cause = "Authentication credentials were missing or incorrect."; break; case FORBIDDEN: cause = "The request is understood, but it has been refused. An accompanying error message will explain why."; break; case NOT_FOUND: cause = "The URI requested is invalid or the resource requested, such as a user, does not exists."; break; case NOT_ACCEPTABLE: cause = "Returned by the Search API when an invalid format is specified in the request."; break; case INTERNAL_SERVER_ERROR: cause = "Something is broken. Please post to the group so the Weibo team can investigate."; break; case BAD_GATEWAY: cause = "Weibo is down or being upgraded."; break; case SERVICE_UNAVAILABLE: cause = "Service Unavailable: The Weibo servers are up, but overloaded with requests. Try again later. The search and trend methods use this to indicate when you are being rate limited."; break; default: cause = ""; } return statusCode + ":" + cause; } public boolean isAuthenticationEnabled() { return isAuthenticationEnabled; } public static void log(String msg) { if (DEBUG) { Log.d(TAG, msg); } } /** * Handle Status code * * @param statusCode * 响应的状态码 * @param res * 服务器响应 * @throws HttpException * 当响应码不为200时都会报出此异常:<br /> * <li>HttpRequestException, 通常发生在请求的错误,如请求错误了 网址导致404等, 抛出此异常, * 首先检查request log, 确认不是人为错误导致请求失败</li> <li>HttpAuthException, * 通常发生在Auth失败, 检查用于验证登录的用户名/密码/KEY等</li> <li> * HttpRefusedException, 通常发生在服务器接受到请求, 但拒绝请求, 可是多种原因, 具体原因 * 服务器会返回拒绝理由, 调用HttpRefusedException#getError#getMessage查看</li> * <li>HttpServerException, 通常发生在服务器发生错误时, 检查服务器端是否在正常提供服务</li> * <li>HttpException, 其他未知错误.</li> */ private void HandleResponseStatusCode(int statusCode, Response res) throws HttpException { String msg = getCause(statusCode) + "\n"; RefuseError error = null; switch (statusCode) { // It's OK, do nothing case OK: break; // Mine mistake, Check the Log case NOT_MODIFIED: case BAD_REQUEST: case NOT_FOUND: case NOT_ACCEPTABLE: throw new HttpException(msg + res.asString(), statusCode); // UserName/Password incorrect case NOT_AUTHORIZED: throw new HttpAuthException(msg + res.asString(), statusCode); // Server will return a error message, use // HttpRefusedException#getError() to see. case FORBIDDEN: throw new HttpRefusedException(msg, statusCode); // Something wrong with server case INTERNAL_SERVER_ERROR: case BAD_GATEWAY: case SERVICE_UNAVAILABLE: throw new HttpServerException(msg, statusCode); // Others default: throw new HttpException(msg + res.asString(), statusCode); } } public static String encode(String value) throws HttpException { try { return URLEncoder.encode(value, HTTP.UTF_8); } catch (UnsupportedEncodingException e_e) { throw new HttpException(e_e.getMessage(), e_e); } } public static String encodeParameters(ArrayList<BasicNameValuePair> params) throws HttpException { StringBuffer buf = new StringBuffer(); for (int j = 0; j < params.size(); j++) { if (j != 0) { buf.append("&"); } try { buf.append(URLEncoder.encode(params.get(j).getName(), "UTF-8")) .append("=") .append(URLEncoder.encode(params.get(j).getValue(), "UTF-8")); } catch (java.io.UnsupportedEncodingException neverHappen) { throw new HttpException(neverHappen.getMessage(), neverHappen); } } return buf.toString(); } /** * 异常自动恢复处理, 使用HttpRequestRetryHandler接口实现请求的异常恢复 */ private static HttpRequestRetryHandler requestRetryHandler = new HttpRequestRetryHandler() { // 自定义的恢复策略 public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { // 设置恢复策略,在发生异常时候将自动重试N次 if (executionCount >= RETRIED_TIME) { // Do not retry if over max retry count return false; } if (exception instanceof NoHttpResponseException) { // Retry if the server dropped connection on us return true; } if (exception instanceof SSLHandshakeException) { // Do not retry on SSL handshake exception return false; } HttpRequest request = (HttpRequest) context .getAttribute(ExecutionContext.HTTP_REQUEST); boolean idempotent = (request instanceof HttpEntityEnclosingRequest); if (!idempotent) { // Retry if the request is considered idempotent return true; } return false; } }; }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/http/HttpClient.java
Java
asf20
24,743
package com.ch_linghu.fanfoudroid.http; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.util.CharArrayBuffer; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Document; import android.util.Log; import com.ch_linghu.fanfoudroid.util.DebugTimer; public class Response { private final HttpResponse mResponse; private boolean mStreamConsumed = false; public Response(HttpResponse res) { mResponse = res; } /** * Convert Response to inputStream * * @return InputStream or null * @throws ResponseException */ public InputStream asStream() throws ResponseException { try { final HttpEntity entity = mResponse.getEntity(); if (entity != null) { return entity.getContent(); } } catch (IllegalStateException e) { throw new ResponseException(e.getMessage(), e); } catch (IOException e) { throw new ResponseException(e.getMessage(), e); } return null; } /** * @deprecated use entity.getContent(); * @param entity * @return * @throws ResponseException */ private InputStream asStream(HttpEntity entity) throws ResponseException { if (null == entity) { return null; } InputStream is = null; try { is = entity.getContent(); } catch (IllegalStateException e) { throw new ResponseException(e.getMessage(), e); } catch (IOException e) { throw new ResponseException(e.getMessage(), e); } // mResponse = null; return is; } /** * Convert Response to Context String * * @return response context string or null * @throws ResponseException */ public String asString() throws ResponseException { try { return entityToString(mResponse.getEntity()); } catch (IOException e) { throw new ResponseException(e.getMessage(), e); } } /** * EntityUtils.toString(entity, "UTF-8"); * * @param entity * @return * @throws IOException * @throws ResponseException */ private String entityToString(final HttpEntity entity) throws IOException, ResponseException { DebugTimer.betweenStart("AS STRING"); if (null == entity) { throw new IllegalArgumentException("HTTP entity may not be null"); } InputStream instream = entity.getContent(); // InputStream instream = asStream(entity); if (instream == null) { return ""; } if (entity.getContentLength() > Integer.MAX_VALUE) { throw new IllegalArgumentException( "HTTP entity too large to be buffered in memory"); } int i = (int) entity.getContentLength(); if (i < 0) { i = 4096; } Log.i("LDS", i + " content length"); Reader reader = new BufferedReader(new InputStreamReader(instream, "UTF-8")); CharArrayBuffer buffer = new CharArrayBuffer(i); try { char[] tmp = new char[1024]; int l; while ((l = reader.read(tmp)) != -1) { buffer.append(tmp, 0, l); } } finally { reader.close(); } DebugTimer.betweenEnd("AS STRING"); return buffer.toString(); } /** * @deprecated use entityToString() * @param in * @return * @throws ResponseException */ private String inputStreamToString(final InputStream in) throws IOException { if (null == in) { return null; } BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); StringBuffer buf = new StringBuffer(); try { char[] buffer = new char[1024]; while ((reader.read(buffer)) != -1) { buf.append(buffer); } return buf.toString(); } finally { if (reader != null) { reader.close(); setStreamConsumed(true); } } } public JSONObject asJSONObject() throws ResponseException { try { return new JSONObject(asString()); } catch (JSONException jsone) { throw new ResponseException(jsone.getMessage() + ":" + asString(), jsone); } } public JSONArray asJSONArray() throws ResponseException { try { return new JSONArray(asString()); } catch (Exception jsone) { throw new ResponseException(jsone.getMessage(), jsone); } } private void setStreamConsumed(boolean mStreamConsumed) { this.mStreamConsumed = mStreamConsumed; } public boolean isStreamConsumed() { return mStreamConsumed; } /** * @deprecated * @return */ public Document asDocument() { // TODO Auto-generated method stub return null; } private static Pattern escaped = Pattern.compile("&#([0-9]{3,5});"); /** * Unescape UTF-8 escaped characters to string. * * @author pengjianq...@gmail.com * * @param original * The string to be unescaped. * @return The unescaped string */ public static String unescape(String original) { Matcher mm = escaped.matcher(original); StringBuffer unescaped = new StringBuffer(); while (mm.find()) { mm.appendReplacement(unescaped, Character.toString((char) Integer .parseInt(mm.group(1), 10))); } mm.appendTail(unescaped); return unescaped.toString(); } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/http/Response.java
Java
asf20
5,123
package com.ch_linghu.fanfoudroid.http; import java.util.HashMap; import java.util.Map; public class HTMLEntity { public static String escape(String original) { StringBuffer buf = new StringBuffer(original); escape(buf); return buf.toString(); } public static void escape(StringBuffer original) { int index = 0; String escaped; while (index < original.length()) { escaped = entityEscapeMap.get(original.substring(index, index + 1)); if (null != escaped) { original.replace(index, index + 1, escaped); index += escaped.length(); } else { index++; } } } public static String unescape(String original) { StringBuffer buf = new StringBuffer(original); unescape(buf); return buf.toString(); } public static void unescape(StringBuffer original) { int index = 0; int semicolonIndex = 0; String escaped; String entity; while (index < original.length()) { index = original.indexOf("&", index); if (-1 == index) { break; } semicolonIndex = original.indexOf(";", index); if (-1 != semicolonIndex && 10 > (semicolonIndex - index)) { escaped = original.substring(index, semicolonIndex + 1); entity = escapeEntityMap.get(escaped); if (null != entity) { original.replace(index, semicolonIndex + 1, entity); } index++; } else { break; } } } private static Map<String, String> entityEscapeMap = new HashMap<String, String>(); private static Map<String, String> escapeEntityMap = new HashMap<String, String>(); static { String[][] entities = { { "&nbsp;", "&#160;"/* no-break space = non-breaking space */, "\u00A0" }, { "&iexcl;", "&#161;"/* inverted exclamation mark */, "\u00A1" }, { "&cent;", "&#162;"/* cent sign */, "\u00A2" }, { "&pound;", "&#163;"/* pound sign */, "\u00A3" }, { "&curren;", "&#164;"/* currency sign */, "\u00A4" }, { "&yen;", "&#165;"/* yen sign = yuan sign */, "\u00A5" }, { "&brvbar;", "&#166;"/* broken bar = broken vertical bar */, "\u00A6" }, { "&sect;", "&#167;"/* section sign */, "\u00A7" }, { "&uml;", "&#168;"/* diaeresis = spacing diaeresis */, "\u00A8" }, { "&copy;", "&#169;"/* copyright sign */, "\u00A9" }, { "&ordf;", "&#170;"/* feminine ordinal indicator */, "\u00AA" }, { "&laquo;", "&#171;"/* * left-pointing double angle quotation mark * = left pointing guillemet */, "\u00AB" }, { "&not;", "&#172;"/* not sign = discretionary hyphen */, "\u00AC" }, { "&shy;", "&#173;"/* soft hyphen = discretionary hyphen */, "\u00AD" }, { "&reg;", "&#174;"/* * registered sign = registered trade mark * sign */, "\u00AE" }, { "&macr;", "&#175;"/* * macron = spacing macron = overline = APL * overbar */, "\u00AF" }, { "&deg;", "&#176;"/* degree sign */, "\u00B0" }, { "&plusmn;", "&#177;"/* plus-minus sign = plus-or-minus sign */, "\u00B1" }, { "&sup2;", "&#178;"/* * superscript two = superscript digit two = * squared */, "\u00B2" }, { "&sup3;", "&#179;"/* * superscript three = superscript digit * three = cubed */, "\u00B3" }, { "&acute;", "&#180;"/* acute accent = spacing acute */, "\u00B4" }, { "&micro;", "&#181;"/* micro sign */, "\u00B5" }, { "&para;", "&#182;"/* pilcrow sign = paragraph sign */, "\u00B6" }, { "&middot;", "&#183;"/* * middle dot = Georgian comma = Greek * middle dot */, "\u00B7" }, { "&cedil;", "&#184;"/* cedilla = spacing cedilla */, "\u00B8" }, { "&sup1;", "&#185;"/* superscript one = superscript digit one */, "\u00B9" }, { "&ordm;", "&#186;"/* masculine ordinal indicator */, "\u00BA" }, { "&raquo;", "&#187;"/* * right-pointing double angle quotation * mark = right pointing guillemet */, "\u00BB" }, { "&frac14;", "&#188;"/* * vulgar fraction one quarter = fraction * one quarter */, "\u00BC" }, { "&frac12;", "&#189;"/* * vulgar fraction one half = fraction one * half */, "\u00BD" }, { "&frac34;", "&#190;"/* * vulgar fraction three quarters = fraction * three quarters */, "\u00BE" }, { "&iquest;", "&#191;"/* * inverted question mark = turned question * mark */, "\u00BF" }, { "&Agrave;", "&#192;"/* * latin capital letter A with grave = latin * capital letter A grave */, "\u00C0" }, { "&Aacute;", "&#193;"/* latin capital letter A with acute */, "\u00C1" }, { "&Acirc;", "&#194;"/* latin capital letter A with circumflex */, "\u00C2" }, { "&Atilde;", "&#195;"/* latin capital letter A with tilde */, "\u00C3" }, { "&Auml;", "&#196;"/* latin capital letter A with diaeresis */, "\u00C4" }, { "&Aring;", "&#197;"/* * latin capital letter A with ring above = * latin capital letter A ring */, "\u00C5" }, { "&AElig;", "&#198;"/* * latin capital letter AE = latin capital * ligature AE */, "\u00C6" }, { "&Ccedil;", "&#199;"/* latin capital letter C with cedilla */, "\u00C7" }, { "&Egrave;", "&#200;"/* latin capital letter E with grave */, "\u00C8" }, { "&Eacute;", "&#201;"/* latin capital letter E with acute */, "\u00C9" }, { "&Ecirc;", "&#202;"/* latin capital letter E with circumflex */, "\u00CA" }, { "&Euml;", "&#203;"/* latin capital letter E with diaeresis */, "\u00CB" }, { "&Igrave;", "&#204;"/* latin capital letter I with grave */, "\u00CC" }, { "&Iacute;", "&#205;"/* latin capital letter I with acute */, "\u00CD" }, { "&Icirc;", "&#206;"/* latin capital letter I with circumflex */, "\u00CE" }, { "&Iuml;", "&#207;"/* latin capital letter I with diaeresis */, "\u00CF" }, { "&ETH;", "&#208;"/* latin capital letter ETH */, "\u00D0" }, { "&Ntilde;", "&#209;"/* latin capital letter N with tilde */, "\u00D1" }, { "&Ograve;", "&#210;"/* latin capital letter O with grave */, "\u00D2" }, { "&Oacute;", "&#211;"/* latin capital letter O with acute */, "\u00D3" }, { "&Ocirc;", "&#212;"/* latin capital letter O with circumflex */, "\u00D4" }, { "&Otilde;", "&#213;"/* latin capital letter O with tilde */, "\u00D5" }, { "&Ouml;", "&#214;"/* latin capital letter O with diaeresis */, "\u00D6" }, { "&times;", "&#215;"/* multiplication sign */, "\u00D7" }, { "&Oslash;", "&#216;"/* * latin capital letter O with stroke = * latin capital letter O slash */, "\u00D8" }, { "&Ugrave;", "&#217;"/* latin capital letter U with grave */, "\u00D9" }, { "&Uacute;", "&#218;"/* latin capital letter U with acute */, "\u00DA" }, { "&Ucirc;", "&#219;"/* latin capital letter U with circumflex */, "\u00DB" }, { "&Uuml;", "&#220;"/* latin capital letter U with diaeresis */, "\u00DC" }, { "&Yacute;", "&#221;"/* latin capital letter Y with acute */, "\u00DD" }, { "&THORN;", "&#222;"/* latin capital letter THORN */, "\u00DE" }, { "&szlig;", "&#223;"/* latin small letter sharp s = ess-zed */, "\u00DF" }, { "&agrave;", "&#224;"/* * latin small letter a with grave = latin * small letter a grave */, "\u00E0" }, { "&aacute;", "&#225;"/* latin small letter a with acute */, "\u00E1" }, { "&acirc;", "&#226;"/* latin small letter a with circumflex */, "\u00E2" }, { "&atilde;", "&#227;"/* latin small letter a with tilde */, "\u00E3" }, { "&auml;", "&#228;"/* latin small letter a with diaeresis */, "\u00E4" }, { "&aring;", "&#229;"/* * latin small letter a with ring above = * latin small letter a ring */, "\u00E5" }, { "&aelig;", "&#230;"/* * latin small letter ae = latin small * ligature ae */, "\u00E6" }, { "&ccedil;", "&#231;"/* latin small letter c with cedilla */, "\u00E7" }, { "&egrave;", "&#232;"/* latin small letter e with grave */, "\u00E8" }, { "&eacute;", "&#233;"/* latin small letter e with acute */, "\u00E9" }, { "&ecirc;", "&#234;"/* latin small letter e with circumflex */, "\u00EA" }, { "&euml;", "&#235;"/* latin small letter e with diaeresis */, "\u00EB" }, { "&igrave;", "&#236;"/* latin small letter i with grave */, "\u00EC" }, { "&iacute;", "&#237;"/* latin small letter i with acute */, "\u00ED" }, { "&icirc;", "&#238;"/* latin small letter i with circumflex */, "\u00EE" }, { "&iuml;", "&#239;"/* latin small letter i with diaeresis */, "\u00EF" }, { "&eth;", "&#240;"/* latin small letter eth */, "\u00F0" }, { "&ntilde;", "&#241;"/* latin small letter n with tilde */, "\u00F1" }, { "&ograve;", "&#242;"/* latin small letter o with grave */, "\u00F2" }, { "&oacute;", "&#243;"/* latin small letter o with acute */, "\u00F3" }, { "&ocirc;", "&#244;"/* latin small letter o with circumflex */, "\u00F4" }, { "&otilde;", "&#245;"/* latin small letter o with tilde */, "\u00F5" }, { "&ouml;", "&#246;"/* latin small letter o with diaeresis */, "\u00F6" }, { "&divide;", "&#247;"/* division sign */, "\u00F7" }, { "&oslash;", "&#248;"/* * latin small letter o with stroke = latin * small letter o slash */, "\u00F8" }, { "&ugrave;", "&#249;"/* latin small letter u with grave */, "\u00F9" }, { "&uacute;", "&#250;"/* latin small letter u with acute */, "\u00FA" }, { "&ucirc;", "&#251;"/* latin small letter u with circumflex */, "\u00FB" }, { "&uuml;", "&#252;"/* latin small letter u with diaeresis */, "\u00FC" }, { "&yacute;", "&#253;"/* latin small letter y with acute */, "\u00FD" }, { "&thorn;", "&#254;"/* latin small letter thorn with */, "\u00FE" }, { "&yuml;", "&#255;"/* latin small letter y with diaeresis */, "\u00FF" }, { "&fnof;", "&#402;"/* * latin small f with hook = function = * florin */, "\u0192" } /* Greek */ , { "&Alpha;", "&#913;"/* greek capital letter alpha */, "\u0391" }, { "&Beta;", "&#914;"/* greek capital letter beta */, "\u0392" }, { "&Gamma;", "&#915;"/* greek capital letter gamma */, "\u0393" }, { "&Delta;", "&#916;"/* greek capital letter delta */, "\u0394" }, { "&Epsilon;", "&#917;"/* greek capital letter epsilon */, "\u0395" }, { "&Zeta;", "&#918;"/* greek capital letter zeta */, "\u0396" }, { "&Eta;", "&#919;"/* greek capital letter eta */, "\u0397" }, { "&Theta;", "&#920;"/* greek capital letter theta */, "\u0398" }, { "&Iota;", "&#921;"/* greek capital letter iota */, "\u0399" }, { "&Kappa;", "&#922;"/* greek capital letter kappa */, "\u039A" }, { "&Lambda;", "&#923;"/* greek capital letter lambda */, "\u039B" }, { "&Mu;", "&#924;"/* greek capital letter mu */, "\u039C" }, { "&Nu;", "&#925;"/* greek capital letter nu */, "\u039D" }, { "&Xi;", "&#926;"/* greek capital letter xi */, "\u039E" }, { "&Omicron;", "&#927;"/* greek capital letter omicron */, "\u039F" }, { "&Pi;", "&#928;"/* greek capital letter pi */, "\u03A0" }, { "&Rho;", "&#929;"/* greek capital letter rho */, "\u03A1" } /* there is no Sigmaf and no \u03A2 */ , { "&Sigma;", "&#931;"/* greek capital letter sigma */, "\u03A3" }, { "&Tau;", "&#932;"/* greek capital letter tau */, "\u03A4" }, { "&Upsilon;", "&#933;"/* greek capital letter upsilon */, "\u03A5" }, { "&Phi;", "&#934;"/* greek capital letter phi */, "\u03A6" }, { "&Chi;", "&#935;"/* greek capital letter chi */, "\u03A7" }, { "&Psi;", "&#936;"/* greek capital letter psi */, "\u03A8" }, { "&Omega;", "&#937;"/* greek capital letter omega */, "\u03A9" }, { "&alpha;", "&#945;"/* greek small letter alpha */, "\u03B1" }, { "&beta;", "&#946;"/* greek small letter beta */, "\u03B2" }, { "&gamma;", "&#947;"/* greek small letter gamma */, "\u03B3" }, { "&delta;", "&#948;"/* greek small letter delta */, "\u03B4" }, { "&epsilon;", "&#949;"/* greek small letter epsilon */, "\u03B5" }, { "&zeta;", "&#950;"/* greek small letter zeta */, "\u03B6" }, { "&eta;", "&#951;"/* greek small letter eta */, "\u03B7" }, { "&theta;", "&#952;"/* greek small letter theta */, "\u03B8" }, { "&iota;", "&#953;"/* greek small letter iota */, "\u03B9" }, { "&kappa;", "&#954;"/* greek small letter kappa */, "\u03BA" }, { "&lambda;", "&#955;"/* greek small letter lambda */, "\u03BB" }, { "&mu;", "&#956;"/* greek small letter mu */, "\u03BC" }, { "&nu;", "&#957;"/* greek small letter nu */, "\u03BD" }, { "&xi;", "&#958;"/* greek small letter xi */, "\u03BE" }, { "&omicron;", "&#959;"/* greek small letter omicron */, "\u03BF" }, { "&pi;", "&#960;"/* greek small letter pi */, "\u03C0" }, { "&rho;", "&#961;"/* greek small letter rho */, "\u03C1" }, { "&sigmaf;", "&#962;"/* greek small letter final sigma */, "\u03C2" }, { "&sigma;", "&#963;"/* greek small letter sigma */, "\u03C3" }, { "&tau;", "&#964;"/* greek small letter tau */, "\u03C4" }, { "&upsilon;", "&#965;"/* greek small letter upsilon */, "\u03C5" }, { "&phi;", "&#966;"/* greek small letter phi */, "\u03C6" }, { "&chi;", "&#967;"/* greek small letter chi */, "\u03C7" }, { "&psi;", "&#968;"/* greek small letter psi */, "\u03C8" }, { "&omega;", "&#969;"/* greek small letter omega */, "\u03C9" }, { "&thetasym;", "&#977;"/* greek small letter theta symbol */, "\u03D1" }, { "&upsih;", "&#978;"/* greek upsilon with hook symbol */, "\u03D2" }, { "&piv;", "&#982;"/* greek pi symbol */, "\u03D6" } /* General Punctuation */ , { "&bull;", "&#8226;"/* bullet = black small circle */, "\u2022" } /* bullet is NOT the same as bullet operator ,"\u2219 */ , { "&hellip;", "&#8230;"/* * horizontal ellipsis = three dot * leader */, "\u2026" }, { "&prime;", "&#8242;"/* prime = minutes = feet */, "\u2032" }, { "&Prime;", "&#8243;"/* double prime = seconds = inches */, "\u2033" }, { "&oline;", "&#8254;"/* overline = spacing overscore */, "\u203E" }, { "&frasl;", "&#8260;"/* fraction slash */, "\u2044" } /* Letterlike Symbols */ , { "&weierp;", "&#8472;"/* * script capital P = power set = * Weierstrass p */, "\u2118" }, { "&image;", "&#8465;"/* blackletter capital I = imaginary part */, "\u2111" }, { "&real;", "&#8476;"/* blackletter capital R = real part symbol */, "\u211C" }, { "&trade;", "&#8482;"/* trade mark sign */, "\u2122" }, { "&alefsym;", "&#8501;"/* * alef symbol = first transfinite * cardinal */, "\u2135" } /* alef symbol is NOT the same as hebrew letter alef ,"\u05D0"} */ /* Arrows */ , { "&larr;", "&#8592;"/* leftwards arrow */, "\u2190" }, { "&uarr;", "&#8593;"/* upwards arrow */, "\u2191" }, { "&rarr;", "&#8594;"/* rightwards arrow */, "\u2192" }, { "&darr;", "&#8595;"/* downwards arrow */, "\u2193" }, { "&harr;", "&#8596;"/* left right arrow */, "\u2194" }, { "&crarr;", "&#8629;"/* * downwards arrow with corner leftwards = * carriage return */, "\u21B5" }, { "&lArr;", "&#8656;"/* leftwards double arrow */, "\u21D0" } /* * Unicode does not say that lArr is the same as the 'is implied * by' arrow but also does not have any other character for that * function. So ? lArr can be used for 'is implied by' as * ISOtech suggests */ , { "&uArr;", "&#8657;"/* upwards double arrow */, "\u21D1" }, { "&rArr;", "&#8658;"/* rightwards double arrow */, "\u21D2" } /* * Unicode does not say this is the 'implies' character but does * not have another character with this function so ? rArr can * be used for 'implies' as ISOtech suggests */ , { "&dArr;", "&#8659;"/* downwards double arrow */, "\u21D3" }, { "&hArr;", "&#8660;"/* left right double arrow */, "\u21D4" } /* Mathematical Operators */ , { "&forall;", "&#8704;"/* for all */, "\u2200" }, { "&part;", "&#8706;"/* partial differential */, "\u2202" }, { "&exist;", "&#8707;"/* there exists */, "\u2203" }, { "&empty;", "&#8709;"/* empty set = null set = diameter */, "\u2205" }, { "&nabla;", "&#8711;"/* nabla = backward difference */, "\u2207" }, { "&isin;", "&#8712;"/* element of */, "\u2208" }, { "&notin;", "&#8713;"/* not an element of */, "\u2209" }, { "&ni;", "&#8715;"/* contains as member */, "\u220B" } /* should there be a more memorable name than 'ni'? */ , { "&prod;", "&#8719;"/* n-ary product = product sign */, "\u220F" } /* prod is NOT the same character as ,"\u03A0"} */ , { "&sum;", "&#8721;"/* n-ary sumation */, "\u2211" } /* sum is NOT the same character as ,"\u03A3"} */ , { "&minus;", "&#8722;"/* minus sign */, "\u2212" }, { "&lowast;", "&#8727;"/* asterisk operator */, "\u2217" }, { "&radic;", "&#8730;"/* square root = radical sign */, "\u221A" }, { "&prop;", "&#8733;"/* proportional to */, "\u221D" }, { "&infin;", "&#8734;"/* infinity */, "\u221E" }, { "&ang;", "&#8736;"/* angle */, "\u2220" }, { "&and;", "&#8743;"/* logical and = wedge */, "\u2227" }, { "&or;", "&#8744;"/* logical or = vee */, "\u2228" }, { "&cap;", "&#8745;"/* intersection = cap */, "\u2229" }, { "&cup;", "&#8746;"/* union = cup */, "\u222A" }, { "&int;", "&#8747;"/* integral */, "\u222B" }, { "&there4;", "&#8756;"/* therefore */, "\u2234" }, { "&sim;", "&#8764;"/* tilde operator = varies with = similar to */, "\u223C" } /* * tilde operator is NOT the same character as the tilde * ,"\u007E"} */ , { "&cong;", "&#8773;"/* approximately equal to */, "\u2245" }, { "&asymp;", "&#8776;"/* almost equal to = asymptotic to */, "\u2248" }, { "&ne;", "&#8800;"/* not equal to */, "\u2260" }, { "&equiv;", "&#8801;"/* identical to */, "\u2261" }, { "&le;", "&#8804;"/* less-than or equal to */, "\u2264" }, { "&ge;", "&#8805;"/* greater-than or equal to */, "\u2265" }, { "&sub;", "&#8834;"/* subset of */, "\u2282" }, { "&sup;", "&#8835;"/* superset of */, "\u2283" } /* note that nsup 'not a superset of ,"\u2283"} */ , { "&sube;", "&#8838;"/* subset of or equal to */, "\u2286" }, { "&supe;", "&#8839;"/* superset of or equal to */, "\u2287" }, { "&oplus;", "&#8853;"/* circled plus = direct sum */, "\u2295" }, { "&otimes;", "&#8855;"/* circled times = vector product */, "\u2297" }, { "&perp;", "&#8869;"/* up tack = orthogonal to = perpendicular */, "\u22A5" }, { "&sdot;", "&#8901;"/* dot operator */, "\u22C5" } /* * dot operator is NOT the same character as ,"\u00B7"} /* * Miscellaneous Technical */ , { "&lceil;", "&#8968;"/* left ceiling = apl upstile */, "\u2308" }, { "&rceil;", "&#8969;"/* right ceiling */, "\u2309" }, { "&lfloor;", "&#8970;"/* left floor = apl downstile */, "\u230A" }, { "&rfloor;", "&#8971;"/* right floor */, "\u230B" }, { "&lang;", "&#9001;"/* left-pointing angle bracket = bra */, "\u2329" } /* lang is NOT the same character as ,"\u003C"} */ , { "&rang;", "&#9002;"/* right-pointing angle bracket = ket */, "\u232A" } /* rang is NOT the same character as ,"\u003E"} */ /* Geometric Shapes */ , { "&loz;", "&#9674;"/* lozenge */, "\u25CA" } /* Miscellaneous Symbols */ , { "&spades;", "&#9824;"/* black spade suit */, "\u2660" } /* black here seems to mean filled as opposed to hollow */ , { "&clubs;", "&#9827;"/* black club suit = shamrock */, "\u2663" }, { "&hearts;", "&#9829;"/* black heart suit = valentine */, "\u2665" }, { "&diams;", "&#9830;"/* black diamond suit */, "\u2666" }, { "&quot;", "&#34;" /* quotation mark = APL quote */, "\"" }, { "&amp;", "&#38;" /* ampersand */, "\u0026" }, { "&lt;", "&#60;" /* less-than sign */, "\u003C" }, { "&gt;", "&#62;" /* greater-than sign */, "\u003E" } /* Latin Extended-A */ , { "&OElig;", "&#338;" /* latin capital ligature OE */, "\u0152" }, { "&oelig;", "&#339;" /* latin small ligature oe */, "\u0153" } /* * ligature is a misnomer this is a separate character in some * languages */ , { "&Scaron;", "&#352;" /* latin capital letter S with caron */, "\u0160" }, { "&scaron;", "&#353;" /* latin small letter s with caron */, "\u0161" }, { "&Yuml;", "&#376;" /* latin capital letter Y with diaeresis */, "\u0178" } /* Spacing Modifier Letters */ , { "&circ;", "&#710;" /* modifier letter circumflex accent */, "\u02C6" }, { "&tilde;", "&#732;" /* small tilde */, "\u02DC" } /* General Punctuation */ , { "&ensp;", "&#8194;"/* en space */, "\u2002" }, { "&emsp;", "&#8195;"/* em space */, "\u2003" }, { "&thinsp;", "&#8201;"/* thin space */, "\u2009" }, { "&zwnj;", "&#8204;"/* zero width non-joiner */, "\u200C" }, { "&zwj;", "&#8205;"/* zero width joiner */, "\u200D" }, { "&lrm;", "&#8206;"/* left-to-right mark */, "\u200E" }, { "&rlm;", "&#8207;"/* right-to-left mark */, "\u200F" }, { "&ndash;", "&#8211;"/* en dash */, "\u2013" }, { "&mdash;", "&#8212;"/* em dash */, "\u2014" }, { "&lsquo;", "&#8216;"/* left single quotation mark */, "\u2018" }, { "&rsquo;", "&#8217;"/* right single quotation mark */, "\u2019" }, { "&sbquo;", "&#8218;"/* single low-9 quotation mark */, "\u201A" }, { "&ldquo;", "&#8220;"/* left double quotation mark */, "\u201C" }, { "&rdquo;", "&#8221;"/* right double quotation mark */, "\u201D" }, { "&bdquo;", "&#8222;"/* double low-9 quotation mark */, "\u201E" }, { "&dagger;", "&#8224;"/* dagger */, "\u2020" }, { "&Dagger;", "&#8225;"/* double dagger */, "\u2021" }, { "&permil;", "&#8240;"/* per mille sign */, "\u2030" }, { "&lsaquo;", "&#8249;"/* * single left-pointing angle quotation * mark */, "\u2039" } /* lsaquo is proposed but not yet ISO standardized */ , { "&rsaquo;", "&#8250;"/* * single right-pointing angle quotation * mark */, "\u203A" } /* rsaquo is proposed but not yet ISO standardized */ , { "&euro;", "&#8364;" /* euro sign */, "\u20AC" } }; for (String[] entity : entities) { entityEscapeMap.put(entity[2], entity[0]); escapeEntityMap.put(entity[0], entity[2]); escapeEntityMap.put(entity[1], entity[2]); } } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/http/HTMLEntity.java
Java
asf20
23,227
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid; import android.app.Activity; import android.app.PendingIntent; import android.app.PendingIntent.CanceledException; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.TextUtils; import android.text.method.LinkMovementMethod; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.fanfou.User; import com.ch_linghu.fanfoudroid.http.HttpAuthException; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskFeedback; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.R; //登录页面需要个性化的菜单绑定, 不直接继承 BaseActivity public class LoginActivity extends Activity { private static final String TAG = "LoginActivity"; private static final String SIS_RUNNING_KEY = "running"; private String mUsername; private String mPassword; // Views. private EditText mUsernameEdit; private EditText mPasswordEdit; private TextView mProgressText; private Button mSigninButton; private ProgressDialog dialog; // Preferences. private SharedPreferences mPreferences; // Tasks. private GenericTask mLoginTask; private User user; private TaskListener mLoginTaskListener = new TaskAdapter() { @Override public void onPreExecute(GenericTask task) { onLoginBegin(); } @Override public void onProgressUpdate(GenericTask task, Object param) { updateProgress((String) param); } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { onLoginSuccess(); } else { onLoginFailure(((LoginTask) task).getMsg()); } } @Override public String getName() { // TODO Auto-generated method stub return "Login"; } }; @Override protected void onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate"); super.onCreate(savedInstanceState); // No Title bar requestWindowFeature(Window.FEATURE_NO_TITLE); requestWindowFeature(Window.FEATURE_PROGRESS); mPreferences = PreferenceManager.getDefaultSharedPreferences(this); setContentView(R.layout.login); // TextView中嵌入HTML链接 TextView registerLink = (TextView) findViewById(R.id.register_link); registerLink.setMovementMethod(LinkMovementMethod.getInstance()); mUsernameEdit = (EditText) findViewById(R.id.username_edit); mPasswordEdit = (EditText) findViewById(R.id.password_edit); // mUsernameEdit.setOnKeyListener(enterKeyHandler); mPasswordEdit.setOnKeyListener(enterKeyHandler); mProgressText = (TextView) findViewById(R.id.progress_text); mProgressText.setFreezesText(true); mSigninButton = (Button) findViewById(R.id.signin_button); if (savedInstanceState != null) { if (savedInstanceState.containsKey(SIS_RUNNING_KEY)) { if (savedInstanceState.getBoolean(SIS_RUNNING_KEY)) { Log.d(TAG, "Was previously logging in. Restart action."); doLogin(); } } } mSigninButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { doLogin(); } }); } @Override protected void onDestroy() { Log.d(TAG, "onDestory"); if (mLoginTask != null && mLoginTask.getStatus() == GenericTask.Status.RUNNING) { mLoginTask.cancel(true); } // dismiss dialog before destroy // to avoid android.view.WindowLeaked Exception TaskFeedback.getInstance(TaskFeedback.DIALOG_MODE, LoginActivity.this) .cancel(); super.onDestroy(); } @Override protected void onStop() { Log.d(TAG, "onStop"); // TODO Auto-generated method stub super.onStop(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mLoginTask != null && mLoginTask.getStatus() == GenericTask.Status.RUNNING) { // If the task was running, want to start it anew when the // Activity restarts. // This addresses the case where you user changes orientation // in the middle of execution. outState.putBoolean(SIS_RUNNING_KEY, true); } } // UI helpers. private void updateProgress(String progress) { mProgressText.setText(progress); } private void enableLogin() { mUsernameEdit.setEnabled(true); mPasswordEdit.setEnabled(true); mSigninButton.setEnabled(true); } private void disableLogin() { mUsernameEdit.setEnabled(false); mPasswordEdit.setEnabled(false); mSigninButton.setEnabled(false); } // Login task. private void doLogin() { mUsername = mUsernameEdit.getText().toString(); mPassword = mPasswordEdit.getText().toString(); if (mLoginTask != null && mLoginTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { if (!TextUtils.isEmpty(mUsername) & !TextUtils.isEmpty(mPassword)) { mLoginTask = new LoginTask(); mLoginTask.setListener(mLoginTaskListener); TaskParams params = new TaskParams(); params.put("username", mUsername); params.put("password", mPassword); mLoginTask.execute(params); } else { updateProgress(getString(R.string.login_status_null_username_or_password)); } } } private void onLoginBegin() { disableLogin(); TaskFeedback.getInstance(TaskFeedback.DIALOG_MODE, LoginActivity.this) .start(getString(R.string.login_status_logging_in)); } private void onLoginSuccess() { TaskFeedback.getInstance(TaskFeedback.DIALOG_MODE, LoginActivity.this) .success(""); updateProgress(""); mUsernameEdit.setText(""); mPasswordEdit.setText(""); Log.d(TAG, "Storing credentials."); TwitterApplication.mApi.setCredentials(mUsername, mPassword); Intent intent = getIntent().getParcelableExtra(Intent.EXTRA_INTENT); String action = intent.getAction(); if (intent.getAction() == null || !Intent.ACTION_SEND.equals(action)) { // We only want to reuse the intent if it was photo send. // Or else default to the main activity. intent = new Intent(this, TwitterActivity.class); } // 发送消息给widget Intent reflogin = new Intent(this.getBaseContext(), FanfouWidget.class); reflogin.setAction("android.appwidget.action.APPWIDGET_UPDATE"); PendingIntent l = PendingIntent.getBroadcast(this.getBaseContext(), 0, reflogin, PendingIntent.FLAG_UPDATE_CURRENT); try { l.send(); } catch (CanceledException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 发送消息给widget_small Intent reflogin2 = new Intent(this.getBaseContext(), FanfouWidgetSmall.class); reflogin2.setAction("android.appwidget.action.APPWIDGET_UPDATE"); PendingIntent l2 = PendingIntent.getBroadcast(this.getBaseContext(), 0, reflogin2, PendingIntent.FLAG_UPDATE_CURRENT); try { l2.send(); } catch (CanceledException e) { // TODO Auto-generated catch block e.printStackTrace(); } startActivity(intent); finish(); } private void onLoginFailure(String reason) { TaskFeedback.getInstance(TaskFeedback.DIALOG_MODE, LoginActivity.this) .failed(reason); enableLogin(); } private class LoginTask extends GenericTask { private String msg = getString(R.string.login_status_failure); public String getMsg() { return msg; } @Override protected TaskResult _doInBackground(TaskParams... params) { TaskParams param = params[0]; publishProgress(getString(R.string.login_status_logging_in) + "..."); try { String username = param.getString("username"); String password = param.getString("password"); user = TwitterApplication.mApi.login(username, password); TwitterApplication.getMyselfId(true); TwitterApplication.getMyselfName(true); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); // TODO:确切的应该从HttpException中返回的消息中获取错误信息 // Throwable cause = e.getCause(); // Maybe null // if (cause instanceof HttpAuthException) { if (e instanceof HttpAuthException) { // Invalid userName/password msg = getString(R.string.login_status_invalid_username_or_password); } else { msg = getString(R.string.login_status_network_or_connection_error); } publishProgress(msg); return TaskResult.FAILED; } SharedPreferences.Editor editor = mPreferences.edit(); editor.putString(Preferences.USERNAME_KEY, mUsername); editor.putString(Preferences.PASSWORD_KEY, encryptPassword(mPassword)); // add 存储当前用户的id editor.putString(Preferences.CURRENT_USER_ID, user.getId()); editor.commit(); return TaskResult.OK; } } private View.OnKeyListener enterKeyHandler = new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { if (event.getAction() == KeyEvent.ACTION_UP) { doLogin(); } return true; } return false; } }; public static String encryptPassword(String password) { // return Base64.encodeToString(password.getBytes(), Base64.DEFAULT); return password; } public static String decryptPassword(String password) { // return new String(Base64.decode(password, Base64.DEFAULT)); return password; } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/LoginActivity.java
Java
asf20
10,605
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.Menu; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.db.StatusTable; import com.ch_linghu.fanfoudroid.fanfou.Paging; import com.ch_linghu.fanfoudroid.fanfou.Status; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity; import com.ch_linghu.fanfoudroid.R; //TODO: 数据来源换成 getFavorites() public class FavoritesActivity extends TwitterCursorBaseActivity { private static final String TAG = "FavoritesActivity"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FAVORITES"; private static final String USER_ID = "userid"; private static final String USER_NAME = "userName"; private static final int DIALOG_WRITE_ID = 0; private String userId = null; private String userName = null; private int currentPage = 1; public static Intent createIntent(String userId, String userName) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra(USER_ID, userId); intent.putExtra(USER_NAME, userName); return intent; } @Override protected boolean _onCreate(Bundle savedInstanceState) { if (super._onCreate(savedInstanceState)) { mNavbar.setHeaderTitle(getActivityTitle()); return true; } else { return false; } } public static Intent createNewTaskIntent(String userId, String userName) { Intent intent = createIntent(userId, userName); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); return intent; } // Menu. @Override public boolean onCreateOptionsMenu(Menu menu) { return super.onCreateOptionsMenu(menu); } @Override protected Cursor fetchMessages() { // TODO Auto-generated method stub return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_FAVORITE); } @Override protected String getActivityTitle() { // TODO Auto-generated method stub String template = getString(R.string.page_title_favorites); String who; if (getUserId().equals(TwitterApplication.getMyselfId(false))) { who = "我"; } else { who = getUserName(); } return MessageFormat.format(template, who); } @Override protected void markAllRead() { // TODO Auto-generated method stub getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_FAVORITE); } // hasRetrieveListTask interface @Override public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) { return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_FAVORITE, isUnread); } @Override public String fetchMaxId() { return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_FAVORITE); } @Override public List<Status> getMessageSinceId(String maxId) throws HttpException { getDb().gc(getUserId(), StatusTable.TYPE_FAVORITE); currentPage = 1; Paging paging = new Paging(currentPage, 20); return getApi().getFavorites(getUserId(), paging); } @Override public String fetchMinId() { return getDb().fetchMinTweetId(getUserId(), StatusTable.TYPE_FAVORITE); } @Override public List<Status> getMoreMessageFromId(String minId) throws HttpException { ++currentPage; Paging paging = new Paging(currentPage, 20); return getApi().getFavorites(getUserId(), paging); } @Override public int getDatabaseType() { return StatusTable.TYPE_FAVORITE; } @Override public String getUserId() { Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null) { userId = extras.getString(USER_ID); } else { userId = TwitterApplication.getMyselfId(false); } return userId; } public String getUserName() { Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null) { userName = extras.getString(USER_NAME); } else { userName = TwitterApplication.getMyselfName(false); } return userName; } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/FavoritesActivity.java
Java
asf20
4,647
package com.ch_linghu.fanfoudroid; import java.util.ArrayList; import java.util.List; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ListView; import android.widget.ProgressBar; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.fanfou.Paging; import com.ch_linghu.fanfoudroid.fanfou.User; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.HttpRefusedException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.base.TwitterListBaseActivity; import com.ch_linghu.fanfoudroid.ui.module.Feedback; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType; import com.ch_linghu.fanfoudroid.ui.module.TweetArrayAdapter; import com.ch_linghu.fanfoudroid.R; import com.markupartist.android.widget.PullToRefreshListView; import com.markupartist.android.widget.PullToRefreshListView.OnRefreshListener; public class UserTimelineActivity extends TwitterListBaseActivity { private static class State { State(UserTimelineActivity activity) { mTweets = activity.mTweets; mMaxId = activity.mMaxId; } public ArrayList<Tweet> mTweets; public String mMaxId; } private static final String TAG = UserTimelineActivity.class .getSimpleName(); private Feedback mFeedback; private static final String EXTRA_USERID = "userID"; private static final String EXTRA_NAME_SHOW = "showName"; private static final String SIS_RUNNING_KEY = "running"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.USERTIMELINE"; public static Intent createIntent(String userID, String showName) { Intent intent = new Intent(LAUNCH_ACTION); intent.putExtra(EXTRA_USERID, userID); intent.putExtra(EXTRA_NAME_SHOW, showName); return intent; } // State. private User mUser; private String mUserID; private String mShowName; private ArrayList<Tweet> mTweets = new ArrayList<Tweet>(); private String mMaxId = ""; // Views. private View footerView; private PullToRefreshListView mTweetList; private ProgressBar loadMoreGIF; private TweetArrayAdapter mAdapter; // 记录服务器拒绝访问的信息 private String msg; private static final int LOADINGFLAG = 1; private static final int SUCCESSFLAG = 2; private static final int NETWORKERRORFLAG = 3; private static final int AUTHERRORFLAG = 4; // Tasks. private GenericTask mRetrieveTask; private GenericTask mLoadMoreTask; private TaskListener mRetrieveTaskListener = new TaskAdapter() { @Override public void onPreExecute(GenericTask task) { onRetrieveBegin(); } @Override public void onPostExecute(GenericTask task, TaskResult result) { mTweetList.onRefreshComplete(); if (result == TaskResult.AUTH_ERROR) { mFeedback.failed("登录失败, 请重新登录."); return; } else if (result == TaskResult.OK) { draw(); goTop(); } else if (result == TaskResult.IO_ERROR) { mFeedback.failed("更新失败."); } mFeedback.success(""); } @Override public String getName() { return "UserTimelineRetrieve"; } }; private TaskListener mLoadMoreTaskListener = new TaskAdapter() { @Override public void onPreExecute(GenericTask task) { loadMoreGIF.setVisibility(View.VISIBLE); onLoadMoreBegin(); } @Override public void onPostExecute(GenericTask task, TaskResult result) { loadMoreGIF.setVisibility(View.GONE); if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { mFeedback.success(""); draw(); } } @Override public String getName() { return "UserTimelineLoadMoreTask"; } }; @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "_onCreate()..."); if (super._onCreate(savedInstanceState)) { mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS); Intent intent = getIntent(); // get user id mUserID = intent.getStringExtra(EXTRA_USERID); // show username in title mShowName = intent.getStringExtra(EXTRA_NAME_SHOW); // Set header title mNavbar.setHeaderTitle("@" + mShowName); boolean wasRunning = isTrue(savedInstanceState, SIS_RUNNING_KEY); State state = (State) getLastNonConfigurationInstance(); if (state != null) { // 此处要求mTweets不为空,最好确保profile页面消息为0时不能进入这个页面 mTweets = state.mTweets; mMaxId = state.mMaxId; if (!mTweets.isEmpty() && !wasRunning) { draw(); } } else { doRetrieve(); } return true; } else { return false; } } @Override protected void onResume() { super.onResume(); checkIsLogedIn(); } @Override public Object onRetainNonConfigurationInstance() { return createState(); } private synchronized State createState() { return new State(this); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } @Override protected void onDestroy() { Log.d(TAG, "onDestroy."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { mRetrieveTask.cancel(true); } if (mLoadMoreTask != null && mLoadMoreTask.getStatus() == GenericTask.Status.RUNNING) { mLoadMoreTask.cancel(true); } super.onDestroy(); } @Override protected void draw() { mAdapter.refresh(mTweets); } public void goTop() { Log.d(TAG, "goTop."); mTweetList.setSelection(1); } public void doRetrieve() { Log.d(TAG, "Attempting retrieve."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mRetrieveTask = new UserTimelineRetrieveTask(); mRetrieveTask.setListener(mRetrieveTaskListener); mRetrieveTask.execute(); } } private void doLoadMore() { Log.d(TAG, "Attempting load more."); if (mLoadMoreTask != null && mLoadMoreTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mLoadMoreTask = new UserTimelineLoadMoreTask(); mLoadMoreTask.setListener(mLoadMoreTaskListener); mLoadMoreTask.execute(); } } private void onRetrieveBegin() { mFeedback.start(""); mTweetList.prepareForRefresh(); // 更新查询状态显示 } private void onLoadMoreBegin() { mFeedback.start(""); } private class UserTimelineRetrieveTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList; try { statusList = getApi().getUserTimeline(mUserID); mUser = getApi().showUser(mUserID); mFeedback.update(60); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); Throwable cause = e.getCause(); if (cause instanceof HttpRefusedException) { // AUTH ERROR msg = ((HttpRefusedException) cause).getError() .getMessage(); return TaskResult.AUTH_ERROR; } else { return TaskResult.IO_ERROR; } } mFeedback.update(100 - (int) Math.floor(statusList.size() * 2)); // 60~100 mTweets.clear(); for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) { if (isCancelled()) { return TaskResult.CANCELLED; } Tweet tweet; tweet = Tweet.create(status); mMaxId = tweet.id; mTweets.add(tweet); if (isCancelled()) { return TaskResult.CANCELLED; } } if (isCancelled()) { return TaskResult.CANCELLED; } return TaskResult.OK; } } private class UserTimelineLoadMoreTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList; try { Paging paging = new Paging(); paging.setMaxId(mMaxId); statusList = getApi().getUserTimeline(mUserID, paging); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); Throwable cause = e.getCause(); if (cause instanceof HttpRefusedException) { // AUTH ERROR msg = ((HttpRefusedException) cause).getError() .getMessage(); return TaskResult.AUTH_ERROR; } else { return TaskResult.IO_ERROR; } } for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) { if (isCancelled()) { return TaskResult.CANCELLED; } Tweet tweet; tweet = Tweet.create(status); mMaxId = tweet.id; mTweets.add(tweet); } if (isCancelled()) { return TaskResult.CANCELLED; } if (isCancelled()) { return TaskResult.CANCELLED; } return TaskResult.OK; } } public void doGetMore() { doLoadMore(); } @Override protected String getActivityTitle() { return "@" + mShowName; } @Override protected Tweet getContextItemTweet(int position) { if (position >= 1 && position <= mAdapter.getCount()) { return (Tweet) mAdapter.getItem(position - 1); } else { return null; } } @Override protected int getLayoutId() { return R.layout.user_timeline; } @Override protected com.ch_linghu.fanfoudroid.ui.module.TweetAdapter getTweetAdapter() { return mAdapter; } @Override protected ListView getTweetList() { return mTweetList; } @Override protected void setupState() { mTweets = new ArrayList<Tweet>(); mAdapter = new TweetArrayAdapter(this); mTweetList = (PullToRefreshListView) findViewById(R.id.tweet_list); mTweetList.setAdapter(mAdapter); mTweetList.setOnRefreshListener(new OnRefreshListener(){ @Override public void onRefresh(){ doRetrieve(); } }); // Add Footer to ListView footerView = (View)View.inflate(this, R.layout.listview_footer, null); mTweetList.addFooterView(footerView); loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar); } @Override protected void updateTweet(Tweet tweet) { // 该方法作用? } @Override protected boolean useBasicMenu() { return true; } @Override protected void specialItemClicked(int position) { // 注意 mTweetAdapter.getCount 和 mTweetList.getCount的区别 // 前者仅包含数据的数量(不包括foot和head),后者包含foot和head // 因此在同时存在foot和head的情况下,list.count = adapter.count + 2 if (position == 0) { doRetrieve(); } else if (position == mTweetList.getCount() - 1) { // 最后一个Item(footer) doGetMore(); } } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/UserTimelineActivity.java
Java
asf20
11,270
package com.ch_linghu.fanfoudroid; import java.util.ArrayList; import java.util.List; import android.database.Cursor; import android.os.Bundle; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.db.StatusTable; import com.ch_linghu.fanfoudroid.fanfou.Status; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity; import com.ch_linghu.fanfoudroid.R; /** * 随便看看 * * @author jmx * */ public class BrowseActivity extends TwitterCursorBaseActivity { private static final String TAG = "BrowseActivity"; @Override protected boolean _onCreate(Bundle savedInstanceState) { if (super._onCreate(savedInstanceState)) { mNavbar.setHeaderTitle(getActivityTitle()); getTweetList().removeFooterView(mListFooter); // 随便看看没有获取更多功能 return true; } else { return false; } } @Override protected String getActivityTitle() { return getResources().getString(R.string.page_title_browse); } @Override public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) { return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_BROWSE, isUnread); } @Override public String fetchMaxId() { return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_BROWSE); } @Override protected Cursor fetchMessages() { return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_BROWSE); } @Override public List<Status> getMessageSinceId(String maxId) throws HttpException { return getApi().getPublicTimeline(); } @Override protected void markAllRead() { getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_BROWSE); } @Override public String fetchMinId() { // 随便看看没有获取更多的功能 return null; } @Override public List<Status> getMoreMessageFromId(String minId) throws HttpException { // 随便看看没有获取更多的功能 return null; } @Override public int getDatabaseType() { return StatusTable.TYPE_BROWSE; } @Override public String getUserId() { return TwitterApplication.getMyselfId(false); } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/BrowseActivity.java
Java
asf20
2,120
package com.ch_linghu.fanfoudroid.task; import android.app.ProgressDialog; import android.content.Context; import android.util.Log; import android.widget.Toast; import com.ch_linghu.fanfoudroid.ui.base.WithHeaderActivity; public abstract class TaskFeedback { private static TaskFeedback _instance = null; public static final int DIALOG_MODE = 0x01; public static final int REFRESH_MODE = 0x02; public static final int PROGRESS_MODE = 0x03; public static TaskFeedback getInstance(int type, Context context) { switch (type) { case DIALOG_MODE: _instance = DialogFeedback.getInstance(); break; case REFRESH_MODE: _instance = RefreshAnimationFeedback.getInstance(); break; case PROGRESS_MODE: _instance = ProgressBarFeedback.getInstance(); } _instance.setContext(context); return _instance; } protected Context _context; protected void setContext(Context context) { _context = context; } public Context getContent() { return _context; } // default do nothing public void start(String prompt) { }; public void cancel() { }; public void success(String prompt) { }; public void success() { success(""); }; public void failed(String prompt) { }; public void showProgress(int progress) { }; } /** * */ class DialogFeedback extends TaskFeedback { private static DialogFeedback _instance = null; public static DialogFeedback getInstance() { if (_instance == null) { _instance = new DialogFeedback(); } return _instance; } private ProgressDialog _dialog = null; @Override public void cancel() { if (_dialog != null) { _dialog.dismiss(); } } @Override public void failed(String prompt) { if (_dialog != null) { _dialog.dismiss(); } Toast toast = Toast.makeText(_context, prompt, Toast.LENGTH_LONG); toast.show(); } @Override public void start(String prompt) { _dialog = ProgressDialog.show(_context, "", prompt, true); _dialog.setCancelable(true); } @Override public void success(String prompt) { if (_dialog != null) { _dialog.dismiss(); } } } /** * */ class RefreshAnimationFeedback extends TaskFeedback { private static RefreshAnimationFeedback _instance = null; public static RefreshAnimationFeedback getInstance() { if (_instance == null) { _instance = new RefreshAnimationFeedback(); } return _instance; } private WithHeaderActivity _activity; @Override protected void setContext(Context context) { super.setContext(context); _activity = (WithHeaderActivity) context; } @Override public void cancel() { _activity.setRefreshAnimation(false); } @Override public void failed(String prompt) { _activity.setRefreshAnimation(false); Toast toast = Toast.makeText(_context, prompt, Toast.LENGTH_LONG); toast.show(); } @Override public void start(String prompt) { _activity.setRefreshAnimation(true); } @Override public void success(String prompt) { _activity.setRefreshAnimation(false); } } /** * */ class ProgressBarFeedback extends TaskFeedback { private static ProgressBarFeedback _instance = null; public static ProgressBarFeedback getInstance() { if (_instance == null) { _instance = new ProgressBarFeedback(); } return _instance; } private WithHeaderActivity _activity; @Override protected void setContext(Context context) { super.setContext(context); _activity = (WithHeaderActivity) context; } @Override public void cancel() { _activity.setGlobalProgress(0); } @Override public void failed(String prompt) { cancel(); Toast toast = Toast.makeText(_context, prompt, Toast.LENGTH_LONG); toast.show(); } @Override public void start(String prompt) { _activity.setGlobalProgress(10); } @Override public void success(String prompt) { Log.d("LDS", "ON SUCCESS"); _activity.setGlobalProgress(0); } @Override public void showProgress(int progress) { _activity.setGlobalProgress(progress); } // mProgress.setIndeterminate(true); }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/task/TaskFeedback.java
Java
asf20
3,972
package com.ch_linghu.fanfoudroid.task; import java.util.HashMap; import org.json.JSONException; import com.ch_linghu.fanfoudroid.http.HttpException; /** * 暂未使用,待观察是否今后需要此类 * * @author lds * */ public class TaskParams { private HashMap<String, Object> params = null; public TaskParams() { params = new HashMap<String, Object>(); } public TaskParams(String key, Object value) { this(); put(key, value); } public void put(String key, Object value) { params.put(key, value); } public Object get(String key) { return params.get(key); } /** * Get the boolean value associated with a key. * * @param key * A key string. * @return The truth. * @throws HttpException * if the value is not a Boolean or the String "true" or * "false". */ public boolean getBoolean(String key) throws HttpException { Object object = get(key); if (object.equals(Boolean.FALSE) || (object instanceof String && ((String) object) .equalsIgnoreCase("false"))) { return false; } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String) object) .equalsIgnoreCase("true"))) { return true; } throw new HttpException(key + " is not a Boolean."); } /** * Get the double value associated with a key. * * @param key * A key string. * @return The numeric value. * @throws HttpException * if the key is not found or if the value is not a Number * object and cannot be converted to a number. */ public double getDouble(String key) throws HttpException { Object object = get(key); try { return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object); } catch (Exception e) { throw new HttpException(key + " is not a number."); } } /** * Get the int value associated with a key. * * @param key * A key string. * @return The integer value. * @throws HttpException * if the key is not found or if the value cannot be converted * to an integer. */ public int getInt(String key) throws HttpException { Object object = get(key); try { return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object); } catch (Exception e) { throw new HttpException(key + " is not an int."); } } /** * Get the string associated with a key. * * @param key * A key string. * @return A string which is the value. * @throws JSONException * if the key is not found. */ public String getString(String key) throws HttpException { Object object = get(key); return object == null ? null : object.toString(); } /** * Determine if the JSONObject contains a specific key. * * @param key * A key string. * @return true if the key exists in the JSONObject. */ public boolean has(String key) { return this.params.containsKey(key); } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/task/TaskParams.java
Java
asf20
3,044
package com.ch_linghu.fanfoudroid.task; import android.util.Log; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.db.StatusTable; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.ui.base.BaseActivity; public class TweetCommonTask { public static class DeleteTask extends GenericTask { public static final String TAG = "DeleteTask"; private BaseActivity activity; public DeleteTask(BaseActivity activity) { this.activity = activity; } @Override protected TaskResult _doInBackground(TaskParams... params) { TaskParams param = params[0]; try { String id = param.getString("id"); com.ch_linghu.fanfoudroid.fanfou.Status status = null; status = activity.getApi().destroyStatus(id); // 对所有相关表的对应消息都进行删除(如果存在的话) activity.getDb().deleteTweet(status.getId(), "", -1); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } return TaskResult.OK; } } public static class FavoriteTask extends GenericTask { private static final String TAG = "FavoriteTask"; private BaseActivity activity; public static final String TYPE_ADD = "add"; public static final String TYPE_DEL = "del"; private String type; public String getType() { return type; } public FavoriteTask(BaseActivity activity) { this.activity = activity; } @Override protected TaskResult _doInBackground(TaskParams... params) { TaskParams param = params[0]; try { String action = param.getString("action"); String id = param.getString("id"); com.ch_linghu.fanfoudroid.fanfou.Status status = null; if (action.equals(TYPE_ADD)) { status = activity.getApi().createFavorite(id); activity.getDb().setFavorited(id, "true"); type = TYPE_ADD; } else { status = activity.getApi().destroyFavorite(id); activity.getDb().setFavorited(id, "false"); type = TYPE_DEL; } Tweet tweet = Tweet.create(status); // if (!Utils.isEmpty(tweet.profileImageUrl)) { // // Fetch image to cache. // try { // activity.getImageManager().put(tweet.profileImageUrl); // } catch (IOException e) { // Log.e(TAG, e.getMessage(), e); // } // } if (action.equals(TYPE_DEL)) { activity.getDb().deleteTweet(tweet.id, TwitterApplication.getMyselfId(false), StatusTable.TYPE_FAVORITE); } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } return TaskResult.OK; } } // public static class UserTask extends GenericTask{ // // @Override // protected TaskResult _doInBackground(TaskParams... params) { // // TODO Auto-generated method stub // return null; // } // // } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/task/TweetCommonTask.java
Java
asf20
2,875
package com.ch_linghu.fanfoudroid.task; public interface TaskListener { String getName(); void onPreExecute(GenericTask task); void onPostExecute(GenericTask task, TaskResult result); void onProgressUpdate(GenericTask task, Object param); void onCancelled(GenericTask task); }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/task/TaskListener.java
Java
asf20
287
package com.ch_linghu.fanfoudroid.task; import java.util.Observable; import java.util.Observer; import android.util.Log; public class TaskManager extends Observable { private static final String TAG = "TaskManager"; public static final Integer CANCEL_ALL = 1; public void cancelAll() { Log.d(TAG, "All task Cancelled."); setChanged(); notifyObservers(CANCEL_ALL); } public void addTask(Observer task) { super.addObserver(task); } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/task/TaskManager.java
Java
asf20
451
package com.ch_linghu.fanfoudroid.task; import java.util.Observable; import java.util.Observer; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.ui.module.Feedback; public abstract class GenericTask extends AsyncTask<TaskParams, Object, TaskResult> implements Observer { private static final String TAG = "TaskManager"; private TaskListener mListener = null; private Feedback mFeedback = null; private boolean isCancelable = true; abstract protected TaskResult _doInBackground(TaskParams... params); public void setListener(TaskListener taskListener) { mListener = taskListener; } public TaskListener getListener() { return mListener; } public void doPublishProgress(Object... values) { super.publishProgress(values); } @Override protected void onCancelled() { super.onCancelled(); if (mListener != null) { mListener.onCancelled(this); } Log.d(TAG, mListener.getName() + " has been Cancelled."); Toast.makeText(TwitterApplication.mContext, mListener.getName() + " has been cancelled", Toast.LENGTH_SHORT); } @Override protected void onPostExecute(TaskResult result) { super.onPostExecute(result); if (mListener != null) { mListener.onPostExecute(this, result); } if (mFeedback != null) { mFeedback.success(""); } /* * Toast.makeText(TwitterApplication.mContext, mListener.getName() + * " completed", Toast.LENGTH_SHORT); */ } @Override protected void onPreExecute() { super.onPreExecute(); if (mListener != null) { mListener.onPreExecute(this); } if (mFeedback != null) { mFeedback.start(""); } } @Override protected void onProgressUpdate(Object... values) { super.onProgressUpdate(values); if (mListener != null) { if (values != null && values.length > 0) { mListener.onProgressUpdate(this, values[0]); } } if (mFeedback != null) { mFeedback.update(values[0]); } } @Override protected TaskResult doInBackground(TaskParams... params) { TaskResult result = _doInBackground(params); if (mFeedback != null) { mFeedback.update(99); } return result; } public void update(Observable o, Object arg) { if (TaskManager.CANCEL_ALL == (Integer) arg && isCancelable) { if (getStatus() == GenericTask.Status.RUNNING) { cancel(true); } } } public void setCancelable(boolean flag) { isCancelable = flag; } public void setFeedback(Feedback feedback) { mFeedback = feedback; } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/task/GenericTask.java
Java
asf20
2,559
package com.ch_linghu.fanfoudroid.task; public abstract class TaskAdapter implements TaskListener { public abstract String getName(); public void onPreExecute(GenericTask task) { }; public void onPostExecute(GenericTask task, TaskResult result) { }; public void onProgressUpdate(GenericTask task, Object param) { }; public void onCancelled(GenericTask task) { }; }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/task/TaskAdapter.java
Java
asf20
380
package com.ch_linghu.fanfoudroid.task; public enum TaskResult { OK, FAILED, CANCELLED, NOT_FOLLOWED_ERROR, IO_ERROR, AUTH_ERROR }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/task/TaskResult.java
Java
asf20
134
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceScreen; import android.util.Log; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.http.HttpClient; import com.ch_linghu.fanfoudroid.ui.module.MyTextView; import com.ch_linghu.fanfoudroid.R; public class PreferencesActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 禁止横屏 if (TwitterApplication.mPref.getBoolean( Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false)) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } // TODO: is this a hack? setResult(RESULT_OK); addPreferencesFromResource(R.xml.preferences); } @Override protected void onResume() { super.onResume(); // Set up a listener whenever a key changes getPreferenceScreen().getSharedPreferences() .registerOnSharedPreferenceChangeListener(this); } @Override public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { return super.onPreferenceTreeClick(preferenceScreen, preference); } public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equalsIgnoreCase(Preferences.NETWORK_TYPE)) { HttpClient httpClient = TwitterApplication.mApi.getHttpClient(); String type = sharedPreferences.getString(Preferences.NETWORK_TYPE, ""); if (type.equalsIgnoreCase(getString(R.string.pref_network_type_cmwap))) { Log.d("LDS", "Set proxy for cmwap mode."); httpClient.setProxy("10.0.0.172", 80, "http"); } else { Log.d("LDS", "No proxy."); httpClient.removeProxy(); } } else if (key.equalsIgnoreCase(Preferences.UI_FONT_SIZE)) { MyTextView.setFontSizeChanged(true); } } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/PreferencesActivity.java
Java
asf20
2,768
package com.ch_linghu.fanfoudroid.db; /** * All information of status table * */ public final class StatusTablesInfo { }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/db/StatusTablesInfo.java
Java
asf20
126
package com.ch_linghu.fanfoudroid.db; import android.database.Cursor; import android.provider.BaseColumns; import android.util.Log; import com.ch_linghu.fanfoudroid.data.User; public final class UserInfoTable implements BaseColumns { public static final String TAG = "UserInfoTable"; public static final String TABLE_NAME = "userinfo"; public static final String FIELD_USER_NAME = "name"; public static final String FIELD_USER_SCREEN_NAME = "screen_name"; public static final String FIELD_LOCALTION = "location"; public static final String FIELD_DESCRIPTION = "description"; public static final String FIELD_PROFILE_IMAGE_URL = "profile_image_url"; public static final String FIELD_URL = "url"; public static final String FIELD_PROTECTED = "protected"; public static final String FIELD_FOLLOWERS_COUNT = "followers_count"; public static final String FIELD_FRIENDS_COUNT = "friends_count"; public static final String FIELD_FAVORITES_COUNT = "favourites_count"; public static final String FIELD_STATUSES_COUNT = "statuses_count"; public static final String FIELD_LAST_STATUS = "last_status"; public static final String FIELD_CREATED_AT = "created_at"; public static final String FIELD_FOLLOWING = "following"; public static final String FIELD_FOLLOWER_IDS = "follower_ids"; public static final String[] TABLE_COLUMNS = new String[] { _ID, FIELD_USER_NAME, FIELD_USER_SCREEN_NAME, FIELD_LOCALTION, FIELD_DESCRIPTION, FIELD_PROFILE_IMAGE_URL, FIELD_URL, FIELD_PROTECTED, FIELD_FOLLOWERS_COUNT, FIELD_FRIENDS_COUNT, FIELD_FAVORITES_COUNT, FIELD_STATUSES_COUNT, FIELD_LAST_STATUS, FIELD_CREATED_AT, FIELD_FOLLOWING }; public static final String CREATE_TABLE = "create table " + TABLE_NAME + " (" + _ID + " text primary key on conflict replace, " + FIELD_USER_NAME + " text not null, " + FIELD_USER_SCREEN_NAME + " text, " + FIELD_LOCALTION + " text, " + FIELD_DESCRIPTION + " text, " + FIELD_PROFILE_IMAGE_URL + " text, " + FIELD_URL + " text, " + FIELD_PROTECTED + " boolean, " + FIELD_FOLLOWERS_COUNT + " integer, " + FIELD_FRIENDS_COUNT + " integer, " + FIELD_FAVORITES_COUNT + " integer, " + FIELD_STATUSES_COUNT + " integer, " + FIELD_LAST_STATUS + " text, " + FIELD_CREATED_AT + " date, " + FIELD_FOLLOWING + " boolean " // +FIELD_FOLLOWER_IDS+" text" + ")"; /** * TODO: 将游标解析为一条用户信息 * * @param cursor * 该方法不会关闭游标 * @return 成功返回User类型的单条数据, 失败返回null */ public static User parseCursor(Cursor cursor) { if (null == cursor || 0 == cursor.getCount()) { Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty."); return null; } User user = new User(); user.id = cursor.getString(cursor.getColumnIndex(_ID)); user.name = cursor.getString(cursor.getColumnIndex(FIELD_USER_NAME)); user.screenName = cursor.getString(cursor .getColumnIndex(FIELD_USER_SCREEN_NAME)); user.location = cursor .getString(cursor.getColumnIndex(FIELD_LOCALTION)); user.description = cursor.getString(cursor .getColumnIndex(FIELD_DESCRIPTION)); user.profileImageUrl = cursor.getString(cursor .getColumnIndex(FIELD_PROFILE_IMAGE_URL)); user.url = cursor.getString(cursor.getColumnIndex(FIELD_URL)); user.isProtected = (0 == cursor.getInt(cursor .getColumnIndex(FIELD_PROTECTED))) ? false : true; user.followersCount = cursor.getInt(cursor .getColumnIndex(FIELD_FOLLOWERS_COUNT)); user.lastStatus = cursor.getString(cursor .getColumnIndex(FIELD_LAST_STATUS)); user.friendsCount = cursor.getInt(cursor .getColumnIndex(FIELD_FRIENDS_COUNT)); user.favoritesCount = cursor.getInt(cursor .getColumnIndex(FIELD_FAVORITES_COUNT)); user.statusesCount = cursor.getInt(cursor .getColumnIndex(FIELD_STATUSES_COUNT)); user.isFollowing = (0 == cursor.getInt(cursor .getColumnIndex(FIELD_FOLLOWING))) ? false : true; // TODO:报空指针异常,待查 // try { // user.createdAt = // StatusDatabase.DB_DATE_FORMATTER.parse(cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_CREATED_AT))); // } catch (ParseException e) { // Log.w(TAG, "Invalid created at data."); // } return user; } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/db/UserInfoTable.java
Java
asf20
4,342
package com.ch_linghu.fanfoudroid.db; import java.text.ParseException; import android.database.Cursor; import android.provider.BaseColumns; import android.util.Log; import com.ch_linghu.fanfoudroid.data.Dm; /** * Table - Direct Messages * */ public final class MessageTable implements BaseColumns { public static final String TAG = "MessageTable"; public static final int TYPE_GET = 0; public static final int TYPE_SENT = 1; public static final String TABLE_NAME = "message"; public static final int MAX_ROW_NUM = 20; public static final String FIELD_USER_ID = "uid"; public static final String FIELD_USER_SCREEN_NAME = "screen_name"; public static final String FIELD_PROFILE_IMAGE_URL = "profile_image_url"; public static final String FIELD_CREATED_AT = "created_at"; public static final String FIELD_TEXT = "text"; public static final String FIELD_IN_REPLY_TO_STATUS_ID = "in_reply_to_status_id"; public static final String FIELD_IN_REPLY_TO_USER_ID = "in_reply_to_user_id"; public static final String FIELD_IN_REPLY_TO_SCREEN_NAME = "in_reply_to_screen_name"; public static final String FIELD_IS_UNREAD = "is_unread"; public static final String FIELD_IS_SENT = "is_send"; public static final String[] TABLE_COLUMNS = new String[] { _ID, FIELD_USER_SCREEN_NAME, FIELD_TEXT, FIELD_PROFILE_IMAGE_URL, FIELD_IS_UNREAD, FIELD_IS_SENT, FIELD_CREATED_AT, FIELD_USER_ID }; public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + _ID + " text primary key on conflict replace, " + FIELD_USER_SCREEN_NAME + " text not null, " + FIELD_TEXT + " text not null, " + FIELD_PROFILE_IMAGE_URL + " text not null, " + FIELD_IS_UNREAD + " boolean not null, " + FIELD_IS_SENT + " boolean not null, " + FIELD_CREATED_AT + " date not null, " + FIELD_USER_ID + " text)"; /** * TODO: 将游标解析为一条私信 * * @param cursor * 该方法不会关闭游标 * @return 成功返回Dm类型的单条数据, 失败返回null */ public static Dm parseCursor(Cursor cursor) { if (null == cursor || 0 == cursor.getCount()) { Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty."); return null; } Dm dm = new Dm(); dm.id = cursor.getString(cursor.getColumnIndex(MessageTable._ID)); dm.screenName = cursor.getString(cursor .getColumnIndex(MessageTable.FIELD_USER_SCREEN_NAME)); dm.text = cursor.getString(cursor .getColumnIndex(MessageTable.FIELD_TEXT)); dm.profileImageUrl = cursor.getString(cursor .getColumnIndex(MessageTable.FIELD_PROFILE_IMAGE_URL)); dm.isSent = (0 == cursor.getInt(cursor .getColumnIndex(MessageTable.FIELD_IS_SENT))) ? false : true; try { dm.createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(cursor .getString(cursor .getColumnIndex(MessageTable.FIELD_CREATED_AT))); } catch (ParseException e) { Log.w(TAG, "Invalid created at data."); } dm.userId = cursor.getString(cursor .getColumnIndex(MessageTable.FIELD_USER_ID)); return dm; } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/db/MessageTable.java
Java
asf20
3,028
package com.ch_linghu.fanfoudroid.db; import android.database.Cursor; import android.provider.BaseColumns; import android.util.Log; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.util.DateTimeHelper; /** * Table - Statuses <br /> * <br /> * 为节省流量,故此表不保证本地数据库中所有消息具有前后连贯性, 而只确保最新的MAX_ROW_NUM条<br /> * 数据的连贯性, 超出部分则视为垃圾数据, 不再允许读取, 也不保证其是前后连续的.<br /> * <br /> * 因为用户可能中途长时间停止使用本客户端,而换其他客户端(如网页), <br /> * 如果保证本地所有数据的连贯性, 那么就必须自动去下载所有本地缺失的中间数据,<br /> * 而这些数据极有可能是用户通过其他客户端阅读过的无用信息, 浪费了用户流量.<br /> * <br /> * 即认为相对于旧信息而言, 新信息对于用户更为价值, 所以只会新信息进行维护, <br /> * 而旧信息一律视为无用的, 如用户需要查看超过MAX_ROW_NUM的旧数据, 可主动点击, <br /> * 从而请求服务器. 本地只缓存最有价值的MAX条最新信息.<br /> * <br /> * 本地数据库中前MAX_ROW_NUM条的数据模拟一个定长列队, 即在尾部插入N条消息, 就会使得头部<br /> * 的N条消息被标记为垃圾数据(但并不立即收回),只有在认为数据库数据过多时,<br /> * 可手动调用 <code>StatusDatabase.gc(int type)</code> 方法进行垃圾清理.<br /> * * */ public final class StatusTable implements BaseColumns { public static final String TAG = "StatusTable"; // Status Types public static final int TYPE_HOME = 1; // 首页(我和我的好友) public static final int TYPE_MENTION = 2; // 提到我的 public static final int TYPE_USER = 3; // 指定USER的 public static final int TYPE_FAVORITE = 4; // 收藏 public static final int TYPE_BROWSE = 5; // 随便看看 public static final String TABLE_NAME = "status"; public static final int MAX_ROW_NUM = 20; // 单类型数据安全区域 public static final String OWNER_ID = "owner"; // 用于标识数据的所有者。以便于处理其他用户的信息(如其他用户的收藏) public static final String USER_ID = "uid"; public static final String USER_SCREEN_NAME = "screen_name"; public static final String PROFILE_IMAGE_URL = "profile_image_url"; public static final String CREATED_AT = "created_at"; public static final String TEXT = "text"; public static final String SOURCE = "source"; public static final String TRUNCATED = "truncated"; public static final String IN_REPLY_TO_STATUS_ID = "in_reply_to_status_id"; public static final String IN_REPLY_TO_USER_ID = "in_reply_to_user_id"; public static final String IN_REPLY_TO_SCREEN_NAME = "in_reply_to_screen_name"; public static final String FAVORITED = "favorited"; public static final String IS_UNREAD = "is_unread"; public static final String STATUS_TYPE = "status_type"; public static final String PIC_THUMB = "pic_thumbnail"; public static final String PIC_MID = "pic_middle"; public static final String PIC_ORIG = "pic_original"; // private static final String FIELD_PHOTO_URL = "photo_url"; // private double latitude = -1; // private double longitude = -1; // private String thumbnail_pic; // private String bmiddle_pic; // private String original_pic; public static final String[] TABLE_COLUMNS = new String[] { _ID, USER_SCREEN_NAME, TEXT, PROFILE_IMAGE_URL, IS_UNREAD, CREATED_AT, FAVORITED, IN_REPLY_TO_STATUS_ID, IN_REPLY_TO_USER_ID, IN_REPLY_TO_SCREEN_NAME, TRUNCATED, PIC_THUMB, PIC_MID, PIC_ORIG, SOURCE, USER_ID, STATUS_TYPE, OWNER_ID }; public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + _ID + " text not null," + STATUS_TYPE + " text not null, " + OWNER_ID + " text not null, " + USER_ID + " text not null, " + USER_SCREEN_NAME + " text not null, " + TEXT + " text not null, " + PROFILE_IMAGE_URL + " text not null, " + IS_UNREAD + " boolean not null, " + CREATED_AT + " date not null, " + SOURCE + " text not null, " + FAVORITED + " text, " // TODO : text -> boolean + IN_REPLY_TO_STATUS_ID + " text, " + IN_REPLY_TO_USER_ID + " text, " + IN_REPLY_TO_SCREEN_NAME + " text, " + PIC_THUMB + " text, " + PIC_MID + " text, " + PIC_ORIG + " text, " + TRUNCATED + " boolean ," + "PRIMARY KEY (" + _ID + "," + OWNER_ID + "," + STATUS_TYPE + "))"; /** * 将游标解析为一条Tweet * * * @param cursor * 该方法不会移动或关闭游标 * @return 成功返回 Tweet 类型的单条数据, 失败返回null */ public static Tweet parseCursor(Cursor cursor) { if (null == cursor || 0 == cursor.getCount()) { Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty."); return null; } else if (-1 == cursor.getPosition()) { cursor.moveToFirst(); } Tweet tweet = new Tweet(); tweet.id = cursor.getString(cursor.getColumnIndex(_ID)); tweet.createdAt = DateTimeHelper.parseDateTimeFromSqlite(cursor .getString(cursor.getColumnIndex(CREATED_AT))); tweet.favorited = cursor.getString(cursor.getColumnIndex(FAVORITED)); tweet.screenName = cursor.getString(cursor .getColumnIndex(USER_SCREEN_NAME)); tweet.userId = cursor.getString(cursor.getColumnIndex(USER_ID)); tweet.text = cursor.getString(cursor.getColumnIndex(TEXT)); tweet.source = cursor.getString(cursor.getColumnIndex(SOURCE)); tweet.profileImageUrl = cursor.getString(cursor .getColumnIndex(PROFILE_IMAGE_URL)); tweet.inReplyToScreenName = cursor.getString(cursor .getColumnIndex(IN_REPLY_TO_SCREEN_NAME)); tweet.inReplyToStatusId = cursor.getString(cursor .getColumnIndex(IN_REPLY_TO_STATUS_ID)); tweet.inReplyToUserId = cursor.getString(cursor .getColumnIndex(IN_REPLY_TO_USER_ID)); tweet.truncated = cursor.getString(cursor.getColumnIndex(TRUNCATED)); tweet.thumbnail_pic = cursor .getString(cursor.getColumnIndex(PIC_THUMB)); tweet.bmiddle_pic = cursor.getString(cursor.getColumnIndex(PIC_MID)); tweet.original_pic = cursor.getString(cursor.getColumnIndex(PIC_ORIG)); tweet.setStatusType(cursor.getInt(cursor.getColumnIndex(STATUS_TYPE))); return tweet; } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/db/StatusTable.java
Java
asf20
6,291
package com.ch_linghu.fanfoudroid.db; import java.text.ParseException; import android.database.Cursor; import android.provider.BaseColumns; import android.util.Log; import com.ch_linghu.fanfoudroid.data.User; /** * Table - Followers * */ public final class FollowTable implements BaseColumns { public static final String TAG = "FollowTable"; public static final String TABLE_NAME = "followers"; public static final String FIELD_USER_NAME = "name"; public static final String FIELD_USER_SCREEN_NAME = "screen_name"; public static final String FIELD_LOCALTION = "location"; public static final String FIELD_DESCRIPTION = "description"; public static final String FIELD_PROFILE_IMAGE_URL = "profile_image_url"; public static final String FIELD_URL = "url"; public static final String FIELD_PROTECTED = "protected"; public static final String FIELD_FOLLOWERS_COUNT = "followers_count"; public static final String FIELD_FRIENDS_COUNT = "friends_count"; public static final String FIELD_FAVORITES_COUNT = "favourites_count"; public static final String FIELD_STATUSES_COUNT = "statuses_count"; public static final String FIELD_LAST_STATUS = "last_status"; public static final String FIELD_CREATED_AT = "created_at"; public static final String FIELD_FOLLOWING = "following"; public static final String[] TABLE_COLUMNS = new String[] { _ID, FIELD_USER_NAME, FIELD_USER_SCREEN_NAME, FIELD_LOCALTION, FIELD_DESCRIPTION, FIELD_PROFILE_IMAGE_URL, FIELD_URL, FIELD_PROTECTED, FIELD_FOLLOWERS_COUNT, FIELD_FRIENDS_COUNT, FIELD_FAVORITES_COUNT, FIELD_STATUSES_COUNT, FIELD_LAST_STATUS, FIELD_CREATED_AT, FIELD_FOLLOWING }; public static final String CREATE_TABLE = "create table " + TABLE_NAME + " (" + _ID + " text primary key on conflict replace, " + FIELD_USER_NAME + " text not null, " + FIELD_USER_SCREEN_NAME + " text, " + FIELD_LOCALTION + " text, " + FIELD_DESCRIPTION + " text, " + FIELD_PROFILE_IMAGE_URL + " text, " + FIELD_URL + " text, " + FIELD_PROTECTED + " boolean, " + FIELD_FOLLOWERS_COUNT + " integer, " + FIELD_FRIENDS_COUNT + " integer, " + FIELD_FAVORITES_COUNT + " integer, " + FIELD_STATUSES_COUNT + " integer, " + FIELD_LAST_STATUS + " text, " + FIELD_CREATED_AT + " date, " + FIELD_FOLLOWING + " boolean " + ")"; /** * TODO: 将游标解析为一条用户信息 * * @param cursor * 该方法不会关闭游标 * @return 成功返回User类型的单条数据, 失败返回null */ public static User parseCursor(Cursor cursor) { if (null == cursor || 0 == cursor.getCount()) { Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty."); return null; } User user = new User(); user.id = cursor.getString(cursor.getColumnIndex(FollowTable._ID)); user.name = cursor.getString(cursor .getColumnIndex(FollowTable.FIELD_USER_NAME)); user.screenName = cursor.getString(cursor .getColumnIndex(FollowTable.FIELD_USER_SCREEN_NAME)); user.location = cursor.getString(cursor .getColumnIndex(FollowTable.FIELD_LOCALTION)); user.description = cursor.getString(cursor .getColumnIndex(FollowTable.FIELD_DESCRIPTION)); user.profileImageUrl = cursor.getString(cursor .getColumnIndex(FollowTable.FIELD_PROFILE_IMAGE_URL)); user.url = cursor.getString(cursor .getColumnIndex(FollowTable.FIELD_URL)); user.isProtected = (0 == cursor.getInt(cursor .getColumnIndex(FollowTable.FIELD_PROTECTED))) ? false : true; user.followersCount = cursor.getInt(cursor .getColumnIndex(FollowTable.FIELD_FOLLOWERS_COUNT)); user.lastStatus = cursor.getString(cursor .getColumnIndex(FollowTable.FIELD_LAST_STATUS)); ; user.friendsCount = cursor.getInt(cursor .getColumnIndex(FollowTable.FIELD_FRIENDS_COUNT)); user.favoritesCount = cursor.getInt(cursor .getColumnIndex(FollowTable.FIELD_FAVORITES_COUNT)); user.statusesCount = cursor.getInt(cursor .getColumnIndex(FollowTable.FIELD_STATUSES_COUNT)); user.isFollowing = (0 == cursor.getInt(cursor .getColumnIndex(FollowTable.FIELD_FOLLOWING))) ? false : true; try { user.createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(cursor .getString(cursor .getColumnIndex(MessageTable.FIELD_CREATED_AT))); } catch (ParseException e) { Log.w(TAG, "Invalid created at data."); } return user; } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/db/FollowTable.java
Java
asf20
4,341
package com.ch_linghu.fanfoudroid.db; import java.io.File; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.List; import java.util.Locale; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import android.text.TextUtils; import android.util.Log; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.dao.StatusDAO; import com.ch_linghu.fanfoudroid.data.Dm; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.fanfou.Status; import com.ch_linghu.fanfoudroid.util.DebugTimer; /** * A Database which contains all statuses and direct-messages, use * getInstane(Context) to get a new instance * */ public class TwitterDatabase { private static final String TAG = "TwitterDatabase"; private static final String DATABASE_NAME = "status_db"; private static final int DATABASE_VERSION = 1; private static TwitterDatabase instance = null; private static DatabaseHelper mOpenHelper = null; private Context mContext = null; /** * SQLiteOpenHelper * */ private static class DatabaseHelper extends SQLiteOpenHelper { // Construct public DatabaseHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } public DatabaseHelper(Context context, String name) { this(context, name, DATABASE_VERSION); } public DatabaseHelper(Context context) { this(context, DATABASE_NAME, DATABASE_VERSION); } public DatabaseHelper(Context context, int version) { this(context, DATABASE_NAME, null, version); } public DatabaseHelper(Context context, String name, int version) { this(context, name, null, version); } @Override public void onCreate(SQLiteDatabase db) { Log.d(TAG, "Create Database."); // Log.d(TAG, StatusTable.STATUS_TABLE_CREATE); db.execSQL(StatusTable.CREATE_TABLE); db.execSQL(MessageTable.CREATE_TABLE); db.execSQL(FollowTable.CREATE_TABLE); // 2011.03.01 add beta db.execSQL(UserInfoTable.CREATE_TABLE); } @Override public synchronized void close() { Log.d(TAG, "Close Database."); super.close(); } @Override public void onOpen(SQLiteDatabase db) { Log.d(TAG, "Open Database."); super.onOpen(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.d(TAG, "Upgrade Database."); dropAllTables(db); } private void dropAllTables(SQLiteDatabase db) { db.execSQL("DROP TABLE IF EXISTS " + StatusTable.TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + MessageTable.TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + FollowTable.TABLE_NAME); // 2011.03.01 add db.execSQL("DROP TABLE IF EXISTS " + UserInfoTable.TABLE_NAME); } } private TwitterDatabase(Context context) { mContext = context; mOpenHelper = new DatabaseHelper(context); } public static synchronized TwitterDatabase getInstance(Context context) { if (null == instance) { return new TwitterDatabase(context); } return instance; } // 测试用 public SQLiteOpenHelper getSQLiteOpenHelper() { return mOpenHelper; } public static SQLiteDatabase getDb(boolean writeable) { if (writeable) { return mOpenHelper.getWritableDatabase(); } else { return mOpenHelper.getReadableDatabase(); } } public void close() { if (null != instance) { mOpenHelper.close(); instance = null; } } /** * 清空所有表中数据, 谨慎使用 * */ public void clearData() { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); db.execSQL("DELETE FROM " + StatusTable.TABLE_NAME); db.execSQL("DELETE FROM " + MessageTable.TABLE_NAME); db.execSQL("DELETE FROM " + FollowTable.TABLE_NAME); // 2011.03.01 add db.execSQL("DELETE FROM " + UserInfoTable.TABLE_NAME); } /** * 直接删除数据库文件, 调试用 * * @return true if this file was deleted, false otherwise. * @deprecated */ private boolean deleteDatabase() { File dbFile = mContext.getDatabasePath(DATABASE_NAME); return dbFile.delete(); } /** * 取出某类型的一条消息 * * @param tweetId * @param type * of status <li>StatusTable.TYPE_HOME</li> <li> * StatusTable.TYPE_MENTION</li> <li>StatusTable.TYPE_USER</li> * <li>StatusTable.TYPE_FAVORITE</li> <li>-1 means all types</li> * @return 将Cursor转换过的Tweet对象 * @deprecated use StatusDAO#findStatus() */ public Tweet queryTweet(String tweetId, int type) { SQLiteDatabase Db = mOpenHelper.getWritableDatabase(); String selection = StatusTable._ID + "=? "; if (-1 != type) { selection += " AND " + StatusTable.STATUS_TYPE + "=" + type; } Cursor cursor = Db.query(StatusTable.TABLE_NAME, StatusTable.TABLE_COLUMNS, selection, new String[] { tweetId }, null, null, null); Tweet tweet = null; if (cursor != null) { cursor.moveToFirst(); if (cursor.getCount() > 0) { tweet = StatusTable.parseCursor(cursor); } } cursor.close(); return tweet; } /** * 快速检查某条消息是否存在(指定类型) * * @param tweetId * @param type * <li>StatusTable.TYPE_HOME</li> <li>StatusTable.TYPE_MENTION</li> * <li>StatusTable.TYPE_USER</li> <li>StatusTable.TYPE_FAVORITE</li> * @return is exists * @deprecated use StatusDAO#isExists() */ public boolean isExists(String tweetId, String owner, int type) { SQLiteDatabase Db = mOpenHelper.getWritableDatabase(); boolean result = false; Cursor cursor = Db.query(StatusTable.TABLE_NAME, new String[] { StatusTable._ID }, StatusTable._ID + " =? AND " + StatusTable.OWNER_ID + "=? AND " + StatusTable.STATUS_TYPE + " = " + type, new String[] { tweetId, owner }, null, null, null); if (cursor != null && cursor.getCount() > 0) { result = true; } cursor.close(); return result; } /** * 删除一条消息 * * @param tweetId * @param type * -1 means all types * @return the number of rows affected if a whereClause is passed in, 0 * otherwise. To remove all rows and get a count pass "1" as the * whereClause. * @deprecated use {@link StatusDAO#deleteStatus(String, String, int)} */ public int deleteTweet(String tweetId, String owner, int type) { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); String where = StatusTable._ID + " =? "; if (!TextUtils.isEmpty(owner)) { where += " AND " + StatusTable.OWNER_ID + " = '" + owner + "' "; } if (-1 != type) { where += " AND " + StatusTable.STATUS_TYPE + " = " + type; } return db.delete(StatusTable.TABLE_NAME, where, new String[] { tweetId }); } /** * 删除超过MAX_ROW_NUM垃圾数据 * * @param type * <li>StatusTable.TYPE_HOME</li> <li>StatusTable.TYPE_MENTION</li> * <li>StatusTable.TYPE_USER</li> <li>StatusTable.TYPE_FAVORITE</li> * <li>-1 means all types</li> */ public void gc(String owner, int type) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); String sql = "DELETE FROM " + StatusTable.TABLE_NAME + " WHERE " + StatusTable._ID + " NOT IN " + " (SELECT " + StatusTable._ID // 子句 + " FROM " + StatusTable.TABLE_NAME; boolean first = true; if (!TextUtils.isEmpty(owner)) { sql += " WHERE " + StatusTable.OWNER_ID + " = '" + owner + "' "; first = false; } if (type != -1) { if (first) { sql += " WHERE "; } else { sql += " AND "; } sql += StatusTable.STATUS_TYPE + " = " + type + " "; } sql += " ORDER BY " + StatusTable.CREATED_AT + " DESC LIMIT " + StatusTable.MAX_ROW_NUM + ")"; if (!TextUtils.isEmpty(owner)) { sql += " AND " + StatusTable.OWNER_ID + " = '" + owner + "' "; } if (type != -1) { sql += " AND " + StatusTable.STATUS_TYPE + " = " + type + " "; } Log.v(TAG, sql); mDb.execSQL(sql); } public final static DateFormat DB_DATE_FORMATTER = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US); private static final int CONFLICT_REPLACE = 0x00000005; /** * 向Status表中写入一行数据, 此方法为私有方法, 外部插入数据请使用 putTweets() * * @param tweet * 需要写入的单条消息 * @return the row ID of the newly inserted row, or -1 if an error occurred * @deprecated use {@link StatusDAO#insertStatus(Status, boolean)} */ public long insertTweet(Tweet tweet, String owner, int type, boolean isUnread) { SQLiteDatabase Db = mOpenHelper.getWritableDatabase(); if (isExists(tweet.id, owner, type)) { Log.w(TAG, tweet.id + "is exists."); return -1; } ContentValues initialValues = makeTweetValues(tweet, owner, type, isUnread); long id = Db.insert(StatusTable.TABLE_NAME, null, initialValues); if (-1 == id) { Log.e(TAG, "cann't insert the tweet : " + tweet.toString()); } else { // Log.v(TAG, "Insert a status into database : " + // tweet.toString()); } return id; } /** * 更新一条消息 * * @param tweetId * @param values * ContentValues 需要更新字段的键值对 * @return the number of rows affected * @deprecated use {@link StatusDAO#updateStatus(String, ContentValues)} */ public int updateTweet(String tweetId, ContentValues values) { Log.v(TAG, "Update Tweet : " + tweetId + " " + values.toString()); SQLiteDatabase Db = mOpenHelper.getWritableDatabase(); return Db.update(StatusTable.TABLE_NAME, values, StatusTable._ID + "=?", new String[] { tweetId }); } /** @deprecated */ private ContentValues makeTweetValues(Tweet tweet, String owner, int type, boolean isUnread) { // 插入一条新消息 ContentValues initialValues = new ContentValues(); initialValues.put(StatusTable.OWNER_ID, owner); initialValues.put(StatusTable.STATUS_TYPE, type); initialValues.put(StatusTable._ID, tweet.id); initialValues.put(StatusTable.TEXT, tweet.text); initialValues.put(StatusTable.USER_ID, tweet.userId); initialValues.put(StatusTable.USER_SCREEN_NAME, tweet.screenName); initialValues.put(StatusTable.PROFILE_IMAGE_URL, tweet.profileImageUrl); initialValues.put(StatusTable.PIC_THUMB, tweet.thumbnail_pic); initialValues.put(StatusTable.PIC_MID, tweet.bmiddle_pic); initialValues.put(StatusTable.PIC_ORIG, tweet.original_pic); initialValues.put(StatusTable.FAVORITED, tweet.favorited); initialValues.put(StatusTable.IN_REPLY_TO_STATUS_ID, tweet.inReplyToStatusId); initialValues.put(StatusTable.IN_REPLY_TO_USER_ID, tweet.inReplyToUserId); initialValues.put(StatusTable.IN_REPLY_TO_SCREEN_NAME, tweet.inReplyToScreenName); // initialValues.put(FIELD_IS_REPLY, tweet.isReply()); initialValues.put(StatusTable.CREATED_AT, DB_DATE_FORMATTER.format(tweet.createdAt)); initialValues.put(StatusTable.SOURCE, tweet.source); initialValues.put(StatusTable.IS_UNREAD, isUnread); initialValues.put(StatusTable.TRUNCATED, tweet.truncated); // TODO: truncated return initialValues; } /** * 写入N条消息 * * @param tweets * 需要写入的消息List * @return 写入的记录条数 */ public int putTweets(List<Tweet> tweets, String owner, int type, boolean isUnread) { if (TwitterApplication.DEBUG) { DebugTimer.betweenStart("Status DB"); } if (null == tweets || 0 == tweets.size()) { return 0; } SQLiteDatabase db = mOpenHelper.getWritableDatabase(); int result = 0; try { db.beginTransaction(); for (int i = tweets.size() - 1; i >= 0; i--) { Tweet tweet = tweets.get(i); Log.d(TAG, "insertTweet, tweet id=" + tweet.id); if (TextUtils.isEmpty(tweet.id) || tweet.id.equals("false")){ Log.e(TAG, "tweet id is null, ghost message encounted"); continue; } ContentValues initialValues = makeTweetValues(tweet, owner, type, isUnread); long id = db .insert(StatusTable.TABLE_NAME, null, initialValues); if (-1 == id) { Log.e(TAG, "cann't insert the tweet : " + tweet.toString()); } else { ++result; // Log.v(TAG, // String.format("Insert a status into database[%s] : %s", // owner, tweet.toString())); Log.v("TAG", "Insert Status"); } } // gc(type); // 保持总量 db.setTransactionSuccessful(); } finally { db.endTransaction(); } if (TwitterApplication.DEBUG) { DebugTimer.betweenEnd("Status DB"); } return result; } /** * 取出指定用户的某一类型的所有消息 * * @param userId * @param tableName * @return a cursor * @deprecated use {@link StatusDAO#findStatuses(String, int)} */ public Cursor fetchAllTweets(String owner, int type) { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); return mDb.query(StatusTable.TABLE_NAME, StatusTable.TABLE_COLUMNS, StatusTable.OWNER_ID + " = ? AND " + StatusTable.STATUS_TYPE + " = " + type, new String[] { owner }, null, null, StatusTable.CREATED_AT + " DESC "); // LIMIT " + StatusTable.MAX_ROW_NUM); } /** * 取出自己的某一类型的所有消息 * * @param tableName * @return a cursor */ public Cursor fetchAllTweets(int type) { // 获取登录用户id SharedPreferences preferences = TwitterApplication.mPref; String myself = preferences.getString(Preferences.CURRENT_USER_ID, TwitterApplication.mApi.getUserId()); return fetchAllTweets(myself, type); } /** * 清空某类型的所有信息 * * @param tableName * @return the number of rows affected if a whereClause is passed in, 0 * otherwise. To remove all rows and get a count pass "1" as the * whereClause. */ public int dropAllTweets(int type) { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); return mDb.delete(StatusTable.TABLE_NAME, StatusTable.STATUS_TYPE + " = " + type, null); } /** * 取出本地某类型最新消息ID * * @param type * @return The newest Status Id */ public String fetchMaxTweetId(String owner, int type) { return fetchMaxOrMinTweetId(owner, type, true); } /** * 取出本地某类型最旧消息ID * * @param tableName * @return The oldest Status Id */ public String fetchMinTweetId(String owner, int type) { return fetchMaxOrMinTweetId(owner, type, false); } private String fetchMaxOrMinTweetId(String owner, int type, boolean isMax) { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); String sql = "SELECT " + StatusTable._ID + " FROM " + StatusTable.TABLE_NAME + " WHERE " + StatusTable.STATUS_TYPE + " = " + type + " AND " + StatusTable.OWNER_ID + " = '" + owner + "' " + " ORDER BY " + StatusTable.CREATED_AT; if (isMax) sql += " DESC "; Cursor mCursor = mDb.rawQuery(sql + " LIMIT 1", null); String result = null; if (mCursor == null) { return result; } mCursor.moveToFirst(); if (mCursor.getCount() == 0) { result = null; } else { result = mCursor.getString(0); } mCursor.close(); return result; } /** * Count unread tweet * * @param tableName * @return */ public int fetchUnreadCount(String owner, int type) { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + StatusTable._ID + ")" + " FROM " + StatusTable.TABLE_NAME + " WHERE " + StatusTable.STATUS_TYPE + " = " + type + " AND " + StatusTable.OWNER_ID + " = '" + owner + "' AND " + StatusTable.IS_UNREAD + " = 1 ", // "LIMIT " + StatusTable.MAX_ROW_NUM, null); int result = 0; if (mCursor == null) { return result; } mCursor.moveToFirst(); result = mCursor.getInt(0); mCursor.close(); return result; } public int addNewTweetsAndCountUnread(List<Tweet> tweets, String owner, int type) { putTweets(tweets, owner, type, true); return fetchUnreadCount(owner, type); } /** * Set isFavorited * * @param tweetId * @param isFavorited * @return Is Succeed * @deprecated use {@link Status#setFavorited(boolean)} and * {@link StatusDAO#updateStatus(Status)} */ public boolean setFavorited(String tweetId, String isFavorited) { ContentValues values = new ContentValues(); values.put(StatusTable.FAVORITED, isFavorited); int i = updateTweet(tweetId, values); return (i > 0) ? true : false; } // DM & Follower /** * 写入一条私信 * * @param dm * @param isUnread * @return the row ID of the newly inserted row, or -1 if an error occurred, * 因为主键的原因,此处返回的不是 _ID 的值, 而是一个自增长的 row_id */ public long createDm(Dm dm, boolean isUnread) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); ContentValues initialValues = new ContentValues(); initialValues.put(MessageTable._ID, dm.id); initialValues.put(MessageTable.FIELD_USER_SCREEN_NAME, dm.screenName); initialValues.put(MessageTable.FIELD_TEXT, dm.text); initialValues.put(MessageTable.FIELD_PROFILE_IMAGE_URL, dm.profileImageUrl); initialValues.put(MessageTable.FIELD_IS_UNREAD, isUnread); initialValues.put(MessageTable.FIELD_IS_SENT, dm.isSent); initialValues.put(MessageTable.FIELD_CREATED_AT, DB_DATE_FORMATTER.format(dm.createdAt)); initialValues.put(MessageTable.FIELD_USER_ID, dm.userId); return mDb.insert(MessageTable.TABLE_NAME, null, initialValues); } // /** * Create a follower * * @param userId * @return the row ID of the newly inserted row, or -1 if an error occurred */ public long createFollower(String userId) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); ContentValues initialValues = new ContentValues(); initialValues.put(FollowTable._ID, userId); long rowId = mDb.insert(FollowTable.TABLE_NAME, null, initialValues); if (-1 == rowId) { Log.e(TAG, "Cann't create Follower : " + userId); } else { Log.v(TAG, "Success create follower : " + userId); } return rowId; } /** * 清空Followers表并添加新内容 * * @param followers */ public void syncFollowers(List<String> followers) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); try { mDb.beginTransaction(); boolean result = deleteAllFollowers(); Log.v(TAG, "Result of DeleteAllFollowers: " + result); for (String userId : followers) { createFollower(userId); } mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } } /** * @param type * <li>MessageTable.TYPE_SENT</li> <li>MessageTable.TYPE_GET</li> * <li>其他任何值都认为取出所有类型</li> * @return */ public Cursor fetchAllDms(int type) { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); String selection = null; if (MessageTable.TYPE_SENT == type) { selection = MessageTable.FIELD_IS_SENT + " = " + MessageTable.TYPE_SENT; } else if (MessageTable.TYPE_GET == type) { selection = MessageTable.FIELD_IS_SENT + " = " + MessageTable.TYPE_GET; } return mDb.query(MessageTable.TABLE_NAME, MessageTable.TABLE_COLUMNS, selection, null, null, null, MessageTable.FIELD_CREATED_AT + " DESC"); } public Cursor fetchInboxDms() { return fetchAllDms(MessageTable.TYPE_GET); } public Cursor fetchSendboxDms() { return fetchAllDms(MessageTable.TYPE_SENT); } public Cursor fetchAllFollowers() { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); return mDb.query(FollowTable.TABLE_NAME, FollowTable.TABLE_COLUMNS, null, null, null, null, null); } /** * FIXME: * * @param filter * @return */ public Cursor getFollowerUsernames(String filter) { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); String likeFilter = '%' + filter + '%'; // FIXME: 此方法的作用应该是在于在写私信时自动完成联系人的功能, // 改造数据库后,因为本地tweets表中的数据有限, 所以几乎使得该功能没有实际价值(因为能从数据库中读到的联系人很少) // 在完成关注者/被关注者两个界面后, 看能不能使得本地有一份 // [互相关注] 的 id/name 缓存(即getFriendsIds和getFollowersIds的交集, 因为客户端只能给他们发私信, // 如果按现在 // 只提示followers的列表则很容易造成服务器返回"只能给互相关注的人发私信"的错误信息, 这会造成用户无法理解, // 因为此联系人是我们提供给他们选择的, // 并且将目前的自动完成功能的基础上加一个[选择联系人]按钮, 用于启动一个新的联系人列表页面以显示所有可发送私信的联系人对象, // 类似手机写短信时的选择联系人功能 return null; // FIXME: clean this up. 新数据库中失效, 表名, 列名 // return mDb.rawQuery( // "SELECT user_id AS _id, user" // + " FROM (SELECT user_id, user FROM tweets" // + " INNER JOIN followers on tweets.user_id = followers._id UNION" // + " SELECT user_id, user FROM dms INNER JOIN followers" // + " on dms.user_id = followers._id)" // + " WHERE user LIKE ?" // + " ORDER BY user COLLATE NOCASE", // new String[] { likeFilter }); } /** * @param userId * 该用户是否follow Me * @deprecated 未使用 * @return */ public boolean isFollower(String userId) { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); Cursor cursor = mDb.query(FollowTable.TABLE_NAME, FollowTable.TABLE_COLUMNS, FollowTable._ID + "= ?", new String[] { userId }, null, null, null); boolean result = false; if (cursor != null && cursor.moveToFirst()) { result = true; } cursor.close(); return result; } public boolean deleteAllFollowers() { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); return mDb.delete(FollowTable.TABLE_NAME, null, null) > 0; } public boolean deleteDm(String id) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); return mDb.delete(MessageTable.TABLE_NAME, String.format("%s = '%s'", MessageTable._ID, id), null) > 0; } /** * @param tableName * @return the number of rows affected */ public int markAllTweetsRead(String owner, int type) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(StatusTable.IS_UNREAD, 0); return mDb.update(StatusTable.TABLE_NAME, values, StatusTable.STATUS_TYPE + "=" + type, null); } public boolean deleteAllDms() { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); return mDb.delete(MessageTable.TABLE_NAME, null, null) > 0; } public int markAllDmsRead() { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(MessageTable.FIELD_IS_UNREAD, 0); return mDb.update(MessageTable.TABLE_NAME, values, null, null); } public String fetchMaxDmId(boolean isSent) { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); Cursor mCursor = mDb.rawQuery("SELECT " + MessageTable._ID + " FROM " + MessageTable.TABLE_NAME + " WHERE " + MessageTable.FIELD_IS_SENT + " = ? " + " ORDER BY " + MessageTable.FIELD_CREATED_AT + " DESC LIMIT 1", new String[] { isSent ? "1" : "0" }); String result = null; if (mCursor == null) { return result; } mCursor.moveToFirst(); if (mCursor.getCount() == 0) { result = null; } else { result = mCursor.getString(0); } mCursor.close(); return result; } public int addNewDmsAndCountUnread(List<Dm> dms) { addDms(dms, true); return fetchUnreadDmCount(); } public int fetchDmCount() { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + MessageTable._ID + ") FROM " + MessageTable.TABLE_NAME, null); int result = 0; if (mCursor == null) { return result; } mCursor.moveToFirst(); result = mCursor.getInt(0); mCursor.close(); return result; } private int fetchUnreadDmCount() { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + MessageTable._ID + ") FROM " + MessageTable.TABLE_NAME + " WHERE " + MessageTable.FIELD_IS_UNREAD + " = 1", null); int result = 0; if (mCursor == null) { return result; } mCursor.moveToFirst(); result = mCursor.getInt(0); mCursor.close(); return result; } public void addDms(List<Dm> dms, boolean isUnread) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); try { mDb.beginTransaction(); for (Dm dm : dms) { createDm(dm, isUnread); } // limitRows(TABLE_DIRECTMESSAGE, TwitterApi.RETRIEVE_LIMIT); mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } } // 2011.03.01 add // UserInfo操作 public Cursor getAllUserInfo() { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); return mDb.query(UserInfoTable.TABLE_NAME, UserInfoTable.TABLE_COLUMNS, null, null, null, null, null); } /** * 根据id列表获取user数据 * * @param userIds * @return */ public Cursor getUserInfoByIds(String[] userIds) { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); String userIdStr = ""; for (String id : userIds) { userIdStr += "'" + id + "',"; } if (userIds.length == 0) { userIdStr = "'',"; } userIdStr = userIdStr.substring(0, userIdStr.lastIndexOf(","));// 删除最后的逗号 return mDb.query(UserInfoTable.TABLE_NAME, UserInfoTable.TABLE_COLUMNS, UserInfoTable._ID + " in (" + userIdStr + ")", null, null, null, null); } /** * 新建用户 * * @param user * @return the row ID of the newly inserted row, or -1 if an error occurred */ public long createUserInfo(com.ch_linghu.fanfoudroid.data.User user) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); ContentValues initialValues = new ContentValues(); initialValues.put(UserInfoTable._ID, user.id); initialValues.put(UserInfoTable.FIELD_USER_NAME, user.name); initialValues .put(UserInfoTable.FIELD_USER_SCREEN_NAME, user.screenName); initialValues.put(UserInfoTable.FIELD_LOCALTION, user.location); initialValues.put(UserInfoTable.FIELD_DESCRIPTION, user.description); initialValues.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, user.profileImageUrl); initialValues.put(UserInfoTable.FIELD_URL, user.url); initialValues.put(UserInfoTable.FIELD_PROTECTED, user.isProtected); initialValues.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, user.followersCount); initialValues.put(UserInfoTable.FIELD_LAST_STATUS, user.lastStatus); initialValues.put(UserInfoTable.FIELD_FRIENDS_COUNT, user.friendsCount); initialValues.put(UserInfoTable.FIELD_FAVORITES_COUNT, user.favoritesCount); initialValues.put(UserInfoTable.FIELD_STATUSES_COUNT, user.statusesCount); initialValues.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing); // long rowId = mDb.insertWithOnConflict(UserInfoTable.TABLE_NAME, null, // initialValues,SQLiteDatabase.CONFLICT_REPLACE); long rowId = insertWithOnConflict(mDb, UserInfoTable.TABLE_NAME, null, initialValues, CONFLICT_REPLACE); if (-1 == rowId) { Log.e(TAG, "Cann't create user : " + user.id); } else { Log.v(TAG, "create create user : " + user.id); } return rowId; } // SQLiteDatabase.insertWithConflict是LEVEL 8(2.2)才引入的新方法 // 为了兼容旧版,这里给出一个简化的兼容实现 // 要注意的是这个实现和标准的函数行为并不完全一致 private long insertWithOnConflict(SQLiteDatabase db, String tableName, String nullColumnHack, ContentValues initialValues, int conflictReplace) { long rowId = db.insert(tableName, nullColumnHack, initialValues); if (-1 == rowId) { // 尝试update rowId = db.update(tableName, initialValues, UserInfoTable._ID + "=" + initialValues.getAsString(UserInfoTable._ID), null); } return rowId; } public long createWeiboUserInfo(com.ch_linghu.fanfoudroid.fanfou.User user) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); ContentValues args = new ContentValues(); args.put(UserInfoTable._ID, user.getId()); args.put(UserInfoTable.FIELD_USER_NAME, user.getName()); args.put(UserInfoTable.FIELD_USER_SCREEN_NAME, user.getScreenName()); String location = user.getLocation(); args.put(UserInfoTable.FIELD_LOCALTION, location); String description = user.getDescription(); args.put(UserInfoTable.FIELD_DESCRIPTION, description); args.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, user .getProfileImageURL().toString()); if (user.getURL() != null) { args.put(UserInfoTable.FIELD_URL, user.getURL().toString()); } args.put(UserInfoTable.FIELD_PROTECTED, user.isProtected()); args.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, user.getFollowersCount()); args.put(UserInfoTable.FIELD_LAST_STATUS, user.getStatusSource()); args.put(UserInfoTable.FIELD_FRIENDS_COUNT, user.getFriendsCount()); args.put(UserInfoTable.FIELD_FAVORITES_COUNT, user.getFavouritesCount()); args.put(UserInfoTable.FIELD_STATUSES_COUNT, user.getStatusesCount()); args.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing()); // long rowId = mDb.insert(UserInfoTable.TABLE_NAME, null, args); // 省去判断existUser,如果存在数据则replace // long rowId=mDb.insertWithOnConflict(UserInfoTable.TABLE_NAME, null, // args, SQLiteDatabase.CONFLICT_REPLACE); long rowId = insertWithOnConflict(mDb, UserInfoTable.TABLE_NAME, null, args, CONFLICT_REPLACE); if (-1 == rowId) { Log.e(TAG, "Cann't createWeiboUserInfo : " + user.getId()); } else { Log.v(TAG, "create createWeiboUserInfo : " + user.getId()); } return rowId; } /** * 查看数据是否已保存用户数据 * * @param userId * @return */ public boolean existsUser(String userId) { SQLiteDatabase Db = mOpenHelper.getReadableDatabase(); boolean result = false; Cursor cursor = Db.query(UserInfoTable.TABLE_NAME, new String[] { UserInfoTable._ID }, UserInfoTable._ID + "='" + userId + "'", null, null, null, null); Log.v("testesetesteste", String.valueOf(cursor.getCount())); if (cursor != null && cursor.getCount() > 0) { result = true; } cursor.close(); return result; } /** * 根据userid提取信息 * * @param userId * @return */ public Cursor getUserInfoById(String userId) { SQLiteDatabase Db = mOpenHelper.getReadableDatabase(); Cursor cursor = Db.query(UserInfoTable.TABLE_NAME, UserInfoTable.TABLE_COLUMNS, UserInfoTable._ID + " = '" + userId + "'", null, null, null, null); return cursor; } /** * 更新用户 * * @param uid * @param args * @return */ public boolean updateUser(String uid, ContentValues args) { SQLiteDatabase Db = mOpenHelper.getWritableDatabase(); return Db.update(UserInfoTable.TABLE_NAME, args, UserInfoTable._ID + "='" + uid + "'", null) > 0; } /** * 更新用户信息 */ public boolean updateUser(com.ch_linghu.fanfoudroid.data.User user) { SQLiteDatabase Db = mOpenHelper.getWritableDatabase(); ContentValues args = new ContentValues(); args.put(UserInfoTable._ID, user.id); args.put(UserInfoTable.FIELD_USER_NAME, user.name); args.put(UserInfoTable.FIELD_USER_SCREEN_NAME, user.screenName); args.put(UserInfoTable.FIELD_LOCALTION, user.location); args.put(UserInfoTable.FIELD_DESCRIPTION, user.description); args.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, user.profileImageUrl); args.put(UserInfoTable.FIELD_URL, user.url); args.put(UserInfoTable.FIELD_PROTECTED, user.isProtected); args.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, user.followersCount); args.put(UserInfoTable.FIELD_LAST_STATUS, user.lastStatus); args.put(UserInfoTable.FIELD_FRIENDS_COUNT, user.friendsCount); args.put(UserInfoTable.FIELD_FAVORITES_COUNT, user.favoritesCount); args.put(UserInfoTable.FIELD_STATUSES_COUNT, user.statusesCount); args.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing); return Db.update(UserInfoTable.TABLE_NAME, args, UserInfoTable._ID + "='" + user.id + "'", null) > 0; } /** * 减少转换的开销 * * @param user * @return */ public boolean updateWeiboUser(com.ch_linghu.fanfoudroid.fanfou.User user) { SQLiteDatabase Db = mOpenHelper.getWritableDatabase(); ContentValues args = new ContentValues(); args.put(UserInfoTable._ID, user.getName()); args.put(UserInfoTable.FIELD_USER_NAME, user.getName()); args.put(UserInfoTable.FIELD_USER_SCREEN_NAME, user.getScreenName()); String location = user.getLocation(); args.put(UserInfoTable.FIELD_LOCALTION, location); String description = user.getDescription(); args.put(UserInfoTable.FIELD_DESCRIPTION, description); args.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, user .getProfileImageURL().toString()); if (user.getURL() != null) { args.put(UserInfoTable.FIELD_URL, user.getURL().toString()); } args.put(UserInfoTable.FIELD_PROTECTED, user.isProtected()); args.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, user.getFollowersCount()); args.put(UserInfoTable.FIELD_LAST_STATUS, user.getStatusSource()); args.put(UserInfoTable.FIELD_FRIENDS_COUNT, user.getFriendsCount()); args.put(UserInfoTable.FIELD_FAVORITES_COUNT, user.getFavouritesCount()); args.put(UserInfoTable.FIELD_STATUSES_COUNT, user.getStatusesCount()); args.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing()); return Db.update(UserInfoTable.TABLE_NAME, args, UserInfoTable._ID + "='" + user.getId() + "'", null) > 0; } /** * 同步用户,更新已存在的用户,插入未存在的用户 */ public void syncUsers(List<com.ch_linghu.fanfoudroid.data.User> users) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); try { mDb.beginTransaction(); for (com.ch_linghu.fanfoudroid.data.User u : users) { // if(existsUser(u.id)){ // updateUser(u); // }else{ // createUserInfo(u); // } createUserInfo(u); } mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } } public void syncWeiboUsers(List<com.ch_linghu.fanfoudroid.fanfou.User> users) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); try { mDb.beginTransaction(); for (com.ch_linghu.fanfoudroid.fanfou.User u : users) { // if (existsUser(u.getId())) { // updateWeiboUser(u); // } else { // createWeiboUserInfo(u); // } createWeiboUserInfo(u); } mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/db/TwitterDatabase.java
Java
asf20
34,712
package com.ch_linghu.fanfoudroid; import java.util.ArrayList; import java.util.List; import android.app.SearchManager; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.ch_linghu.fanfoudroid.fanfou.SavedSearch; import com.ch_linghu.fanfoudroid.fanfou.Trend; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.base.BaseActivity; import com.ch_linghu.fanfoudroid.ui.module.Feedback; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType; import com.ch_linghu.fanfoudroid.ui.module.NavBar; import com.ch_linghu.fanfoudroid.util.TextHelper; import com.commonsware.cwac.merge.MergeAdapter; import com.ch_linghu.fanfoudroid.R; public class SearchActivity extends BaseActivity { private static final String TAG = SearchActivity.class.getSimpleName(); private static final int LOADING = 1; private static final int NETWORKERROR = 2; private static final int SUCCESS = 3; private EditText mSearchEdit; private ListView mSearchSectionList; private TextView trendsTitle; private TextView savedSearchTitle; private MergeAdapter mSearchSectionAdapter; private SearchAdapter trendsAdapter; private SearchAdapter savedSearchesAdapter; private ArrayList<SearchItem> trends; private ArrayList<SearchItem> savedSearch; private String initialQuery; private NavBar mNavbar; private Feedback mFeedback; private GenericTask trendsAndSavedSearchesTask; private TaskListener trendsAndSavedSearchesTaskListener = new TaskAdapter() { @Override public String getName() { return "trendsAndSavedSearchesTask"; } @Override public void onPreExecute(GenericTask task) { } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { refreshSearchSectionList(SearchActivity.SUCCESS); } else if (result == TaskResult.IO_ERROR) { refreshSearchSectionList(SearchActivity.NETWORKERROR); Toast.makeText( SearchActivity.this, getResources() .getString( R.string.login_status_network_or_connection_error), Toast.LENGTH_SHORT).show(); } } }; @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate()..."); if (super._onCreate(savedInstanceState)) { setContentView(R.layout.search); mNavbar = new NavBar(NavBar.HEADER_STYLE_SEARCH, this); mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS); initView(); initSearchSectionList(); refreshSearchSectionList(SearchActivity.LOADING); doGetSavedSearches(); return true; } else { return false; } } private void initView() { mSearchEdit = (EditText) findViewById(R.id.search_edit); mSearchEdit.setOnKeyListener(enterKeyHandler); trendsTitle = (TextView) getLayoutInflater().inflate( R.layout.search_section_header, null); trendsTitle.setText(getResources().getString(R.string.trends_title)); savedSearchTitle = (TextView) getLayoutInflater().inflate( R.layout.search_section_header, null); savedSearchTitle.setText(getResources().getString( R.string.saved_search_title)); mSearchSectionAdapter = new MergeAdapter(); mSearchSectionList = (ListView) findViewById(R.id.search_section_list); mNavbar.getSearchButton().setOnClickListener( new View.OnClickListener() { public void onClick(View v) { initialQuery = mSearchEdit.getText().toString(); startSearch(); } }); } @Override protected void onResume() { Log.d(TAG, "onResume()..."); super.onResume(); } private void doGetSavedSearches() { if (trendsAndSavedSearchesTask != null && trendsAndSavedSearchesTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { trendsAndSavedSearchesTask = new TrendsAndSavedSearchesTask(); trendsAndSavedSearchesTask .setListener(trendsAndSavedSearchesTaskListener); trendsAndSavedSearchesTask.setFeedback(mFeedback); trendsAndSavedSearchesTask.execute(); } } private void initSearchSectionList() { trends = new ArrayList<SearchItem>(); savedSearch = new ArrayList<SearchItem>(); trendsAdapter = new SearchAdapter(this); savedSearchesAdapter = new SearchAdapter(this); mSearchSectionAdapter.addView(savedSearchTitle); mSearchSectionAdapter.addAdapter(savedSearchesAdapter); mSearchSectionAdapter.addView(trendsTitle); mSearchSectionAdapter.addAdapter(trendsAdapter); mSearchSectionList.setAdapter(mSearchSectionAdapter); } /** * 辅助计算位置的类 * * @author jmx * */ class PositionHelper { /** * 返回指定位置属于哪一个小节 * * @param position * 绝对位置 * @return 小节的序号,0是第一小节,1是第二小节, -1为无效位置 */ public int getSectionIndex(int position) { int[] contentLength = new int[2]; contentLength[0] = savedSearchesAdapter.getCount(); contentLength[1] = trendsAdapter.getCount(); if (position > 0 && position < contentLength[0] + 1) { return 0; } else if (position > contentLength[0] + 1 && position < (contentLength[0] + contentLength[1] + 1) + 1) { return 1; } else { return -1; } } /** * 返回指定位置在自己所在小节的相对位置 * * @param position * 绝对位置 * @return 所在小节的相对位置,-1为无效位置 */ public int getRelativePostion(int position) { int[] contentLength = new int[2]; contentLength[0] = savedSearchesAdapter.getCount(); contentLength[1] = trendsAdapter.getCount(); int sectionIndex = getSectionIndex(position); int offset = 0; for (int i = 0; i < sectionIndex; ++i) { offset += contentLength[i] + 1; } return position - offset - 1; } } /** * flag: loading;network error;success */ PositionHelper pos_helper = new PositionHelper(); private void refreshSearchSectionList(int flag) { AdapterView.OnItemClickListener searchSectionListListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { MergeAdapter adapter = (MergeAdapter) (adapterView.getAdapter()); SearchAdapter subAdapter = (SearchAdapter) adapter .getAdapter(position); // 计算针对subAdapter中的相对位置 int relativePos = pos_helper.getRelativePostion(position); SearchItem item = (SearchItem) (subAdapter.getItem(relativePos)); initialQuery = item.query; startSearch(); } }; if (flag == SearchActivity.LOADING) { mSearchSectionList.setOnItemClickListener(null); savedSearch.clear(); trends.clear(); savedSearchesAdapter.refresh(getString(R.string.search_loading)); trendsAdapter.refresh(getString(R.string.search_loading)); } else if (flag == SearchActivity.NETWORKERROR) { mSearchSectionList.setOnItemClickListener(null); savedSearch.clear(); trends.clear(); savedSearchesAdapter .refresh(getString(R.string.login_status_network_or_connection_error)); trendsAdapter .refresh(getString(R.string.login_status_network_or_connection_error)); } else { savedSearchesAdapter.refresh(savedSearch); trendsAdapter.refresh(trends); } if (flag == SearchActivity.SUCCESS) { mSearchSectionList .setOnItemClickListener(searchSectionListListener); } } protected boolean startSearch() { if (!TextUtils.isEmpty(initialQuery)) { // 以下这个方法在7可用,在8就报空指针 // triggerSearch(initialQuery, null); Intent i = new Intent(this, SearchResultActivity.class); i.putExtra(SearchManager.QUERY, initialQuery); startActivity(i); } else if (TextUtils.isEmpty(initialQuery)) { Toast.makeText(this, getResources().getString(R.string.search_box_null), Toast.LENGTH_SHORT).show(); return false; } return false; } // 搜索框回车键判断 private View.OnKeyListener enterKeyHandler = new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { if (event.getAction() == KeyEvent.ACTION_UP) { initialQuery = mSearchEdit.getText().toString(); startSearch(); } return true; } return false; } }; private class TrendsAndSavedSearchesTask extends GenericTask { Trend[] trendsList; List<SavedSearch> savedSearchsList; @Override protected TaskResult _doInBackground(TaskParams... params) { try { trendsList = getApi().getTrends().getTrends(); savedSearchsList = getApi().getSavedSearches(); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } trends.clear(); savedSearch.clear(); for (int i = 0; i < trendsList.length; i++) { SearchItem item = new SearchItem(); item.name = trendsList[i].getName(); item.query = trendsList[i].getQuery(); trends.add(item); } for (int i = 0; i < savedSearchsList.size(); i++) { SearchItem item = new SearchItem(); item.name = savedSearchsList.get(i).getName(); item.query = savedSearchsList.get(i).getQuery(); savedSearch.add(item); } return TaskResult.OK; } } } class SearchItem { public String name; public String query; } class SearchAdapter extends BaseAdapter { protected ArrayList<SearchItem> mSearchList; private Context mContext; protected LayoutInflater mInflater; protected StringBuilder mMetaBuilder; public SearchAdapter(Context context) { mSearchList = new ArrayList<SearchItem>(); mContext = context; mInflater = LayoutInflater.from(mContext); mMetaBuilder = new StringBuilder(); } public SearchAdapter(Context context, String prompt) { this(context); refresh(prompt); } public void refresh(ArrayList<SearchItem> searchList) { mSearchList = searchList; notifyDataSetChanged(); } public void refresh(String prompt) { SearchItem item = new SearchItem(); item.name = prompt; item.query = null; mSearchList.clear(); mSearchList.add(item); notifyDataSetChanged(); } @Override public int getCount() { return mSearchList.size(); } @Override public Object getItem(int position) { return mSearchList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view; if (convertView == null) { view = mInflater.inflate(R.layout.search_section_view, parent, false); TextView text = (TextView) view .findViewById(R.id.search_section_text); view.setTag(text); } else { view = convertView; } TextView text = (TextView) view.getTag(); SearchItem item = mSearchList.get(position); text.setText(item.name); return view; } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/SearchActivity.java
Java
asf20
11,514
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.CursorAdapter; import android.widget.EditText; import android.widget.TextView; import com.ch_linghu.fanfoudroid.data.Dm; import com.ch_linghu.fanfoudroid.db.StatusTable; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.fanfou.DirectMessage; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.base.BaseActivity; import com.ch_linghu.fanfoudroid.ui.module.NavBar; import com.ch_linghu.fanfoudroid.ui.module.TweetEdit; import com.ch_linghu.fanfoudroid.R; //FIXME: 将WriteDmActivity和WriteActivity进行整合。 /** * 撰写私信界面 * * @author lds * */ public class WriteDmActivity extends BaseActivity { public static final String NEW_TWEET_ACTION = "com.ch_linghu.fanfoudroid.NEW"; public static final String EXTRA_TEXT = "text"; public static final String REPLY_ID = "reply_id"; private static final String TAG = "WriteActivity"; private static final String SIS_RUNNING_KEY = "running"; private static final String PREFS_NAME = "com.ch_linghu.fanfoudroid"; // View private TweetEdit mTweetEdit; private EditText mTweetEditText; private TextView mProgressText; private Button mSendButton; // private AutoCompleteTextView mToEdit; private TextView mToEdit; private NavBar mNavbar; // Task private GenericTask mSendTask; private TaskListener mSendTaskListener = new TaskAdapter() { @Override public void onPreExecute(GenericTask task) { disableEntry(); updateProgress(getString(R.string.page_status_updating)); } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { mToEdit.setText(""); mTweetEdit.setText(""); updateProgress(""); enableEntry(); // 发送成功就直接关闭界面 finish(); // 关闭软键盘 InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mTweetEdit.getEditText() .getWindowToken(), 0); } else if (result == TaskResult.NOT_FOLLOWED_ERROR) { updateProgress(getString(R.string.direct_meesage_status_the_person_not_following_you)); enableEntry(); } else if (result == TaskResult.IO_ERROR) { // TODO: 什么情况下会抛出IO_ERROR?需要给用户更为具体的失败原因 updateProgress(getString(R.string.page_status_unable_to_update)); enableEntry(); } } @Override public String getName() { return "DMSend"; } }; private FriendsAdapter mFriendsAdapter; // Adapter for To: recipient // autocomplete. private static final String EXTRA_USER = "user"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.DMSW"; public static Intent createIntent(String user) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); if (!TextUtils.isEmpty(user)) { intent.putExtra(EXTRA_USER, user); } return intent; } // sub menu // protected void createInsertPhotoDialog() { // // final CharSequence[] items = { // getString(R.string.write_label_take_a_picture), // getString(R.string.write_label_choose_a_picture) }; // // AlertDialog.Builder builder = new AlertDialog.Builder(this); // builder.setTitle(getString(R.string.write_label_insert_picture)); // builder.setItems(items, new DialogInterface.OnClickListener() { // public void onClick(DialogInterface dialog, int item) { // // Toast.makeText(getApplicationContext(), items[item], // // Toast.LENGTH_SHORT).show(); // switch (item) { // case 0: // openImageCaptureMenu(); // break; // case 1: // openPhotoLibraryMenu(); // } // } // }); // AlertDialog alert = builder.create(); // alert.show(); // } @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate."); if (super._onCreate(savedInstanceState)) { // init View setContentView(R.layout.write_dm); mNavbar = new NavBar(NavBar.HEADER_STYLE_WRITE, this); // Intent & Action & Extras Intent intent = getIntent(); Bundle extras = intent.getExtras(); // View mProgressText = (TextView) findViewById(R.id.progress_text); mTweetEditText = (EditText) findViewById(R.id.tweet_edit); TwitterDatabase db = getDb(); // FIXME: 暂时取消收件人自动完成功能 // FIXME: 可根据目前以后内容重新完成自动完成功能 // mToEdit = (AutoCompleteTextView) findViewById(R.id.to_edit); // Cursor cursor = db.getFollowerUsernames(""); // // startManagingCursor(cursor); // mFriendsAdapter = new FriendsAdapter(this, cursor); // mToEdit.setAdapter(mFriendsAdapter); mToEdit = (TextView) findViewById(R.id.to_edit); // Update status mTweetEdit = new TweetEdit(mTweetEditText, (TextView) findViewById(R.id.chars_text)); mTweetEdit.setOnKeyListener(editEnterHandler); mTweetEdit.addTextChangedListener(new MyTextWatcher( WriteDmActivity.this)); // With extras if (extras != null) { String to = extras.getString(EXTRA_USER); if (!TextUtils.isEmpty(to)) { mToEdit.setText(to); mTweetEdit.requestFocus(); } } View.OnClickListener sendListenner = new View.OnClickListener() { public void onClick(View v) { doSend(); } }; Button mTopSendButton = (Button) findViewById(R.id.top_send_btn); mTopSendButton.setOnClickListener(sendListenner); return true; } else { return false; } } @Override protected void onRestoreInstanceState(Bundle bundle) { super.onRestoreInstanceState(bundle); mTweetEdit.updateCharsRemain(); } @Override protected void onPause() { super.onPause(); Log.d(TAG, "onPause."); } @Override protected void onRestart() { super.onRestart(); Log.d(TAG, "onRestart."); } @Override protected void onResume() { super.onResume(); Log.d(TAG, "onResume."); } @Override protected void onStart() { super.onStart(); Log.d(TAG, "onStart."); } @Override protected void onStop() { super.onStop(); Log.d(TAG, "onStop."); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy."); if (mSendTask != null && mSendTask.getStatus() == GenericTask.Status.RUNNING) { // Doesn't really cancel execution (we let it continue running). // See the SendTask code for more details. mSendTask.cancel(true); } // Don't need to cancel FollowersTask (assuming it ends properly). super.onDestroy(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mSendTask != null && mSendTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } public static Intent createNewTweetIntent(String text) { Intent intent = new Intent(NEW_TWEET_ACTION); intent.putExtra(EXTRA_TEXT, text); return intent; } private class MyTextWatcher implements TextWatcher { private WriteDmActivity _activity; public MyTextWatcher(WriteDmActivity activity) { _activity = activity; } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub if (s.length() == 0) { } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } } private void doSend() { if (mSendTask != null && mSendTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { String to = mToEdit.getText().toString(); String status = mTweetEdit.getText().toString(); if (!TextUtils.isEmpty(status) && !TextUtils.isEmpty(to)) { mSendTask = new DmSendTask(); mSendTask.setListener(mSendTaskListener); mSendTask.execute(); } else if (TextUtils.isEmpty(status)) { updateProgress(getString(R.string.direct_meesage_status_texting_is_null)); } else if (TextUtils.isEmpty(to)) { updateProgress(getString(R.string.direct_meesage_status_user_is_null)); } } } private class DmSendTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { String user = mToEdit.getText().toString(); String text = mTweetEdit.getText().toString(); DirectMessage directMessage = getApi().sendDirectMessage(user, text); Dm dm = Dm.create(directMessage, true); // if (!Utils.isEmpty(dm.profileImageUrl)) { // // Fetch image to cache. // try { // getImageManager().put(dm.profileImageUrl); // } catch (IOException e) { // Log.e(TAG, e.getMessage(), e); // } // } getDb().createDm(dm, false); } catch (HttpException e) { Log.d(TAG, e.getMessage()); // TODO: check is this is actually the case. return TaskResult.NOT_FOLLOWED_ERROR; } return TaskResult.OK; } } private static class FriendsAdapter extends CursorAdapter { public FriendsAdapter(Context context, Cursor cursor) { super(context, cursor); mInflater = LayoutInflater.from(context); mUserTextColumn = cursor .getColumnIndexOrThrow(StatusTable.USER_SCREEN_NAME); } private LayoutInflater mInflater; private int mUserTextColumn; @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = mInflater .inflate(R.layout.dropdown_item, parent, false); ViewHolder holder = new ViewHolder(); holder.userText = (TextView) view.findViewById(android.R.id.text1); view.setTag(holder); return view; } class ViewHolder { public TextView userText; } @Override public void bindView(View view, Context context, Cursor cursor) { ViewHolder holder = (ViewHolder) view.getTag(); holder.userText.setText(cursor.getString(mUserTextColumn)); } @Override public Cursor runQueryOnBackgroundThread(CharSequence constraint) { String filter = constraint == null ? "" : constraint.toString(); return TwitterApplication.mDb.getFollowerUsernames(filter); } @Override public String convertToString(Cursor cursor) { return cursor.getString(mUserTextColumn); } } private void enableEntry() { mTweetEdit.setEnabled(true); mSendButton.setEnabled(true); } private void disableEntry() { mTweetEdit.setEnabled(false); mSendButton.setEnabled(false); } // UI helpers. private void updateProgress(String progress) { mProgressText.setText(progress); } private View.OnKeyListener editEnterHandler = new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { if (event.getAction() == KeyEvent.ACTION_UP) { doSend(); } return true; } return false; } }; }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/WriteDmActivity.java
Java
asf20
12,236
package com.ch_linghu.fanfoudroid; import java.text.ParseException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.Button; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.data.Dm; import com.ch_linghu.fanfoudroid.db.MessageTable; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.fanfou.DirectMessage; 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.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.base.BaseActivity; import com.ch_linghu.fanfoudroid.ui.base.Refreshable; 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.SimpleFeedback; import com.ch_linghu.fanfoudroid.util.DateTimeHelper; import com.ch_linghu.fanfoudroid.util.TextHelper; import com.ch_linghu.fanfoudroid.R; public class DmActivity extends BaseActivity implements Refreshable { private static final String TAG = "DmActivity"; // Views. private ListView mTweetList; private Adapter mAdapter; private Adapter mInboxAdapter; private Adapter mSendboxAdapter; Button inbox; Button sendbox; Button newMsg; private int mDMType; private static final int DM_TYPE_ALL = 0; private static final int DM_TYPE_INBOX = 1; private static final int DM_TYPE_SENDBOX = 2; private TextView mProgressText; private NavBar mNavbar; private Feedback mFeedback; // Tasks. private GenericTask mRetrieveTask; private GenericTask mDeleteTask; private TaskListener mDeleteTaskListener = new TaskAdapter() { @Override public void onPreExecute(GenericTask task) { updateProgress(getString(R.string.page_status_deleting)); } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { mAdapter.refresh(); } else { // Do nothing. } updateProgress(""); } @Override public String getName() { return "DmDeleteTask"; } }; private TaskListener mRetrieveTaskListener = new TaskAdapter() { @Override public void onPreExecute(GenericTask task) { updateProgress(getString(R.string.page_status_refreshing)); } @Override public void onProgressUpdate(GenericTask task, Object params) { draw(); } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { SharedPreferences.Editor editor = mPreferences.edit(); editor.putLong(Preferences.LAST_DM_REFRESH_KEY, DateTimeHelper.getNowTime()); editor.commit(); draw(); goTop(); } else { // Do nothing. } updateProgress(""); } @Override public String getName() { return "DmRetrieve"; } }; // Refresh data at startup if last refresh was this long ago or greater. private static final long REFRESH_THRESHOLD = 5 * 60 * 1000; private static final String EXTRA_USER = "user"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.DMS"; public static Intent createIntent() { return createIntent(""); } public static Intent createIntent(String user) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); if (!TextUtils.isEmpty(user)) { intent.putExtra(EXTRA_USER, user); } return intent; } @Override protected boolean _onCreate(Bundle savedInstanceState) { if (super._onCreate(savedInstanceState)) { setContentView(R.layout.dm); mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this); mNavbar.setHeaderTitle("我的私信"); mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS); bindFooterButtonEvent(); mTweetList = (ListView) findViewById(R.id.tweet_list); mProgressText = (TextView) findViewById(R.id.progress_text); TwitterDatabase db = getDb(); // Mark all as read. db.markAllDmsRead(); setupAdapter(); // Make sure call bindFooterButtonEvent first boolean shouldRetrieve = false; long lastRefreshTime = mPreferences.getLong( Preferences.LAST_DM_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 (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(); } // Want to be able to focus on the items with the trackball. // That way, we can navigate up and down by changing item focus. mTweetList.setItemsCanFocus(true); return true; } else { return false; } } @Override protected void onResume() { super.onResume(); checkIsLogedIn(); } private static final String SIS_RUNNING_KEY = "running"; @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } @Override protected void onDestroy() { Log.d(TAG, "onDestroy."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { mRetrieveTask.cancel(true); } if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING) { mDeleteTask.cancel(true); } super.onDestroy(); } // UI helpers. private void bindFooterButtonEvent() { inbox = (Button) findViewById(R.id.inbox); sendbox = (Button) findViewById(R.id.sendbox); newMsg = (Button) findViewById(R.id.new_message); inbox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mDMType != DM_TYPE_INBOX) { mDMType = DM_TYPE_INBOX; inbox.setEnabled(false); sendbox.setEnabled(true); mTweetList.setAdapter(mInboxAdapter); mInboxAdapter.refresh(); } } }); sendbox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mDMType != DM_TYPE_SENDBOX) { mDMType = DM_TYPE_SENDBOX; inbox.setEnabled(true); sendbox.setEnabled(false); mTweetList.setAdapter(mSendboxAdapter); mSendboxAdapter.refresh(); } } }); newMsg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(DmActivity.this, WriteDmActivity.class); intent.putExtra("reply_to_id", 0); // TODO: 传入实际的reply_to_id startActivity(intent); } }); } private void setupAdapter() { Cursor cursor = getDb().fetchAllDms(-1); startManagingCursor(cursor); mAdapter = new Adapter(this, cursor); Cursor inboxCursor = getDb().fetchInboxDms(); startManagingCursor(inboxCursor); mInboxAdapter = new Adapter(this, inboxCursor); Cursor sendboxCursor = getDb().fetchSendboxDms(); startManagingCursor(sendboxCursor); mSendboxAdapter = new Adapter(this, sendboxCursor); mTweetList.setAdapter(mInboxAdapter); registerForContextMenu(mTweetList); inbox.setEnabled(false); } private class DmRetrieveTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { List<DirectMessage> dmList; ArrayList<Dm> dms = new ArrayList<Dm>(); TwitterDatabase db = getDb(); // ImageManager imageManager = getImageManager(); String maxId = db.fetchMaxDmId(false); HashSet<String> imageUrls = new HashSet<String>(); try { if (maxId != null) { Paging paging = new Paging(maxId); dmList = getApi().getDirectMessages(paging); } else { dmList = getApi().getDirectMessages(); } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } publishProgress(SimpleFeedback.calProgressBySize(40, 20, dmList)); for (DirectMessage directMessage : dmList) { if (isCancelled()) { return TaskResult.CANCELLED; } Dm dm; dm = Dm.create(directMessage, false); dms.add(dm); imageUrls.add(dm.profileImageUrl); if (isCancelled()) { return TaskResult.CANCELLED; } } maxId = db.fetchMaxDmId(true); try { if (maxId != null) { Paging paging = new Paging(maxId); dmList = getApi().getSentDirectMessages(paging); } else { dmList = getApi().getSentDirectMessages(); } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } for (DirectMessage directMessage : dmList) { if (isCancelled()) { return TaskResult.CANCELLED; } Dm dm; dm = Dm.create(directMessage, true); dms.add(dm); imageUrls.add(dm.profileImageUrl); if (isCancelled()) { return TaskResult.CANCELLED; } } db.addDms(dms, false); // if (isCancelled()) { // return TaskResult.CANCELLED; // } // // publishProgress(null); // // for (String imageUrl : imageUrls) { // if (!Utils.isEmpty(imageUrl)) { // // Fetch image to cache. // try { // imageManager.put(imageUrl); // } catch (IOException e) { // Log.e(TAG, e.getMessage(), e); // } // } // // if (isCancelled()) { // return TaskResult.CANCELLED; // } // } return TaskResult.OK; } } private static class Adapter extends CursorAdapter { public Adapter(Context context, Cursor cursor) { super(context, cursor); mInflater = LayoutInflater.from(context); // TODO: 可使用: // DM dm = MessageTable.parseCursor(cursor); mUserTextColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_USER_SCREEN_NAME); mTextColumn = cursor.getColumnIndexOrThrow(MessageTable.FIELD_TEXT); mProfileImageUrlColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_PROFILE_IMAGE_URL); mCreatedAtColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_CREATED_AT); mIsSentColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_IS_SENT); } private LayoutInflater mInflater; private int mUserTextColumn; private int mTextColumn; private int mProfileImageUrlColumn; private int mIsSentColumn; private int mCreatedAtColumn; @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = mInflater.inflate(R.layout.direct_message, parent, false); ViewHolder holder = new ViewHolder(); holder.userText = (TextView) view .findViewById(R.id.tweet_user_text); holder.tweetText = (TextView) view.findViewById(R.id.tweet_text); holder.profileImage = (ImageView) view .findViewById(R.id.profile_image); holder.metaText = (TextView) view .findViewById(R.id.tweet_meta_text); view.setTag(holder); return view; } class ViewHolder { public TextView userText; public TextView tweetText; public ImageView profileImage; public TextView metaText; } @Override public void bindView(View view, Context context, Cursor cursor) { ViewHolder holder = (ViewHolder) view.getTag(); int isSent = cursor.getInt(mIsSentColumn); String user = cursor.getString(mUserTextColumn); if (0 == isSent) { holder.userText.setText(context .getString(R.string.direct_message_label_from_prefix) + user); } else { holder.userText.setText(context .getString(R.string.direct_message_label_to_prefix) + user); } TextHelper.setTweetText(holder.tweetText, cursor.getString(mTextColumn)); String profileImageUrl = cursor.getString(mProfileImageUrlColumn); if (!TextUtils.isEmpty(profileImageUrl)) { holder.profileImage .setImageBitmap(TwitterApplication.mImageLoader.get( profileImageUrl, new ImageLoaderCallback() { @Override public void refresh(String url, Bitmap bitmap) { Adapter.this.refresh(); } })); } try { holder.metaText.setText(DateTimeHelper .getRelativeDate(TwitterDatabase.DB_DATE_FORMATTER .parse(cursor.getString(mCreatedAtColumn)))); } catch (ParseException e) { Log.w(TAG, "Invalid created at data."); } } public void refresh() { getCursor().requery(); } } // Menu. @Override public boolean onCreateOptionsMenu(Menu menu) { return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // FIXME: 将刷新功能绑定到顶部的刷新按钮上,主菜单中的刷新选项已删除 // case OPTIONS_MENU_ID_REFRESH: // doRetrieve(); // return true; case OPTIONS_MENU_ID_TWEETS: launchActivity(TwitterActivity.createIntent(this)); return true; case OPTIONS_MENU_ID_REPLIES: launchActivity(MentionActivity.createIntent(this)); return true; } return super.onOptionsItemSelected(item); } private static final int CONTEXT_REPLY_ID = 0; private static final int CONTEXT_DELETE_ID = 1; @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(0, CONTEXT_REPLY_ID, 0, R.string.cmenu_reply); menu.add(0, CONTEXT_DELETE_ID, 0, R.string.cmenu_delete); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); Cursor cursor = (Cursor) mAdapter.getItem(info.position); if (cursor == null) { Log.w(TAG, "Selected item not available."); return super.onContextItemSelected(item); } switch (item.getItemId()) { case CONTEXT_REPLY_ID: String user_id = cursor.getString(cursor .getColumnIndexOrThrow(MessageTable.FIELD_USER_ID)); Intent intent = WriteDmActivity.createIntent(user_id); startActivity(intent); return true; case CONTEXT_DELETE_ID: int idIndex = cursor.getColumnIndexOrThrow(MessageTable._ID); String id = cursor.getString(idIndex); doDestroy(id); return true; default: return super.onContextItemSelected(item); } } private void doDestroy(String id) { Log.d(TAG, "Attempting delete."); if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mDeleteTask = new DmDeleteTask(); mDeleteTask.setListener(mDeleteTaskListener); TaskParams params = new TaskParams(); params.put("id", id); mDeleteTask.execute(params); } } private class DmDeleteTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { TaskParams param = params[0]; try { String id = param.getString("id"); DirectMessage directMessage = getApi().destroyDirectMessage(id); Dm.create(directMessage, false); getDb().deleteDm(id); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } if (isCancelled()) { return TaskResult.CANCELLED; } return TaskResult.OK; } } public void doRetrieve() { Log.d(TAG, "Attempting retrieve."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mRetrieveTask = new DmRetrieveTask(); mRetrieveTask.setFeedback(mFeedback); mRetrieveTask.setListener(mRetrieveTaskListener); mRetrieveTask.execute(); } } public void goTop() { mTweetList.setSelection(0); } public void draw() { mAdapter.refresh(); mInboxAdapter.refresh(); mSendboxAdapter.refresh(); } private void updateProgress(String msg) { mProgressText.setText(msg); } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/DmActivity.java
Java
asf20
17,743
package com.ch_linghu.fanfoudroid.util; import java.io.InputStream; import java.io.OutputStream; public class StreamUtils { public static void CopyStream(InputStream is, OutputStream os) { final int buffer_size = 1024; try { byte[] bytes = new byte[buffer_size]; for (;;) { int count = is.read(bytes, 0, buffer_size); if (count == -1) break; os.write(bytes, 0, count); } } catch (Exception ex) { } } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/util/StreamUtils.java
Java
asf20
458
package com.ch_linghu.fanfoudroid.util; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Arrays; import java.util.HashMap; import android.util.Log; import com.ch_linghu.fanfoudroid.TwitterApplication; /** * Debug Timer * * Usage: -------------------------------- DebugTimer.start(); * DebugTimer.mark("my_mark1"); // optional DebugTimer.stop(); * * System.out.println(DebugTimer.__toString()); // get report * -------------------------------- * * @author LDS */ public class DebugTimer { public static final int START = 0; public static final int END = 1; private static HashMap<String, Long> mTime = new HashMap<String, Long>(); private static long mStartTime = 0; private static long mLastTime = 0; /** * Start a timer */ public static void start() { reset(); mStartTime = touch(); } /** * Mark current time * * @param tag * mark tag * @return */ public static long mark(String tag) { long time = System.currentTimeMillis() - mStartTime; mTime.put(tag, time); return time; } /** * Mark current time * * @param tag * mark tag * @return */ public static long between(String tag, int startOrEnd) { if (TwitterApplication.DEBUG) { Log.v("DEBUG", tag + " " + startOrEnd); } switch (startOrEnd) { case START: return mark(tag); case END: long time = System.currentTimeMillis() - mStartTime - get(tag, mStartTime); mTime.put(tag, time); // touch(); return time; default: return -1; } } public static long betweenStart(String tag) { return between(tag, START); } public static long betweenEnd(String tag) { return between(tag, END); } /** * Stop timer * * @return result */ public static String stop() { mTime.put("_TOTLE", touch() - mStartTime); return __toString(); } public static String stop(String tag) { mark(tag); return stop(); } /** * Get a mark time * * @param tag * mark tag * @return time(milliseconds) or NULL */ public static long get(String tag) { return get(tag, 0); } public static long get(String tag, long defaultValue) { if (mTime.containsKey(tag)) { return mTime.get(tag); } return defaultValue; } /** * Reset timer */ public static void reset() { mTime = new HashMap<String, Long>(); mStartTime = 0; mLastTime = 0; } /** * static toString() * * @return */ public static String __toString() { return "Debuger [time =" + mTime.toString() + "]"; } private static long touch() { return mLastTime = System.currentTimeMillis(); } public static DebugProfile[] getProfile() { DebugProfile[] profile = new DebugProfile[mTime.size()]; long totel = mTime.get("_TOTLE"); int i = 0; for (String key : mTime.keySet()) { long time = mTime.get(key); profile[i] = new DebugProfile(key, time, time / (totel * 1.0)); i++; } try { Arrays.sort(profile); } catch (NullPointerException e) { // in case item is null, do nothing } return profile; } public static String getProfileAsString() { StringBuilder sb = new StringBuilder(); for (DebugProfile p : getProfile()) { sb.append("TAG: "); sb.append(p.tag); sb.append("\t INC: "); sb.append(p.inc); sb.append("\t INCP: "); sb.append(p.incPercent); sb.append("\n"); } return sb.toString(); } @Override public String toString() { return __toString(); } } class DebugProfile implements Comparable<DebugProfile> { private static NumberFormat percent = NumberFormat.getPercentInstance(); public String tag; public long inc; public String incPercent; public DebugProfile(String tag, long inc, double incPercent) { this.tag = tag; this.inc = inc; percent = new DecimalFormat("0.00#%"); this.incPercent = percent.format(incPercent); } @Override public int compareTo(DebugProfile o) { // TODO Auto-generated method stub return (int) (o.inc - this.inc); } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/util/DebugTimer.java
Java
asf20
3,972
package com.ch_linghu.fanfoudroid.util; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import android.util.Log; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; public class DateTimeHelper { private static final String TAG = "DateTimeHelper"; // Wed Dec 15 02:53:36 +0000 2010 public static final DateFormat TWITTER_DATE_FORMATTER = new SimpleDateFormat( "E MMM d HH:mm:ss Z yyyy", Locale.US); public static final DateFormat TWITTER_SEARCH_API_DATE_FORMATTER = new SimpleDateFormat( "E, d MMM yyyy HH:mm:ss Z", Locale.US); // TODO: Z -> z ? public static final Date parseDateTime(String dateString) { try { Log.v(TAG, String.format("in parseDateTime, dateString=%s", dateString)); return TWITTER_DATE_FORMATTER.parse(dateString); } catch (ParseException e) { Log.w(TAG, "Could not parse Twitter date string: " + dateString); return null; } } // Handle "yyyy-MM-dd'T'HH:mm:ss.SSS" from sqlite public static final Date parseDateTimeFromSqlite(String dateString) { try { Log.v(TAG, String.format("in parseDateTime, dateString=%s", dateString)); return TwitterDatabase.DB_DATE_FORMATTER.parse(dateString); } catch (ParseException e) { Log.w(TAG, "Could not parse Twitter date string: " + dateString); return null; } } public static final Date parseSearchApiDateTime(String dateString) { try { return TWITTER_SEARCH_API_DATE_FORMATTER.parse(dateString); } catch (ParseException e) { Log.w(TAG, "Could not parse Twitter search date string: " + dateString); return null; } } public static final DateFormat AGO_FULL_DATE_FORMATTER = new SimpleDateFormat( "yyyy-MM-dd HH:mm"); public static String getRelativeDate(Date date) { Date now = new Date(); String prefix = TwitterApplication.mContext .getString(R.string.tweet_created_at_beautify_prefix); String sec = TwitterApplication.mContext .getString(R.string.tweet_created_at_beautify_sec); String min = TwitterApplication.mContext .getString(R.string.tweet_created_at_beautify_min); String hour = TwitterApplication.mContext .getString(R.string.tweet_created_at_beautify_hour); String day = TwitterApplication.mContext .getString(R.string.tweet_created_at_beautify_day); String suffix = TwitterApplication.mContext .getString(R.string.tweet_created_at_beautify_suffix); // Seconds. long diff = (now.getTime() - date.getTime()) / 1000; if (diff < 0) { diff = 0; } if (diff < 60) { return diff + sec + suffix; } // Minutes. diff /= 60; if (diff < 60) { return prefix + diff + min + suffix; } // Hours. diff /= 60; if (diff < 24) { return prefix + diff + hour + suffix; } return AGO_FULL_DATE_FORMATTER.format(date); } public static long getNowTime() { return Calendar.getInstance().getTime().getTime(); } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/util/DateTimeHelper.java
Java
asf20
3,060
package com.ch_linghu.fanfoudroid.util; import java.io.File; import java.io.IOException; import android.os.Environment; /** * 对SD卡文件的管理 * * @author ch.linghu * */ public class FileHelper { private static final String TAG = "FileHelper"; private static final String BASE_PATH = "fanfoudroid"; public static File getBasePath() throws IOException { File basePath = new File(Environment.getExternalStorageDirectory(), BASE_PATH); if (!basePath.exists()) { if (!basePath.mkdirs()) { throw new IOException(String.format("%s cannot be created!", basePath.toString())); } } if (!basePath.isDirectory()) { throw new IOException(String.format("%s is not a directory!", basePath.toString())); } return basePath; } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/util/FileHelper.java
Java
asf20
778
package com.ch_linghu.fanfoudroid.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.text.Html; import android.text.util.Linkify; import android.util.Log; import android.widget.TextView; import android.widget.TextView.BufferType; public class TextHelper { private static final String TAG = "TextHelper"; public static String stringifyStream(InputStream is) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } return sb.toString(); } private static HashMap<String, String> _userLinkMapping = new HashMap<String, String>(); private static final Pattern NAME_MATCHER = Pattern.compile("@.+?\\s"); private static final Linkify.MatchFilter NAME_MATCHER_MATCH_FILTER = new Linkify.MatchFilter() { @Override public final boolean acceptMatch(final CharSequence s, final int start, final int end) { String name = s.subSequence(start + 1, end).toString().trim(); boolean result = _userLinkMapping.containsKey(name); return result; } }; private static final Linkify.TransformFilter NAME_MATCHER_TRANSFORM_FILTER = new Linkify.TransformFilter() { @Override public String transformUrl(Matcher match, String url) { // TODO Auto-generated method stub String name = url.subSequence(1, url.length()).toString().trim(); return _userLinkMapping.get(name); } }; private static final String TWITTA_USER_URL = "twitta://users/"; public static void linkifyUsers(TextView view) { Linkify.addLinks(view, NAME_MATCHER, TWITTA_USER_URL, NAME_MATCHER_MATCH_FILTER, NAME_MATCHER_TRANSFORM_FILTER); } private static final Pattern TAG_MATCHER = Pattern.compile("#\\w+#"); private static final Linkify.TransformFilter TAG_MATCHER_TRANSFORM_FILTER = new Linkify.TransformFilter() { @Override public final String transformUrl(Matcher match, String url) { String result = url.substring(1, url.length() - 1); return result; } }; private static final String TWITTA_SEARCH_URL = "twitta://search/"; public static void linkifyTags(TextView view) { Linkify.addLinks(view, TAG_MATCHER, TWITTA_SEARCH_URL, null, TAG_MATCHER_TRANSFORM_FILTER); } private static Pattern USER_LINK = Pattern .compile("@<a href=\"http:\\/\\/fanfou\\.com\\/(.*?)\" class=\"former\">(.*?)<\\/a>"); private static String preprocessText(String text) { // 处理HTML格式返回的用户链接 Matcher m = USER_LINK.matcher(text); while (m.find()) { _userLinkMapping.put(m.group(2), m.group(1)); Log.d(TAG, String.format("Found mapping! %s=%s", m.group(2), m.group(1))); } // 将User Link的连接去掉 StringBuffer sb = new StringBuffer(); m = USER_LINK.matcher(text); while (m.find()) { m.appendReplacement(sb, "@$2"); } m.appendTail(sb); return sb.toString(); } public static String getSimpleTweetText(String text) { return Html.fromHtml(text).toString(); } public static void setSimpleTweetText(TextView textView, String text) { String processedText = getSimpleTweetText(text); textView.setText(processedText); } public static void setTweetText(TextView textView, String text) { String processedText = preprocessText(text); textView.setText(Html.fromHtml(processedText), BufferType.SPANNABLE); Linkify.addLinks(textView, Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES); linkifyUsers(textView); linkifyTags(textView); _userLinkMapping.clear(); } /** * 从消息中获取全部提到的人,将它们按先后顺序放入一个列表 * * @param msg * 消息文本 * @return 消息中@的人的列表,按顺序存放 */ public static List<String> getMentions(String msg) { ArrayList<String> mentionList = new ArrayList<String>(); final Pattern p = Pattern.compile("@(.*?)\\s"); final int MAX_NAME_LENGTH = 12; // 简化判断,无论中英文最长12个字 Matcher m = p.matcher(msg); while (m.find()) { String mention = m.group(1); // 过长的名字就忽略(不是合法名字) +1是为了补上“@”所占的长度 if (mention.length() <= MAX_NAME_LENGTH + 1) { // 避免重复名字 if (!mentionList.contains(mention)) { mentionList.add(m.group(1)); } } } return mentionList; } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/util/TextHelper.java
Java
asf20
4,585
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid; import java.io.IOException; import java.io.InputStream; import java.text.MessageFormat; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.text.ClipboardManager; import android.text.TextUtils; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import com.ch_linghu.fanfoudroid.app.ImageCache; import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.http.HttpClient; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.Response; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.task.TweetCommonTask; import com.ch_linghu.fanfoudroid.ui.base.BaseActivity; import com.ch_linghu.fanfoudroid.ui.module.Feedback; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType; import com.ch_linghu.fanfoudroid.ui.module.NavBar; import com.ch_linghu.fanfoudroid.util.DateTimeHelper; import com.ch_linghu.fanfoudroid.util.TextHelper; import com.ch_linghu.fanfoudroid.R; public class StatusActivity extends BaseActivity { private static final String TAG = "StatusActivity"; private static final String SIS_RUNNING_KEY = "running"; private static final String PREFS_NAME = "com.ch_linghu.fanfoudroid"; private static final String EXTRA_TWEET = "tweet"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.STATUS"; static final private int CONTEXT_REFRESH_ID = 0x0001; static final private int CONTEXT_CLIPBOARD_ID = 0x0002; static final private int CONTEXT_DELETE_ID = 0x0003; // Task TODO: tasks private GenericTask mReplyTask; private GenericTask mStatusTask; private GenericTask mPhotoTask; // TODO: 压缩图片,提供获取图片的过程中可取消获取 private GenericTask mFavTask; private GenericTask mDeleteTask; private NavBar mNavbar; private Feedback mFeedback; private TaskListener mReplyTaskListener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { showReplyStatus(replyTweet); StatusActivity.this.mFeedback.success(""); } @Override public String getName() { return "GetReply"; } }; private TaskListener mStatusTaskListener = new TaskAdapter() { @Override public void onPreExecute(GenericTask task) { clean(); } @Override public void onPostExecute(GenericTask task, TaskResult result) { StatusActivity.this.mFeedback.success(""); draw(); } @Override public String getName() { return "GetStatus"; } }; private TaskListener mPhotoTaskListener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { status_photo.setImageBitmap(mPhotoBitmap); } else { status_photo.setVisibility(View.GONE); } StatusActivity.this.mFeedback.success(""); } @Override public String getName() { // TODO Auto-generated method stub return "GetPhoto"; } }; private TaskListener mFavTaskListener = new TaskAdapter() { @Override public String getName() { return "FavoriteTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { onFavSuccess(); } else if (result == TaskResult.IO_ERROR) { onFavFailure(); } } }; private TaskListener mDeleteTaskListener = new TaskAdapter() { @Override public String getName() { return "DeleteTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { onDeleteSuccess(); } else if (result == TaskResult.IO_ERROR) { onDeleteFailure(); } } }; // View private TextView tweet_screen_name; private TextView tweet_text; private TextView tweet_user_info; private ImageView profile_image; private TextView tweet_source; private TextView tweet_created_at; private ImageButton btn_person_more; private ImageView status_photo = null; // if exists private ViewGroup reply_wrap; private TextView reply_status_text = null; // if exists private TextView reply_status_date = null; // if exists private ImageButton tweet_fav; private Tweet tweet = null; private Tweet replyTweet = null; // if exists private HttpClient mClient; private Bitmap mPhotoBitmap = ImageCache.mDefaultBitmap; // if exists public static Intent createIntent(Tweet tweet) { Intent intent = new Intent(LAUNCH_ACTION); intent.putExtra(EXTRA_TWEET, tweet); return intent; } private static Pattern PHOTO_PAGE_LINK = Pattern .compile("http://fanfou.com(/photo/[-a-zA-Z0-9+&@#%?=~_|!:,.;]*[-a-zA-Z0-9+&@#%=~_|])"); private static Pattern PHOTO_SRC_LINK = Pattern .compile("src=\"(http:\\/\\/photo\\.fanfou\\.com\\/.*?)\""); /** * 获得消息中的照片页面链接 * * @param text * 消息文本 * @param size * 照片尺寸 * @return 照片页面的链接,若不存在,则返回null */ public static String getPhotoPageLink(String text, String size) { Matcher m = PHOTO_PAGE_LINK.matcher(text); if (m.find()) { String THUMBNAIL = TwitterApplication.mContext .getString(R.string.pref_photo_preview_type_thumbnail); String MIDDLE = TwitterApplication.mContext .getString(R.string.pref_photo_preview_type_middle); String ORIGINAL = TwitterApplication.mContext .getString(R.string.pref_photo_preview_type_original); if (size.equals(THUMBNAIL) || size.equals(MIDDLE)) { return "http://m.fanfou.com" + m.group(1); } else if (size.endsWith(ORIGINAL)) { return m.group(0); } else { return null; } } else { return null; } } /** * 获得照片页面中的照片链接 * * @param pageHtml * 照片页面文本 * @return 照片链接,若不存在,则返回null */ public static String getPhotoURL(String pageHtml) { Matcher m = PHOTO_SRC_LINK.matcher(pageHtml); if (m.find()) { return m.group(1); } else { return null; } } @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate."); if (super._onCreate(savedInstanceState)) { mClient = getApi().getHttpClient(); // Intent & Action & Extras Intent intent = getIntent(); String action = intent.getAction(); Bundle extras = intent.getExtras(); // Must has extras if (null == extras) { Log.e(TAG, this.getClass().getName() + " must has extras."); finish(); return false; } setContentView(R.layout.status); mNavbar = new NavBar(NavBar.HEADER_STYLE_BACK, this); mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS); findView(); bindNavBarListener(); // Set view with intent data this.tweet = extras.getParcelable(EXTRA_TWEET); draw(); bindFooterBarListener(); bindReplyViewListener(); return true; } else { return false; } } private void findView() { tweet_screen_name = (TextView) findViewById(R.id.tweet_screen_name); tweet_user_info = (TextView) findViewById(R.id.tweet_user_info); tweet_text = (TextView) findViewById(R.id.tweet_text); tweet_source = (TextView) findViewById(R.id.tweet_source); profile_image = (ImageView) findViewById(R.id.profile_image); tweet_created_at = (TextView) findViewById(R.id.tweet_created_at); btn_person_more = (ImageButton) findViewById(R.id.person_more); tweet_fav = (ImageButton) findViewById(R.id.tweet_fav); reply_wrap = (ViewGroup) findViewById(R.id.reply_wrap); reply_status_text = (TextView) findViewById(R.id.reply_status_text); reply_status_date = (TextView) findViewById(R.id.reply_tweet_created_at); status_photo = (ImageView) findViewById(R.id.status_photo); } private void bindNavBarListener() { mNavbar.getRefreshButton().setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { doGetStatus(tweet.id); } }); } private void bindFooterBarListener() { // person_more btn_person_more.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = ProfileActivity.createIntent(tweet.userId); startActivity(intent); } }); // Footer bar TextView footer_btn_share = (TextView) findViewById(R.id.footer_btn_share); TextView footer_btn_reply = (TextView) findViewById(R.id.footer_btn_reply); TextView footer_btn_retweet = (TextView) findViewById(R.id.footer_btn_retweet); TextView footer_btn_fav = (TextView) findViewById(R.id.footer_btn_fav); TextView footer_btn_more = (TextView) findViewById(R.id.footer_btn_more); // 分享 footer_btn_share.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra( Intent.EXTRA_TEXT, String.format("@%s %s", tweet.screenName, TextHelper.getSimpleTweetText(tweet.text))); startActivity(Intent.createChooser(intent, getString(R.string.cmenu_share))); } }); // 回复 footer_btn_reply.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = WriteActivity.createNewReplyIntent(tweet.text, tweet.screenName, tweet.id); startActivity(intent); } }); // 转发 footer_btn_retweet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = WriteActivity.createNewRepostIntent( StatusActivity.this, tweet.text, tweet.screenName, tweet.id); startActivity(intent); } }); // 收藏/取消收藏 footer_btn_fav.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (tweet.favorited.equals("true")) { doFavorite("del", tweet.id); } else { doFavorite("add", tweet.id); } } }); // TODO: 更多操作 registerForContextMenu(footer_btn_more); footer_btn_more.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openContextMenu(v); } }); } private void bindReplyViewListener() { // 点击回复消息打开新的Status界面 OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View v) { if (!TextUtils.isEmpty(tweet.inReplyToStatusId)) { if (replyTweet == null) { Log.w(TAG, "Selected item not available."); } else { launchActivity(StatusActivity.createIntent(replyTweet)); } } } }; reply_wrap.setOnClickListener(listener); } @Override protected void onPause() { super.onPause(); Log.d(TAG, "onPause."); } @Override protected void onRestart() { super.onRestart(); Log.d(TAG, "onRestart."); } @Override protected void onResume() { super.onResume(); Log.d(TAG, "onResume."); } @Override protected void onStart() { super.onStart(); Log.d(TAG, "onStart."); } @Override protected void onStop() { super.onStop(); Log.d(TAG, "onStop."); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy."); if (mReplyTask != null && mReplyTask.getStatus() == GenericTask.Status.RUNNING) { mReplyTask.cancel(true); } if (mPhotoTask != null && mPhotoTask.getStatus() == GenericTask.Status.RUNNING) { mPhotoTask.cancel(true); } if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { mFavTask.cancel(true); } super.onDestroy(); } private ImageLoaderCallback callback = new ImageLoaderCallback() { @Override public void refresh(String url, Bitmap bitmap) { profile_image.setImageBitmap(bitmap); } }; private void clean() { tweet_screen_name.setText(""); tweet_text.setText(""); tweet_created_at.setText(""); tweet_source.setText(""); tweet_user_info.setText(""); tweet_fav.setEnabled(false); profile_image.setImageBitmap(ImageCache.mDefaultBitmap); status_photo.setVisibility(View.GONE); ViewGroup reply_wrap = (ViewGroup) findViewById(R.id.reply_wrap); reply_wrap.setVisibility(View.GONE); } private void draw() { Log.d(TAG, "draw"); String PHOTO_PREVIEW_TYPE_NONE = getString(R.string.pref_photo_preview_type_none); String PHOTO_PREVIEW_TYPE_THUMBNAIL = getString(R.string.pref_photo_preview_type_thumbnail); String PHOTO_PREVIEW_TYPE_MIDDLE = getString(R.string.pref_photo_preview_type_middle); String PHOTO_PREVIEW_TYPE_ORIGINAL = getString(R.string.pref_photo_preview_type_original); SharedPreferences pref = getPreferences(); String photoPreviewSize = pref.getString(Preferences.PHOTO_PREVIEW, PHOTO_PREVIEW_TYPE_ORIGINAL); boolean forceShowAllImage = pref.getBoolean( Preferences.FORCE_SHOW_ALL_IMAGE, false); tweet_screen_name.setText(tweet.screenName); TextHelper.setTweetText(tweet_text, tweet.text); tweet_created_at.setText(DateTimeHelper .getRelativeDate(tweet.createdAt)); tweet_source.setText(getString(R.string.tweet_source_prefix) + tweet.source); tweet_user_info.setText(tweet.userId); boolean isFav = (tweet.favorited.equals("true")) ? true : false; tweet_fav.setEnabled(isFav); // Bitmap mProfileBitmap = // TwitterApplication.mImageManager.get(tweet.profileImageUrl); profile_image.setImageBitmap(TwitterApplication.mImageLoader.get( tweet.profileImageUrl, callback)); // has photo if (!photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_NONE)) { String photoLink; boolean isPageLink = false; if (photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_THUMBNAIL)) { photoLink = tweet.thumbnail_pic; } else if (photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_MIDDLE)) { photoLink = tweet.bmiddle_pic; } else if (photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_ORIGINAL)) { photoLink = tweet.original_pic; } else { Log.e(TAG, "Invalid Photo Preview Size Type"); photoLink = ""; } // 如果选用了强制显示则再尝试分析图片链接 if (forceShowAllImage) { photoLink = getPhotoPageLink(tweet.text, photoPreviewSize); isPageLink = true; } if (!TextUtils.isEmpty(photoLink)) { status_photo.setVisibility(View.VISIBLE); status_photo.setImageBitmap(mPhotoBitmap); doGetPhoto(photoLink, isPageLink); } } else { status_photo.setVisibility(View.GONE); } // has reply if (!TextUtils.isEmpty(tweet.inReplyToStatusId)) { ViewGroup reply_wrap = (ViewGroup) findViewById(R.id.reply_wrap); reply_wrap.setVisibility(View.VISIBLE); reply_status_text = (TextView) findViewById(R.id.reply_status_text); reply_status_date = (TextView) findViewById(R.id.reply_tweet_created_at); doGetReply(tweet.inReplyToStatusId); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mReplyTask != null && mReplyTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } private String fetchWebPage(String url) throws HttpException { Log.d(TAG, "Fetching WebPage: " + url); Response res = mClient.get(url); return res.asString(); } private Bitmap fetchPhotoBitmap(String url) throws HttpException, IOException { Log.d(TAG, "Fetching Photo: " + url); Response res = mClient.get(url); // FIXME:这里使用了一个作废的方法,如何修正? InputStream is = res.asStream(); Bitmap bitmap = BitmapFactory.decodeStream(is); is.close(); return bitmap; } private void doGetReply(String status_id) { Log.d(TAG, "Attempting get status task."); mFeedback.start(""); if (mReplyTask != null && mReplyTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mReplyTask = new GetReplyTask(); mReplyTask.setListener(mReplyTaskListener); TaskParams params = new TaskParams(); params.put("reply_id", status_id); mReplyTask.execute(params); } } private class GetReplyTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { TaskParams param = params[0]; com.ch_linghu.fanfoudroid.fanfou.Status status; try { String reply_id = param.getString("reply_id"); if (!TextUtils.isEmpty(reply_id)) { // 首先查看是否在数据库中,如不在再去获取 replyTweet = getDb().queryTweet(reply_id, -1); if (replyTweet == null) { status = getApi().showStatus(reply_id); replyTweet = Tweet.create(status); } } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } return TaskResult.OK; } } private void doGetStatus(String status_id) { Log.d(TAG, "Attempting get status task."); mFeedback.start(""); if (mStatusTask != null && mStatusTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mStatusTask = new GetStatusTask(); mStatusTask.setListener(mStatusTaskListener); TaskParams params = new TaskParams(); params.put("id", status_id); mStatusTask.execute(params); } } private class GetStatusTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { TaskParams param = params[0]; com.ch_linghu.fanfoudroid.fanfou.Status status; try { String id = param.getString("id"); if (!TextUtils.isEmpty(id)) { status = getApi().showStatus(id); mFeedback.update(80); tweet = Tweet.create(status); } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } mFeedback.update(99); return TaskResult.OK; } } private void doGetPhoto(String photoPageURL, boolean isPageLink) { mFeedback.start(""); if (mPhotoTask != null && mPhotoTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mPhotoTask = new GetPhotoTask(); mPhotoTask.setListener(mPhotoTaskListener); TaskParams params = new TaskParams(); params.put("photo_url", photoPageURL); params.put("is_page_link", isPageLink); mPhotoTask.execute(params); } } private class GetPhotoTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { TaskParams param = params[0]; try { String photoURL = param.getString("photo_url"); boolean isPageLink = param.getBoolean("is_page_link"); if (!TextUtils.isEmpty(photoURL)) { if (isPageLink) { String pageHtml = fetchWebPage(photoURL); String photoSrcURL = getPhotoURL(pageHtml); if (photoSrcURL != null) { mPhotoBitmap = fetchPhotoBitmap(photoSrcURL); } } else { mPhotoBitmap = fetchPhotoBitmap(photoURL); } } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } catch (IOException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } return TaskResult.OK; } } private void showReplyStatus(Tweet tweet) { if (tweet != null) { String text = tweet.screenName + " : " + tweet.text; TextHelper.setSimpleTweetText(reply_status_text, text); reply_status_date.setText(DateTimeHelper .getRelativeDate(tweet.createdAt)); } else { String msg = MessageFormat.format( getString(R.string.status_status_reply_cannot_display), this.tweet.inReplyToScreenName); reply_status_text.setText(msg); } } public void onDeleteFailure() { Log.e(TAG, "Delete failed"); } public void onDeleteSuccess() { finish(); } // for HasFavorite interface public void doFavorite(String action, String id) { if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { if (!TextUtils.isEmpty(id)) { Log.d(TAG, "doFavorite."); mFavTask = new TweetCommonTask.FavoriteTask(this); mFavTask.setListener(mFavTaskListener); TaskParams param = new TaskParams(); param.put("action", action); param.put("id", id); mFavTask.execute(param); } } } public void onFavSuccess() { // updateProgress(getString(R.string.refreshing)); if (((TweetCommonTask.FavoriteTask) mFavTask).getType().equals( TweetCommonTask.FavoriteTask.TYPE_ADD)) { tweet.favorited = "true"; tweet_fav.setEnabled(true); } else { tweet.favorited = "false"; tweet_fav.setEnabled(false); } } public void onFavFailure() { // updateProgress(getString(R.string.refreshing)); } private void doDelete(String id) { if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mDeleteTask = new TweetCommonTask.DeleteTask(this); mDeleteTask.setListener(mDeleteTaskListener); TaskParams params = new TaskParams(); params.put("id", id); mDeleteTask.execute(params); } } @Override public boolean onContextItemSelected(MenuItem item) { switch (item.getItemId()) { case CONTEXT_REFRESH_ID: doGetStatus(tweet.id); return true; case CONTEXT_CLIPBOARD_ID: ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); clipboard.setText(TextHelper.getSimpleTweetText(tweet.text)); return true; case CONTEXT_DELETE_ID: doDelete(tweet.id); return true; } return super.onContextItemSelected(item); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { menu.setHeaderIcon(android.R.drawable.ic_menu_more); menu.setHeaderTitle(getString(R.string.cmenu_more)); menu.add(0, CONTEXT_REFRESH_ID, 0, R.string.omenu_refresh); menu.add(0, CONTEXT_CLIPBOARD_ID, 0, R.string.cmenu_clipboard); if (tweet.userId.equals(TwitterApplication.getMyselfId(false))) { menu.add(0, CONTEXT_DELETE_ID, 0, R.string.cmenu_delete); } } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/StatusActivity.java
Java
asf20
23,198
package com.ch_linghu.fanfoudroid; import java.text.MessageFormat; import java.util.List; import android.content.Intent; import android.os.Bundle; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.ListView; 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.ui.base.UserArrayBaseActivity; import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter; import com.ch_linghu.fanfoudroid.R; public class FollowingActivity extends UserArrayBaseActivity { private ListView mUserList; private UserArrayAdapter mAdapter; private String userId; private String userName; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FOLLOWING"; private static final String USER_ID = "userId"; private static final String USER_NAME = "userName"; private int currentPage = 1; String myself = ""; @Override protected boolean _onCreate(Bundle savedInstanceState) { Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null) { this.userId = extras.getString(USER_ID); this.userName = extras.getString(USER_NAME); } else { // 获取登录用户id userId = TwitterApplication.getMyselfId(false); userName = TwitterApplication.getMyselfName(false); } if (super._onCreate(savedInstanceState)) { myself = TwitterApplication.getMyselfId(false); if (getUserId() == myself) { mNavbar.setHeaderTitle(MessageFormat.format( getString(R.string.profile_friends_count_title), "我")); } else { mNavbar.setHeaderTitle(MessageFormat.format( getString(R.string.profile_friends_count_title), userName)); } return true; } else { return false; } } /* * 添加取消关注按钮 * * @see * com.ch_linghu.fanfoudroid.ui.base.UserListBaseActivity#onCreateContextMenu * (android.view.ContextMenu, android.view.View, * android.view.ContextMenu.ContextMenuInfo) */ @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); if (getUserId() == myself) { AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; User user = getContextItemUser(info.position); menu.add( 0, CONTENT_DEL_FRIEND, 0, getResources().getString( R.string.cmenu_user_addfriend_prefix) + user.screenName + getResources().getString( R.string.cmenu_user_friend_suffix)); } } public static Intent createIntent(String userId, String userName) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra(USER_ID, userId); intent.putExtra(USER_NAME, userName); return intent; } @Override public Paging getNextPage() { currentPage += 1; return new Paging(currentPage); } @Override protected String getUserId() { return this.userId; } @Override public Paging getCurrentPage() { currentPage = 1; return new Paging(this.currentPage); } @Override protected List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers( String userId, Paging page) throws HttpException { return getApi().getFriendsStatuses(userId, page); } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/FollowingActivity.java
Java
asf20
3,452
package com.ch_linghu.fanfoudroid; import java.util.HashSet; //import org.acra.ReportingInteractionMode; //import org.acra.annotation.ReportsCrashes; import android.app.Application; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.preference.PreferenceManager; import android.widget.Toast; import com.ch_linghu.fanfoudroid.app.LazyImageLoader; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.db.StatusTable; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.fanfou.Configuration; import com.ch_linghu.fanfoudroid.fanfou.User; import com.ch_linghu.fanfoudroid.fanfou.Weibo; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; //@ReportsCrashes(formKey="dHowMk5LMXQweVJkWGthb1E1T1NUUHc6MQ", // mode = ReportingInteractionMode.NOTIFICATION, // resNotifTickerText = R.string.crash_notif_ticker_text, // resNotifTitle = R.string.crash_notif_title, // resNotifText = R.string.crash_notif_text, // resNotifIcon = android.R.drawable.stat_notify_error, // optional. default is a warning sign // resDialogText = R.string.crash_dialog_text, // resDialogIcon = android.R.drawable.ic_dialog_info, //optional. default is a warning sign // resDialogTitle = R.string.crash_dialog_title, // optional. default is your application name // resDialogCommentPrompt = R.string.crash_dialog_comment_prompt, // optional. when defined, adds a user text field input with this text resource as a label // resDialogOkToast = R.string.crash_dialog_ok_toast // optional. displays a Toast message when the user accepts to send a report. //) public class TwitterApplication extends Application { public static final String TAG = "TwitterApplication"; // public static ImageManager mImageManager; public static LazyImageLoader mImageLoader; public static TwitterDatabase mDb; public static Weibo mApi; // new API public static Context mContext; public static SharedPreferences mPref; public static int networkType = 0; public final static boolean DEBUG = Configuration.getDebug(); public GenericTask mUserInfoTask = new GetUserInfoTask(); // FIXME:获取登录用户id, 据肉眼观察,刚注册的用户系统分配id都是~开头的,因为不知道 // 用户何时去修改这个ID,目前只有把所有以~开头的ID在每次需要UserId时都去服务器 // 取一次数据,看看新的ID是否已经设定,判断依据是是否以~开头。这么判断会把有些用户 // 就是把自己ID设置的以~开头的造成,每次都需要去服务器取数。 // 只是简单处理了mPref没有CURRENT_USER_ID的情况,因为用户在登陆时,肯定会记一个CURRENT_USER_ID // 到mPref. private static void fetchMyselfInfo() { User myself; try { myself = TwitterApplication.mApi.showUser(TwitterApplication.mApi .getUserId()); TwitterApplication.mPref.edit() .putString(Preferences.CURRENT_USER_ID, myself.getId()) .commit(); TwitterApplication.mPref .edit() .putString(Preferences.CURRENT_USER_SCREEN_NAME, myself.getScreenName()).commit(); } catch (HttpException e) { e.printStackTrace(); } } public static String getMyselfId(boolean forceGet) { if (!mPref.contains(Preferences.CURRENT_USER_ID)){ if (forceGet && mPref.getString(Preferences.CURRENT_USER_ID, "~") .startsWith("~")){ fetchMyselfInfo(); } } return mPref.getString(Preferences.CURRENT_USER_ID, "~"); } public static String getMyselfName(boolean forceGet) { if (!mPref.contains(Preferences.CURRENT_USER_ID) || !mPref.contains(Preferences.CURRENT_USER_SCREEN_NAME)) { if (forceGet && mPref.getString(Preferences.CURRENT_USER_ID, "~") .startsWith("~")){ fetchMyselfInfo(); } } return mPref.getString(Preferences.CURRENT_USER_SCREEN_NAME, ""); } @Override public void onCreate() { // FIXME: StrictMode类在1.6以下的版本中没有,会导致类加载失败。 // 因此将这些代码设成关闭状态,仅在做性能调试时才打开。 // //NOTE: StrictMode模式需要2.3+ API支持。 // if (DEBUG){ // StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() // .detectAll() // .penaltyLog() // .build()); // StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() // .detectAll() // .penaltyLog() // .build()); // } super.onCreate(); mContext = this.getApplicationContext(); // mImageManager = new ImageManager(this); mImageLoader = new LazyImageLoader(); mApi = new Weibo(); mDb = TwitterDatabase.getInstance(this); mPref = PreferenceManager.getDefaultSharedPreferences(this); String username = mPref.getString(Preferences.USERNAME_KEY, ""); String password = mPref.getString(Preferences.PASSWORD_KEY, ""); password = LoginActivity.decryptPassword(password); if (Weibo.isValidCredentials(username, password)) { mApi.setCredentials(username, password); // Setup API and HttpClient doGetUserInfo(); } // 为cmwap用户设置代理上网 String type = getNetworkType(); if (null != type && type.equalsIgnoreCase("cmwap")) { Toast.makeText(this, "您当前正在使用cmwap网络上网.", Toast.LENGTH_SHORT); mApi.getHttpClient().setProxy("10.0.0.172", 80, "http"); } } public String getNetworkType() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); // NetworkInfo mobNetInfo = connectivityManager // .getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (activeNetInfo != null) { return activeNetInfo.getExtraInfo(); // 接入点名称: 此名称可被用户任意更改 如: cmwap, // cmnet, // internet ... } else { return null; } } @Override public void onTerminate() { // FIXME: 根据android文档,onTerminate不会在真实机器上被执行到 // 因此这些清理动作需要再找合适的地方放置,以确保执行。 cleanupImages(); mDb.close(); Toast.makeText(this, "exit app", Toast.LENGTH_LONG); super.onTerminate(); } private void cleanupImages() { HashSet<String> keepers = new HashSet<String>(); Cursor cursor = mDb.fetchAllTweets(StatusTable.TYPE_HOME); if (cursor.moveToFirst()) { int imageIndex = cursor .getColumnIndexOrThrow(StatusTable.PROFILE_IMAGE_URL); do { keepers.add(cursor.getString(imageIndex)); } while (cursor.moveToNext()); } cursor.close(); cursor = mDb.fetchAllDms(-1); if (cursor.moveToFirst()) { int imageIndex = cursor .getColumnIndexOrThrow(StatusTable.PROFILE_IMAGE_URL); do { keepers.add(cursor.getString(imageIndex)); } while (cursor.moveToNext()); } cursor.close(); mImageLoader.getImageManager().cleanup(keepers); } public void doGetUserInfo() { if (mUserInfoTask != null && mUserInfoTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mUserInfoTask = new GetUserInfoTask(); mUserInfoTask.setListener(new TaskAdapter(){ @Override public String getName() { return "GetUserInfo"; } }); mUserInfoTask.execute(); } } public class GetUserInfoTask extends GenericTask { public static final String TAG = "DeleteTask"; @Override protected TaskResult _doInBackground(TaskParams... params) { getMyselfId(true); getMyselfName(true); return TaskResult.OK; } } }
061304011116lyj-lyj
src/com/ch_linghu/fanfoudroid/TwitterApplication.java
Java
asf20
8,108
package com.markupartist.android.widget; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.GestureDetector; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.widget.AbsListView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.AbsListView.OnScrollListener; import com.ch_linghu.fanfoudroid.R; public class PullToRefreshListView extends ListView implements OnScrollListener, GestureDetector.OnGestureListener { private final int MAXHEIGHT = 20; private static final int TAP_TO_REFRESH = 1; private static final int PULL_TO_REFRESH = 2; private static final int RELEASE_TO_REFRESH = 3; private static final int REFRESHING = 4; // private static final int RELEASING = 5;//释放过程做动画用 private static final String TAG = "PullToRefreshListView"; private OnRefreshListener mOnRefreshListener; /** * Listener that will receive notifications every time the list scrolls. */ private OnScrollListener mOnScrollListener; private LayoutInflater mInflater; private LinearLayout mRefreshView; private TextView mRefreshViewText; private ImageView mRefreshViewImage; private ProgressBar mRefreshViewProgress; private TextView mRefreshViewLastUpdated; private int mCurrentScrollState; private int mRefreshState; private RotateAnimation mFlipAnimation; private RotateAnimation mReverseFlipAnimation; private int mRefreshViewHeight; private int mRefreshOriginalTopPadding; private int mLastMotionY; private GestureDetector mDetector; // private int mPadding; public PullToRefreshListView(Context context) { super(context); init(context); } public PullToRefreshListView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public PullToRefreshListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); } private void init(Context context) { GestureDetector localGestureDetector = new GestureDetector(this); this.mDetector = localGestureDetector; // Load all of the animations we need in code rather than through XML mFlipAnimation = new RotateAnimation(0, -180, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); mFlipAnimation.setInterpolator(new LinearInterpolator()); mFlipAnimation.setDuration(200); mFlipAnimation.setFillAfter(true); mReverseFlipAnimation = new RotateAnimation(-180, 0, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); mReverseFlipAnimation.setInterpolator(new LinearInterpolator()); mReverseFlipAnimation.setDuration(200); mReverseFlipAnimation.setFillAfter(true); mInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); mRefreshView = (LinearLayout) mInflater.inflate( R.layout.pull_to_refresh_header, null); mRefreshViewText = (TextView) mRefreshView .findViewById(R.id.pull_to_refresh_text); mRefreshViewImage = (ImageView) mRefreshView .findViewById(R.id.pull_to_refresh_image); mRefreshViewProgress = (ProgressBar) mRefreshView .findViewById(R.id.pull_to_refresh_progress); mRefreshViewLastUpdated = (TextView) mRefreshView .findViewById(R.id.pull_to_refresh_updated_at); mRefreshViewImage.setMinimumHeight(50); mRefreshView.setOnClickListener(new OnClickRefreshListener()); mRefreshOriginalTopPadding = mRefreshView.getPaddingTop(); mRefreshState = TAP_TO_REFRESH; addHeaderView(mRefreshView); super.setOnScrollListener(this); measureView(mRefreshView); mRefreshViewHeight = mRefreshView.getMeasuredHeight(); } @Override public void setAdapter(ListAdapter adapter) { super.setAdapter(adapter); setSelection(1); } /** * Set the listener that will receive notifications every time the list * scrolls. * * @param l * The scroll listener. */ @Override public void setOnScrollListener(AbsListView.OnScrollListener l) { mOnScrollListener = l; } /** * Register a callback to be invoked when this list should be refreshed. * * @param onRefreshListener * The callback to run. */ public void setOnRefreshListener(OnRefreshListener onRefreshListener) { mOnRefreshListener = onRefreshListener; } /** * Set a text to represent when the list was last updated. * * @param lastUpdated * Last updated at. */ public void setLastUpdated(CharSequence lastUpdated) { if (lastUpdated != null) { mRefreshViewLastUpdated.setVisibility(View.VISIBLE); mRefreshViewLastUpdated.setText(lastUpdated); } else { mRefreshViewLastUpdated.setVisibility(View.GONE); } } @Override /** * TODO:此方法重写 */ public boolean onTouchEvent(MotionEvent event) { GestureDetector localGestureDetector = this.mDetector; localGestureDetector.onTouchEvent(event); final int y = (int) event.getY(); Log.d(TAG, String.format( "[onTouchEvent]event.Action=%d, currState=%d, refreshState=%d,y=%d", event.getAction(), mCurrentScrollState, mRefreshState, y)); switch (event.getAction()) { case MotionEvent.ACTION_UP: if (!isVerticalScrollBarEnabled()) { setVerticalScrollBarEnabled(true); } if (getFirstVisiblePosition() == 0 && mRefreshState != REFRESHING) { if ((mRefreshView.getBottom() >= mRefreshViewHeight + MAXHEIGHT || mRefreshView .getTop() >= 0)) { // Initiate the refresh mRefreshState = REFRESHING; prepareForRefresh(); onRefresh(); } else if (mRefreshView.getBottom() < mRefreshViewHeight + MAXHEIGHT || mRefreshView.getTop() <= 0) { // Abort refresh and scroll down below the refresh view resetHeader(); setSelection(1); } } break; case MotionEvent.ACTION_DOWN: mLastMotionY = y; break; case MotionEvent.ACTION_MOVE: applyHeaderPadding(event); break; } return super.onTouchEvent(event); } /** * TODO:此方法重写 * @param ev */ private void applyHeaderPadding(MotionEvent ev) { final int historySize = ev.getHistorySize(); Log.d(TAG, String.format( "[applyHeaderPadding]currState=%d, refreshState=%d", mCurrentScrollState, mRefreshState)); // Workaround for getPointerCount() which is unavailable in 1.5 // (it's always 1 in 1.5) int pointerCount = 1; try { Method method = MotionEvent.class.getMethod("getPointerCount"); pointerCount = (Integer) method.invoke(ev); } catch (NoSuchMethodException e) { pointerCount = 1; } catch (IllegalArgumentException e) { throw e; } catch (IllegalAccessException e) { System.err.println("unexpected " + e); } catch (InvocationTargetException e) { System.err.println("unexpected " + e); } if (mRefreshState == RELEASE_TO_REFRESH) { // this.offsetTopAndBottom(-mPadding); for (int h = 0; h < historySize; h++) { for (int p = 0; p < pointerCount; p++) { if (isVerticalFadingEdgeEnabled()) { setVerticalScrollBarEnabled(false); } int historicalY = 0; try { // For Android > 2.0 Method method = MotionEvent.class.getMethod( "getHistoricalY", Integer.TYPE, Integer.TYPE); historicalY = ((Float) method.invoke(ev, p, h)) .intValue(); } catch (NoSuchMethodException e) { // For Android < 2.0 historicalY = (int) (ev.getHistoricalY(h)); } catch (IllegalArgumentException e) { throw e; } catch (IllegalAccessException e) { System.err.println("unexpected " + e); } catch (InvocationTargetException e) { System.err.println("unexpected " + e); } // Calculate the padding to apply, we divide by 1.7 to // simulate a more resistant effect during pull. int topPadding = (int) (((historicalY - mLastMotionY) - mRefreshViewHeight) / 1.7); // Log.d(TAG, // String.format( // "[applyHeaderPadding]historicalY=%d,topPadding=%d,mRefreshViewHeight=%d,mLastMotionY=%d", // historicalY, topPadding, // mRefreshViewHeight, mLastMotionY)); mRefreshView.setPadding(mRefreshView.getPaddingLeft(), topPadding, mRefreshView.getPaddingRight(), mRefreshView.getPaddingBottom()); } } } } /** * Sets the header padding back to original size. */ private void resetHeaderPadding() { Log.d(TAG, String.format( "[resetHeaderPadding]currState=%d, refreshState=%d", mCurrentScrollState, mRefreshState)); // invalidate(); //this.mPadding=0; //this.offsetTopAndBottom(this.mPadding); mRefreshView.setPadding(mRefreshView.getPaddingLeft(), mRefreshOriginalTopPadding, mRefreshView.getPaddingRight(), mRefreshView.getPaddingBottom()); } /** * Resets the header to the original state. */ private void resetHeader() { Log.d(TAG, String.format("[resetHeader]currState=%d, refreshState=%d", mCurrentScrollState, mRefreshState)); if (mRefreshState != TAP_TO_REFRESH) { mRefreshState = TAP_TO_REFRESH; resetHeaderPadding(); // Set refresh view text to the pull label // mRefreshViewText.setText(R.string.pull_to_refresh_tap_label);//点击刷新是否有用 mRefreshViewText.setText(R.string.pull_to_refresh_pull_label); // Replace refresh drawable with arrow drawable mRefreshViewImage .setImageResource(R.drawable.ic_pulltorefresh_arrow); // Clear the full rotation animation mRefreshViewImage.clearAnimation(); // Hide progress bar and arrow. mRefreshViewImage.setVisibility(View.GONE); mRefreshViewProgress.setVisibility(View.GONE); } } private void measureView(View child) { Log.d(TAG, String.format("[measureView]currState=%d, refreshState=%d", mCurrentScrollState, mRefreshState)); ViewGroup.LayoutParams p = child.getLayoutParams(); if (p == null) { p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width); int lpHeight = p.height; int childHeightSpec; if (lpHeight > 0) { childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY); } else { childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } child.measure(childWidthSpec, childHeightSpec); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { Log.d(TAG, "List onScroll"); if (mCurrentScrollState == SCROLL_STATE_FLING && firstVisibleItem == 0 && mRefreshState != REFRESHING) { setSelection(1); mRefreshViewImage.setVisibility(View.INVISIBLE); } if (mOnScrollListener != null) { mOnScrollListener.onScroll(this, firstVisibleItem, visibleItemCount, totalItemCount); } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { mCurrentScrollState = scrollState; if (mOnScrollListener != null) { mOnScrollListener.onScrollStateChanged(view, scrollState); } } public void prepareForRefresh() { resetHeaderPadding(); mRefreshViewImage.setVisibility(View.GONE); // We need this hack, otherwise it will keep the previous drawable. mRefreshViewImage.setImageDrawable(null); mRefreshViewProgress.setVisibility(View.VISIBLE); // Set refresh view text to the refreshing label mRefreshViewText.setText(R.string.pull_to_refresh_refreshing_label); mRefreshState = REFRESHING; } public void onRefresh() { Log.d(TAG, "onRefresh"); if (mOnRefreshListener != null) { mOnRefreshListener.onRefresh(); } } /** * Resets the list to a normal state after a refresh. * * @param lastUpdated * Last updated at. */ public void onRefreshComplete(CharSequence lastUpdated) { setLastUpdated(lastUpdated); onRefreshComplete(); } /** * Resets the list to a normal state after a refresh. */ public void onRefreshComplete() { Log.d(TAG, "onRefreshComplete"); resetHeader(); // If refresh view is visible when loading completes, scroll down to // the next item. if (mRefreshView.getBottom() > 0) { invalidateViews(); // setSelection(1); } } /** * Invoked when the refresh view is clicked on. This is mainly used when * there's only a few items in the list and it's not possible to drag the * list. */ private class OnClickRefreshListener implements OnClickListener { @Override public void onClick(View v) { if (mRefreshState != REFRESHING) { prepareForRefresh(); onRefresh(); } } } /** * Interface definition for a callback to be invoked when list should be * refreshed. */ public interface OnRefreshListener { /** * Called when the list should be refreshed. * <p> * A call to {@link PullToRefreshListView #onRefreshComplete()} is * expected to indicate that the refresh has completed. */ public void onRefresh(); } @Override public boolean onDown(MotionEvent e) { // TODO Auto-generated method stub return false; } @Override public void onShowPress(MotionEvent e) { // TODO Auto-generated method stub } @Override public boolean onSingleTapUp(MotionEvent e) { // TODO Auto-generated method stub return false; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { int firstVisibleItem = this.getFirstVisiblePosition(); // When the refresh view is completely visible, change the text to say // "Release to refresh..." and flip the arrow drawable. Log.d(TAG, String.format( "[OnScroll]first=%d, currState=%d, refreshState=%d", firstVisibleItem, mCurrentScrollState, mRefreshState)); if (mCurrentScrollState == SCROLL_STATE_TOUCH_SCROLL && mRefreshState != REFRESHING) { if (firstVisibleItem == 0) { mRefreshViewImage.setVisibility(View.VISIBLE); // Log.d(TAG, // String.format( // "getBottom=%d,refreshViewHeight=%d,getTop=%d,mRefreshOriginalTopPadding=%d", // mRefreshView.getBottom(), mRefreshViewHeight // + MAXHEIGHT, // this.getTopPaddingOffset(), // mRefreshOriginalTopPadding)); if ((mRefreshView.getBottom() >= mRefreshViewHeight + MAXHEIGHT || mRefreshView .getTop() >= 0) && mRefreshState != RELEASE_TO_REFRESH) { //this.mPadding+=distanceY;//备用 mRefreshViewText .setText(R.string.pull_to_refresh_release_label); mRefreshViewImage.clearAnimation(); mRefreshViewImage.startAnimation(mFlipAnimation); mRefreshState = RELEASE_TO_REFRESH; } else if (mRefreshView.getBottom() < mRefreshViewHeight + MAXHEIGHT && mRefreshState != PULL_TO_REFRESH) { mRefreshViewText .setText(R.string.pull_to_refresh_pull_label); if (mRefreshState != TAP_TO_REFRESH) { mRefreshViewImage.clearAnimation(); mRefreshViewImage.startAnimation(mReverseFlipAnimation); } mRefreshState = PULL_TO_REFRESH; } } else { mRefreshViewImage.setVisibility(View.GONE); resetHeader(); } } /*not execute else if (mCurrentScrollState == SCROLL_STATE_FLING && firstVisibleItem == 0 && mRefreshState != REFRESHING) { setSelection(1); }*/ return false; } @Override public void onLongPress(MotionEvent e) { // TODO Auto-generated method stub } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // TODO Auto-generated method stub return false; } }
061304011116lyj-lyj
src/com/markupartist/android/widget/PullToRefreshListView.java
Java
asf20
15,869
#!/bin/bash # 打开apache.http调试信息 adb shell setprop log.tag.org.apache.http VERBOSE adb shell setprop log.tag.org.apache.http.wire VERBOSE adb shell setprop log.tag.org.apache.http.headers VERBOSE echo "Enable Debug"
061304011116lyj-lyj
tools/openHttpDebug.sh
Shell
asf20
229
/* Javadoc 样式表 */ /* 在此处定义颜色、字体和其他样式属性以覆盖默认值 */ /* 页面背景颜色 */ body { background-color: #FFFFFF; color:#000000 } /* 标题 */ h1 { font-size: 145% } /* 表格颜色 */ .TableHeadingColor { background: #CCCCFF; color:#000000 } /* 深紫色 */ .TableSubHeadingColor { background: #EEEEFF; color:#000000 } /* 淡紫色 */ .TableRowColor { background: #FFFFFF; color:#000000 } /* 白色 */ /* 左侧的框架列表中使用的字体 */ .FrameTitleFont { font-size: 100%; font-family: Helvetica, Arial, sans-serif; color:#000000 } .FrameHeadingFont { font-size: 90%; font-family: Helvetica, Arial, sans-serif; color:#000000 } .FrameItemFont { font-size: 90%; font-family: Helvetica, Arial, sans-serif; color:#000000 } /* 导航栏字体和颜色 */ .NavBarCell1 { background-color:#EEEEFF; color:#000000} /* 淡紫色 */ .NavBarCell1Rev { background-color:#00008B; color:#FFFFFF} /* 深蓝色 */ .NavBarFont1 { font-family: Arial, Helvetica, sans-serif; color:#000000;color:#000000;} .NavBarFont1Rev { font-family: Arial, Helvetica, sans-serif; color:#FFFFFF;color:#FFFFFF;} .NavBarCell2 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF; color:#000000} .NavBarCell3 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF; color:#000000}
061304011116lyj-lyj
doc/stylesheet.css
CSS
asf20
1,370
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.jh.query.jquery; import java.util.ArrayList; import java.util.List; /** * * @author namhh */ public class main { public static void main(String[] args) { BCol bCol1 = new BCol("A", 1); BCol bCol2 = new BCol("B", (Double).6876); BTable bTable = new BTable("AB"); bTable.addCol(bCol1).addCol(bCol2).addCol(bCol2); List l = new ArrayList(); l.add(bCol2); System.out.println( bTable.QUERY.setSelectedColumns(bCol1) .setSelectedColumns(bCol2) .addCondtion(BTable.TYPE.AND, bCol2, BTable.OPERATION.EQUAL, 1) .join(bTable.QUERY, BTable.JOIN_TYPE.INNER_JOIN, l) .toQueryString()); System.out.println(bTable.QUERY.toQueryString()); } }
1001files
trunk/jquery/JQuery/src/com/jh/query/jquery/main.java
Java
asf20
1,034
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.jh.query.jquery; /** * * @author namhh * @param <_Type> */ public class BCol<_Type extends Object> implements Cloneable { private String colname; private _Type value; private boolean isPk = false; private int index = -1; public BCol(String colname, _Type value) { this.colname = colname; this.value = value; } public boolean isPrimaryKey() { return isPk; } public void setPrimaryKey() { isPk = true; } public void setPrimaryKey(boolean isPrimaryKey) { isPk = isPrimaryKey; } public _Type getValue() { return value; } public String getCoumnName() { return colname; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public void setValue(_Type value) { this.value = value; } @Override public String toString() { return this.colname; //To change body of generated methods, choose Tools | Templates. } }
1001files
trunk/jquery/JQuery/src/com/jh/query/jquery/BCol.java
Java
asf20
1,265
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.jh.query.jquery; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * * @author namhh */ public class BTable { private String _tableName; public Query QUERY; public BTable(String tableName) { _tableName = tableName; QUERY = new Query(); } private Set<BCol> cols = new HashSet<>(); public BTable addCol(BCol bcol) { cols.add(bcol); return this; } public String aliasName() { return hashCode() + ""; } protected enum TYPE { AND(" AND "), OR(" OR "), INNER_JOIN(" INNER JOIN "); private final String type; private TYPE(String type) { this.type = type; } public String getVal() { return type; } } protected enum JOIN_TYPE { INNER_JOIN(" INNER JOIN "); private final String type; private JOIN_TYPE(String type) { this.type = type; } public String getVal() { return type; } } protected enum OPERATION { EQUAL(" = "), LESS_EQUAL(" <= "), GREATER_EQUAL(" >= "); private final String type; private OPERATION(String type) { this.type = type; } public String getVal() { return type; } } public class Query { private final List<BCol> selectedColumns = new ArrayList<BCol>(); private String _where = " "; private String _join = " "; public Query setSelectedColumns(BCol column) { selectedColumns.add(column); return this; } public String getEntityAlias() { return "t" + aliasName(); } public String getEntityOperation() { return "t" + aliasName() + "."; } private String getSELECT() { String ret = " SELECT "; if (!selectedColumns.isEmpty()) { for (int i = 0; i < selectedColumns.size(); i++) { ret += " " + getEntityOperation() + selectedColumns.get(i); if (i + 1 < selectedColumns.size()) { ret += " , "; } } } else { ret += " * "; } return ret; } private String getFROM() { return " FROM " + _tableName + " " + getEntityAlias(); } public Query addCondtion(TYPE type, BCol cols, OPERATION operation, Object val) { String col = getEntityOperation() + cols; if (val instanceof String) { val = "LOWER('" + val + "')"; col = "LOWER(" + cols + ")"; } if (_where.contains("WHERE")) { _where += type.getVal() + col + operation.getVal() + val; } else { _where += "WHERE " + col + operation.getVal() + val; } return this; } public Query join(Query other, JOIN_TYPE type, List<BCol> joinOn) { String on = ""; for (int i = 0; i < joinOn.size(); i++) { on += getEntityOperation() + joinOn.get(i) + " = " + other.getEntityOperation() + joinOn.get(i); if (i + 1 < joinOn.size()) { on += " AND "; } } _join = type.getVal() + "\n (" + other.toQueryString() + "\n" + " )" + other.getEntityAlias() + " \n ON" + "(" + on + ")"; return this; } public String toQueryString() { String ret = getSELECT() + "\n" + getFROM() + "\n" + _join + "\n" + _where; clear(); return ret; } public void clear() { selectedColumns.clear(); _join = ""; _where = ""; } } }
1001files
trunk/jquery/JQuery/src/com/jh/query/jquery/BTable.java
Java
asf20
4,155
import com.jh.jutil.worker.Pool; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author namhh */ public class SimplePoolImp extends Pool{ }
1001files
trunk/jutil/test/SimplePoolImp.java
Java
asf20
297
import com.jh.jutil.worker.MonitorPool; import com.jh.jutil.worker.Observer; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author namhh */ public class PoolImp extends MonitorPool{ @Override public void alert(Observer observer, Object value) { System.out.println( " Recieve alert : " +value); } }
1001files
trunk/jutil/test/PoolImp.java
Java
asf20
472
import com.jh.jutil.worker.Subject; import com.jh.jutil.worker.AlertJob; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author namhh */ public class AlertJobImp extends AlertJob { public AlertJobImp(Subject subject) { super(subject); } @Override public void run() { System.out.println("Run " + this.getJobName()); subject.alert(this, " DONE "); System.out.println( this.getJobName() + " DONE"); } @Override public int update(Object object) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public int noftify(Object object) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
1001files
trunk/jutil/test/AlertJobImp.java
Java
asf20
1,000
import com.jh.jutil.worker.Job; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author namhh */ public class JobImp extends Job{ @Override public void run() { System.out.println(this.getJobName() + "DONE"); } }
1001files
trunk/jutil/test/JobImp.java
Java
asf20
389
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.jh.jutil.sql.client; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; /** * * @author root */ public class MysqlClient { private final String _host; private final int _port; private final String _dbname; private final String _user; private final String _password; private BlockingQueue<Connection> pool; private String url; public static MysqlClient _instance; public MysqlClient(String _host, int _port, String _dbname, String _user, String _password, int poolSize) { this._host = _host; this._port = _port; this._dbname = _dbname; this._user = _user; this._password = _password; init(poolSize); } private boolean init(int poolsize) { try { Class.forName("com.mysql.jdbc.Driver"); url = "jdbc:mysql://" + _host + ":" + _port + "/" + _dbname + "?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&interactiveClient=true&" + "&user=" + _user + "&password=" + _password; BlockingQueue<Connection> cnnPool = new ArrayBlockingQueue<Connection>(poolsize); while (cnnPool.size() < poolsize) { cnnPool.add(DriverManager.getConnection(url)); } pool = cnnPool; } catch (Exception ex) { return false; } return true; } public Connection getDbConnection() { Connection conn = null; int retry = 0; do { try { conn = pool.poll(10000, TimeUnit.MILLISECONDS); if (conn == null || !conn.isValid(0)) { conn = DriverManager.getConnection(url); } } catch (Exception ex) { } ++retry; } while (conn == null && retry < 3); return conn; } public void releaseDbConnection(java.sql.Connection conn) { if (conn != null) { pool.add(conn); } } public void importData(String tableName, String filename) { Statement stmt; String query; Connection conn = getDbConnection(); if (conn == null) { return; } try { stmt = conn.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); query = "LOAD DATA LOCAL INFILE '" + filename + "' REPLACE INTO TABLE " + tableName; stmt.executeUpdate(query); } catch (Exception e) { stmt = null; } finally { releaseDbConnection(conn); } } }
1001files
trunk/jutil/src/com/jh/jutil/sql/client/MysqlClient.java
Java
asf20
3,040
package com.jh.jutil.helper; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.security.MessageDigest; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * @author */ public class UtilHelper { public static final Charset charset = Charset.forName("UTF-8"); public static final CharsetEncoder encoder = charset.newEncoder(); public static final CharsetDecoder decoder = charset.newDecoder(); private static final Random rand = new Random(); public static String md5(String str) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte byteData[] = md.digest(); //convert the byte to hex format method 1 StringBuilder sb = new StringBuilder(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); } catch (Exception ex) { return ""; } } public static ByteBuffer strToBB(String msg) { try { return encoder.encode(CharBuffer.wrap(msg)); } catch (Exception e) { } return null; } public static ByteBuffer longToBB(long l) { ByteBuffer buffer = ByteBuffer.allocateDirect(8); buffer.putLong(l); buffer.flip(); return buffer; } public static long bbToL(ByteBuffer buffer) { int old_position = buffer.position(); long l = buffer.getLong(); buffer.position(old_position); return l; } public static String bbToStr(ByteBuffer buffer) { String data = ""; try { int old_position = buffer.position(); data = decoder.decode(buffer).toString(); buffer.position(old_position); } catch (Exception e) { } return data; } public static String toASCII(String text) { if (text == null) { return ""; } text = text.replaceAll(" ", ""); text = text.toLowerCase(); text = text.replaceAll("à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ", "a"); text = text.replaceAll("è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ", "e"); text = text.replaceAll("ì|í|ị|ỉ|ĩ", "i"); text = text.replaceAll("ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ", "o"); text = text.replaceAll("ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ", "u"); text = text.replaceAll("ỳ|ý|ỵ|ỷ|ỹ", "y"); text = text.replaceAll("đ", "d"); text = text.replaceAll("!|@|%|\\^|\\*|\\(|\\)|\\+|\\=|\\<|\\>|\\?|\\/|,|\\.|\\:|\\;|\\'|\\\"|\\&|\\#|\\[|\\]|~|$|_", "-"); text = text.replaceAll("-+-", "-"); text = text.replaceAll("^\\-+|\\-+$", ""); return text; } public static String filterUnicodeToASCII(String str) { String rs = ""; String[] marTViet = new String[]{"à", "á", "ạ", "ả", "ã", "â", "ầ", "ấ", "ậ", "ẩ", "ẫ", "ă", "ằ", "ắ", "ặ", "ẳ", "ẵ", "è", "é", "ẹ", "ẻ", "ẽ", "ê", "ề", "ế", "ệ", "ể", "ễ", "ì", "í", "ị", "ỉ", "ĩ", "ò", "ó", "ọ", "ỏ", "õ", "ô", "ồ", "ố", "ộ", "ổ", "ỗ", "ơ", "ờ", "ớ", "ợ", "ở", "ỡ", "ù", "ú", "ụ", "ủ", "ũ", "ư", "ừ", "ứ", "ự", "ử", "ữ", "ỳ", "ý", "ỵ", "ỷ", "ỹ", "đ", "À", "Á", "Ạ", "Ả", "Ã", "Â", "Ầ", "Ấ", "Ậ", "Ẩ", "Ẫ", "Ă", "Ằ", "Ắ", "Ặ", "Ẳ", "Ẵ", "È", "É", "Ẹ", "Ẻ", "Ẽ", "Ê", "Ề", "Ế", "Ệ", "Ể", "Ễ", "Ì", "Í", "Ị", "Ỉ", "Ĩ", "Ò", "Ó", "Ọ", "Ỏ", "Õ", "Ô", "Ồ", "Ố", "Ộ", "Ổ", "Ỗ", "Ơ", "Ờ", "Ớ", "Ợ", "Ở", "Ỡ", "Ù", "Ú", "Ụ", "Ủ", "Ũ", "Ư", "Ừ", "Ứ", "Ự", "Ử", "Ữ", "Ỳ", "Ý", "Ỵ", "Ỷ", "Ỹ", "Đ"}; String[] marKoDau = new String[]{"a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "i", "i", "i", "i", "i", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "u", "u", "u", "u", "u", "u", "u", "u", "u", "u", "u", "y", "y", "y", "y", "y", "d", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "E", "E", "E", "E", "E", "E", "E", "E", "E", "E", "E", "I", "I", "I", "I", "I", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "U", "U", "U", "U", "U", "U", "U", "U", "U", "U", "U", "Y", "Y", "Y", "Y", "Y", "D"}; rs = str; for (int index = 0; index < marTViet.length; ++index) { rs = rs.replace(marTViet[index], marKoDau[index]); } return rs; } public static long getTime(String strDate, String format) { if (format == null) { format = "dd/MM/yyyy HH:mm:ss"; } long result = 0; try { if (strDate != null && !strDate.isEmpty()) { DateFormat formatter; Date date; formatter = new SimpleDateFormat(format); date = (Date) formatter.parse(strDate); result = date.getTime(); } else { result = System.currentTimeMillis(); } } catch (ParseException e) { System.out.println("Exception :" + e); } return result; } public static String getStrDate(long time, String format) { if (format == null || format.isEmpty()) { format = "dd - MM - yyyy"; } DateFormat dateFormat = new SimpleDateFormat(format); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(time); String result = dateFormat.format(cal.getTime()); return (result != null ? result : ""); } public static boolean validateURL(String url) { // String rex = "((([A-Za-z]{3,9}:(?:\\/\\/)?)(?:[-;:&=\\+\\$,\\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\\+\\$,\\w]+@)[A-Za-z0-9.-]+)((?:\\/[\\+~%\\/.\\w-_]*)?\\??(?:[-\\+=&;%@.\\w_]*)#?(?:[\\w]*))?)"; String rex = "^(https?:\\/\\/)" + // protocol "((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|" + // domain name "((\\d{1,3}\\.){3}\\d{1,3}))" + // OR ip (v4) address "(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*" + // port and path "(\\?[;&a-z\\d%_.~+=-]*)?" + // query string "(\\#[-a-z\\d_]*)?$"; // fragment locater // return url.matches(rex); return true; } public static boolean validateEmail(String hex) { String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; Pattern pattern = Pattern.compile(EMAIL_PATTERN); Matcher matcher = pattern.matcher(hex); return matcher.matches(); } public static boolean validateUsername(String hex) { String USERNAME_PATTERN = "^(?=.{6,24}$)(?![_.])(?![0-9])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$"; Pattern pattern = Pattern.compile(USERNAME_PATTERN); Matcher matcher = pattern.matcher(hex); return matcher.matches(); } public static boolean validateDisplayname(String hex) { hex = filterUnicodeToASCII(hex); String DISPLAYNAME_PATTERN = "^[a-zA-Z0-9 ]{1,50}$"; Pattern pattern = Pattern.compile(DISPLAYNAME_PATTERN); Matcher matcher = pattern.matcher(hex); return matcher.matches(); } public static boolean validatePhone(String phone) { String PHONE_PATTERN = "^\\+?[0-9]{6,24}$"; Pattern pattern = Pattern.compile(PHONE_PATTERN); Matcher matcher = pattern.matcher(phone); return matcher.matches(); } public static List<String> splitStrToList(String str, String regex) { String[] tempArr = str.split(regex); List<String> result = new ArrayList(); if (tempArr != null && tempArr.length > 0) { Collections.addAll(result, tempArr); } return result; } public static String zenCaptcha(int numchar) { String code = ""; for (int i = 0; i < numchar; ++i) { code += String.valueOf(rand.nextInt(9)); } return code; } public static ByteBuffer getByteBufferFromFile(String path) { ByteBuffer buff = null; File fcover = new File(path); if (fcover.exists()) { FileInputStream fileStream; try { fileStream = new FileInputStream(fcover); ByteArrayOutputStream byteArray = new ByteArrayOutputStream(); byte[] read = new byte[2048]; int i = 0; while ((i = fileStream.read(read)) > 0) { byteArray.write(read, 0, i); } fileStream.close(); buff = ByteBuffer.wrap(byteArray.toByteArray()); } catch (Exception ex) { } } return buff; } public static String strtrim(String str) { String rs = str; int length; do { length = rs.length(); rs = rs.replace(" ", " "); } while (length != rs.length()); return rs; } public static String hashMediaName(String filename) { String rs = ""; int pos = filename.lastIndexOf("."); if (pos > -1) { String name = filename.substring(0, pos); String type = filename.substring(pos + 1, filename.length()); name = strtrim(name); name = filterUnicodeToASCII(name); name = md5(name); name += "_" + System.currentTimeMillis(); rs = name + "." + type; } return rs; } public static String escapeHTML(String html) { if (html != null) { return html.replaceAll("\\<.*?\\>", ""); } return ""; } public static String xssRemove(String content) { if (content == null) { return ""; } return content.replaceAll("(?i)<script.*?>.*?</script.*?>", "") // case 1 .replaceAll("(?i)<.*?javascript:.*?>.*?</.*?>", "") // case 2 .replaceAll("(?i)<.*?\\s+on.*?>.*?</.*?>", ""); // case 3 } public static String safeStr(String content) { content = xssRemove(content); content = escapeHTML(content); content = strtrim(content); return content; } }
1001files
trunk/jutil/src/com/jh/jutil/helper/UtilHelper.java
Java
asf20
10,972
package com.jh.jutil.worker; import java.util.HashSet; import java.util.Set; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author namhh */ public abstract class MonitorPool extends Pool implements Subject { private Set<Observer> obsersvers = new HashSet<>(); @Override public void add(Observer observer) { obsersvers.add(observer); } @Override public void remove(Observer observer) { obsersvers.remove(observer); } }
1001files
trunk/jutil/src/com/jh/jutil/worker/MonitorPool.java
Java
asf20
619
package com.jh.jutil.worker; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author namhh */ public abstract class Job implements Runnable{ private String jobName; public String getJobName() { if (jobName == null || jobName.isEmpty()) { return " {JOB} " + this.hashCode() + " "; } return " {JOB} " + jobName + " "; } public void setJobName(String jobName) { this.jobName = jobName; } @Override public String toString() { return getJobName(); } }
1001files
trunk/jutil/src/com/jh/jutil/worker/Job.java
Java
asf20
686
package com.jh.jutil.worker; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author namhh */ public interface Subject { void add(Observer observer); void remove(Observer observer); void alert(Observer observer,Object value); }
1001files
trunk/jutil/src/com/jh/jutil/worker/Subject.java
Java
asf20
393
package com.jh.jutil.worker; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author namhh */ public abstract class Pool { private static final int _corePoolSize = 10; private static final int _maxPoolSize = 18; private static final long _keepAliveTime = 5000; private final ThreadPoolExecutor _threadPoolExecutor = new ThreadPoolExecutor( _corePoolSize, _maxPoolSize, _keepAliveTime, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(5000) ); public void excute(Job job) { _threadPoolExecutor.execute(job); } public Pool setRejectedExecutionHandler(final long timeout) { _threadPoolExecutor.setRejectedExecutionHandler(new RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { try { Thread.sleep(timeout); executor.execute(r); } catch (Exception ex) { ex.printStackTrace(); } } }); return this; } public void shutdown(long timeOutBySecond) { try { _threadPoolExecutor.shutdown(); _threadPoolExecutor.awaitTermination(timeOutBySecond, TimeUnit.SECONDS); } catch (InterruptedException ex) { ex.printStackTrace(); } } }
1001files
trunk/jutil/src/com/jh/jutil/worker/Pool.java
Java
asf20
1,865
package com.jh.jutil.worker; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author namhh */ public interface Observer { int update(Object object); int noftify(Object object); }
1001files
trunk/jutil/src/com/jh/jutil/worker/Observer.java
Java
asf20
344
package com.jh.jutil.worker; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author namhh */ public abstract class AlertJob extends Job implements Observer { protected Subject subject; public AlertJob(Subject subject) { this.subject = subject; } }
1001files
trunk/jutil/src/com/jh/jutil/worker/AlertJob.java
Java
asf20
424
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>0597玩棋牌游戏平台</title> <link rel="stylesheet" type="text/css" href="css/style.css"/> </head> <body> <!--top start--> <div class="top"> <div class="guardianship"> <ul> <li><a href="#" title="家长监护"><img src="images/guardianship.gif" /></a></li> </ul> </div> <div class="nav"> <div class="logo"> <a href="#" title="主页"><img src="images/logo.jpg" /></a> </div> <div class="menu"> <ul> <li><a href="#" title="官网首页">官网首页</a></li> <li><a href="#" title="下载中心">下载中心</a></li> <li><a href="#" title="领奖中心">领奖中心</a></li> <li><a href="#" title="账号管理">账号管理</a></li> <li><a href="#" title="充值中心">充值中心</a></li> <li><a href="#" title="帮助">帮助</a></li> </ul> </div> </div> </div> <!--top end--> <!--main start--> <div class="main"> <div class="download"> <div class="main_left"> <!--快捷通道开始--> <div class="kjtd"> <ul class="kjtd_title"> <li>快捷通道</li> </ul> <ul class="kjtd_list"> <li class="account_ico"><a href="#" title="">账号管理</a></li> <li class="recharge_ico"><a href="#" title="">充值中心</a></li> <li class="award_ico"><a href="#" title="">领奖中心</a></li> <li class="down_ico"><a href="#" title="">下载中心</a></li> <li class="help_ico"><a href="#" title="">新手帮助</a></li> </ul> </div> <!--快捷通道结束--> <!--在线客服开始--> <div class="zxkf"> <ul class="zxkf_title"> <li>在线客服</li> </ul> <ul class="zxkf_list"> <li>电话:40086-55006</li> <li>q&nbsp;&nbsp;q:133550597</li> <li class="qqonline_ico"><a href="#" title="">点击联系我们!</a></li> <li>邮箱:<a href="mailto:133550597@qq.com" title="">133550597@qq.com</a></li> </ul> </div> <!--在线客服结束--> </div> <div class="main_right"> <!--当前位置开始--> <div class="localtion"> <ul> <li class="arrow"><a href="#" title="首页">首页</a></li> <li class="arrow"><a href="#" title="下载中心">下载中心</a></li> </ul> </div> <!--当前位置结束--> <div class="full"> <ul> <li style="float:left;"><h3>完整版客户端下载</h3></li> <li><h6>(版本号:6.25.0.3 大小:111MB 支持系统:WIN8/WIN7/VISTA/XP)</h6></li> <li>1.、点击右侧的按钮下载游戏,下载完成后运行安装文件按照提示步骤完成安装。</li> <li>2.、安装完毕后,运行在桌面上生成的0597玩游戏图标开始游戏。</li> </ul> <ul> <li><a href="#" title="电信下载">电信下载</a></li> <li><a href="#" title="双线下载">双线下载</a></li> </ul> </div> <div class="lite"> <ul> <li style="float:left;"><h3>精简版客户端下载</h3></li> <li><h6>(版本号:6.25.0.3 大小:111MB 支持系统:WIN8/WIN7/VISTA/XP)</h6></li> <li>1.、点击右侧的按钮下载游戏,下载完成后运行安装文件按照提示步骤完成安装。</li> <li>2.、安装完毕后,运行在桌面上生成的0597玩游戏图标开始游戏。</li> </ul> <ul> <li><a href="#" title="电信下载">电信下载</a></li> <li><a href="#" title="双线下载">双线下载</a></li> </ul> </div> <div class="tips"> <ul> <li>温馨提示:为了解决您在下载过程中遇到的一些问题,请在下载的时间中阅读下载说明!(点击进入)</li> </ul> <div> </div> </div> </div> </div> </div> <!--main end--> <!--footer start--> <div class="footer"> <div class="links"> <ul> <li></li> </ul> </div> <div class="copyright"> <ul> <li>抵制不良游戏,拒绝盗版游戏。注意自我保护,谨防上当受骗。适度游戏益脑,沉迷游戏伤身。合理安排时间,享受健康生活。</li> <li>Copy Right@2012-2013 福建省网众网络科技有限公司 文网文 闽网文[2011]-0382-13号 互联网经营许可证 闽B2-20110073 版权所有:福建省网众网络科技有限公司</li> </ul> </div> </div> <!--footer end--> </body> </html>
0597wan
trunk/download.html
HTML
asf20
5,653
var banner_index=0;//图片下标值 var time; var banner_ico_now_count=0;//活动按钮当前值 var banner_url=""; function imagePlayer(){ if(images[banner_index]!=null) { APpendBannerIco(); } banner_index++; if(banner_index>=images.length)//循环完一次,重新初始化index { banner_index=0; } time= setTimeout("imagePlayer()",15000); } //为banner中背景及选中"按钮"一一对应赋值 function APpendBannerIco() { var temp = images.length; if(banner_ico_now_count >= images.length)//活动按钮循环完一次,清空重复加载 { $("banner_ico").innerHTML=""; } var ul =document.createElement("ul");//加载图片和对应按钮的值 for(var i = 0;i < images.length;i++) { temp--; var li =document.createElement("li"); li.style.width="20px"; li.innerHTML="<img src='/images/imgPlayer_dot.gif' width='12' height='12' style='cursor:pointer;' onmouseover=\"go("+i+");\"/>"; if(i==banner_index) { $("banner").style.background="url("+images[temp].imageUrl+")"; banner_url=images[temp].linkUrl; li.innerHTML="<img src='/images/imgPlayer_active.gif' width='12' height='12' style='cursor:pointer;' onmouseover=\"go("+i+");\"/>"; } ul.appendChild(li); banner_ico_now_count++; $("banner_link").innerHTML=""; $("banner_link").innerHTML="<a href='"+banner_url+"' target='_blank'><div style='width:510px; height:275px;cursor:pointer;'></div></a>"; } var ul_temp = document.createElement("ul");//最初创建顺序为至右往左反向,依次倒序调整。 var ul_count=ul.childNodes.length; var i_temp = ul.childNodes.length; for(var i=0;i< ul_count; i++) { i_temp--; var li_temp =document.createElement("li"); li_temp= ul.childNodes[i_temp]; ul_temp.appendChild(li_temp); } $("banner_ico").appendChild(ul_temp); } //点击按钮进行"跳转"图片操作 function go(index) { clearTimeout(time); banner_index = index; APpendBannerIco(); time= setTimeout("imagePlayer()",15000); } imagePlayer(); function ChangeImg(now_obj,change_img) { now_obj.src="/images/"+change_img; }
0597wan
trunk/js/banner.js
JavaScript
asf20
2,479
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>0597玩棋牌游戏平台</title> <link rel="stylesheet" type="text/css" href="css/style.css"/> <!--幻灯脚本--> <script language="javascript" type="text/javascript"> $=function(id){return document.getElementById(id);} String.prototype.trim = function(){return this.replace(/(^\s*)|(\s*$)/g, "");} function logonout(){ $("imgLogonout").src="Js/logonout.js"; setTimeout(reload,3000); } function reload(){window.location.href="/";} </script> <!--幻灯脚本--> </head> <body> <!--top start--> <div class="top"> <div class="guardianship"> <ul> <li><a href="#" title="家长监护"><img src="images/guardianship.gif" /></a></li> </ul> </div> <div class="nav"> <div class="logo"> <a href="#" title="主页"><img src="images/logo.jpg" /></a> </div> <div class="menu"> <ul> <li><a href="#" title="官网首页">官网首页</a></li> <li><a href="#" title="下载中心">下载中心</a></li> <li><a href="#" title="领奖中心">领奖中心</a></li> <li><a href="#" title="账号管理">账号管理</a></li> <li><a href="#" title="充值中心">充值中心</a></li> <li><a href="#" title="帮助">帮助</a></li> </ul> </div> </div> </div> <!--top end--> <!--main start--> <div class="main"> <div class="content_top"> <!--幻灯 start--> <div class="banner"> <div style="float:left;"> <div id="banner"> <div> <div> <ul style="float:left;"> <li><a href="#"><img width="108" height="40" src="images/download_1.png" alt="下载客户端" onMouseOver="ChangeImg(this,'download_2.png');" onMouseOut="ChangeImg(this,'download_1.png');"/></a></li> <li><a href="#"><img width="108" height="40" src="images/reg_1.png" alt="快捷网页版" onMouseOver="ChangeImg(this,'reg_2.png');" onMouseOut="ChangeImg(this,'reg_1.png');"/></a></li> <li><a href="#"><img width="108" height="40" src="images/game_1.png" alt="免注册试玩" onMouseOver="ChangeImg(this,'game_2.png');" onMouseOut="ChangeImg(this,'game_1.png');"/></a></li> <li><a href="#"><img width="108" height="40" src="images/login_1.png" alt="免注册试玩" onMouseOver="ChangeImg(this,'login_2.png');" onMouseOut="ChangeImg(this,'login_1.png');"/></a></li> </ul> </div> <div id="banner_link"> </div> </div> <div id="banner_ico"> </div> </div> <script language="javascript" type="text/javascript">var images=[{"linkUrl":"index.html","imageUrl":"images/banner_1.jpg"},{"linkUrl":"index.html","imageUrl":"images/banner_2.jpg"},{"linkUrl":"index.html","imageUrl":"images/banner_3.jpg"},{"linkUrl":"index.html","imageUrl":"images/banner_4.jpg"}] ;</script> <script language="javascript" type="text/javascript" src="Js/banner.js"></script> </div> </div> <!--幻灯 end--> <!--获奖荣誉榜 start--> <div class="honor"> <ul class="honor_title"> <li>获奖荣誉榜</li> </ul> <ul class="honor_header"> <li><span>昵称</span><span>财富</span></li> </ul> <div id="honor_list"> <ul id="honor_content"> <li class="honor_content"><span>恭喜一二三四五六</span><span>获得一等奖</span></li> <li class="honor_content"><span>恭喜一二三四五六</span><span>获得二等奖</span></li> <li class="honor_content"><span>恭喜一二三四五六</span><span>获得三等奖</span></li> <li class="honor_content"><span>恭喜一二三四五六</span><span>获得四等奖</span></li> <li class="honor_content"><span>恭喜一二三四五六</span><span>获得五等奖</span></li> <li class="honor_content"><span>恭喜一二三四五六</span><span>获得六等奖</span></li> <li class="honor_content"><span>恭喜一二三四五六</span><span>获得七等奖</span></li> <li class="honor_content"><span>恭喜一二三四五六</span><span>获得八等奖</span></li> <li class="honor_content"><span>恭喜一二三四五六</span><span>获得九等奖</span></li> <li class="honor_content"><span>恭喜一二三四五六</span><span>获得十等奖</span></li> <li class="honor_content"><span>恭喜一二三四五六</span><span>获得一等奖</span></li> <li class="honor_content"><span>恭喜一二三四五六</span><span>获得二等奖</span></li> <li class="honor_content"><span>恭喜一二三四五六</span><span>获得三等奖</span></li> <li class="honor_content"><span>恭喜一二三四五六</span><span>获得四等奖</span></li> <li class="honor_content"><span>恭喜一二三四五六</span><span>获得五等奖</span></li> <li class="honor_content"><span>恭喜一二三四五六</span><span>获得六等奖</span></li> </ul> </div> </div> <!--滚动脚本 start--> <SCRIPT language=JavaScript> <!-- function _InitScroll(_S1,_S2,_W,_H,_T){ return "var marqueesHeight"+_S1+"="+_H+";var stopscroll"+_S1+"=false;var scrollElem"+_S1+"=document.getElementById('"+_S1+"');with(scrollElem"+_S1+"){style.width="+_W+";style.height=marqueesHeight"+_S1+";style.overflow='hidden';noWrap=true;}scrollElem"+_S1+".onmouseover=new Function('stopscroll"+_S1+"=true');scrollElem"+_S1+".onmouseout=new Function('stopscroll"+_S1+"=false');var preTop"+_S1+"=0; var currentTop"+_S1+"=0; var stoptime"+_S1+"=0;var leftElem"+_S2+"=document.getElementById('"+_S2+"');scrollElem"+_S1+".appendChild(leftElem"+_S2+".cloneNode(true));setTimeout('init_srolltext"+_S1+"()',"+_T+");function init_srolltext"+_S1+"(){scrollElem"+_S1+".scrollTop=0;setInterval('scrollUp"+_S1+"()',50);}function scrollUp"+_S1+"(){if(stopscroll"+_S1+"){return;}currentTop"+_S1+"+=1;if(currentTop"+_S1+"==(marqueesHeight"+_S1+"+1)) {stoptime"+_S1+"+=1;currentTop"+_S1+"-=1;if(stoptime"+_S1+"=="+_T/50+") {currentTop"+_S1+"=0;stoptime"+_S1+"=0;}}else{preTop"+_S1+"=scrollElem"+_S1+".scrollTop;scrollElem"+_S1+".scrollTop +=1;if(preTop"+_S1+"==scrollElem"+_S1+".scrollTop){scrollElem"+_S1+".scrollTop=0;scrollElem"+_S1+".scrollTop +=1;}}}"; } eval(_InitScroll("honor_list","honor_content",217,31*9,1000)); //--> </SCRIPT> <!--滚动脚本 end--> <!--获奖荣誉榜 end--> </div> <div class="main_center"> <div class="content_left"> <div class="subnav"> <!--快捷通道 strat--> <div class="shortcut"> <ul class="shortcut_title"> <li>快捷通道</li> </ul> <div class="shortcut_list"> <ul> <li class="shortcut_content"><a href="" title="充值中心">充值中心</a></li> <li class="shortcut_content"><a href="" title="领奖中心">领奖中心</a></li> <li class="shortcut_content"><a href="" title="账号管理">账号管理</a></li> <li class="shortcut_content"><a href="" title="新手帮助">新手帮助</a></li> <li class="shortcut_content"><a href="" title="下载中心">下载中心</a></li> </ul> </div> </div> <!--快捷通道 end--> <!--客服中心 strat--> <div class="service"> <ul class="service_title"> <li>客服中心</li> </ul> <div class="service_list"> <ul> <li class="tell">电话:40086-55006</li> <li class="qq">q&nbsp;&nbsp;q:133550597</li> <li class="qqonline"><a href="#">点击联系我们!</a></li> <li class="mail"><a href="mailto:133550597@qq.com">133550597@qq.com</a></li> </ul> </div> </div> <!--客服中心 end--> </div> <div class="guild"> <!--公告、比赛、心得 strat--> <div class="tab"> <ul class="tab_title"> <li><a href="#" title="公告">公告</a></li> <li><a href="#" title="比赛">比赛</a></li> <li><a href="#" title="心得">心得</a></li> <li><a href="#" title="心得">心得</a></li> <li><a href="#" title="心得">心得</a></li> </ul> <div class="tab_list"> <ul class="block"> <li class="frist"><a href="#">【公告】麻将大赛3月3日正式开启!<span>【2013-03-08】</span></a></li> <li><a href="#">【公告】麻将大赛3月3日正式开启!<span>【2013-03-08】</span></a></li> <li><a href="#">【公告】麻将大赛3月3日正式开启!<span>【2013-03-08】</span></a></li> <li><a href="#">【公告】麻将大赛3月3日正式开启!<span>【2013-03-08】</span></a></li> <li><a href="#">【公告】麻将大赛3月3日正式开启!<span>【2013-03-08】</span></a></li> <li><a href="#">【公告】麻将大赛3月3日正式开启!<span>【2013-03-08】</span></a></li> </ul> <ul> <li class="frist"><a href="#">【比赛】麻将大赛3月3日正式开启!<span>【2013-03-08】</span></a></li> <li><a href="#">【比赛】麻将大赛3月3日正式开启!<span>【2013-03-08】</span></a></li> <li><a href="#">【比赛】麻将大赛3月3日正式开启!<span>【2013-03-08】</span></a></li> <li><a href="#">【比赛】麻将大赛3月3日正式开启!<span>【2013-03-08】</span></a></li> <li><a href="#">【比赛】麻将大赛3月3日正式开启!<span>【2013-03-08】</span></a></li> <li><a href="#">【比赛】麻将大赛3月3日正式开启!<span>【2013-03-08】</span></a></li> </ul> <ul> <li class="frist"><a href="#">【心得】麻将大赛3月3日正式开启!<span>【2013-03-08】</span></a></li> <li><a href="#">【心得】麻将大赛3月3日正式开启!<span>【2013-03-08】</span></a></li> <li><a href="#">【心得】麻将大赛3月3日正式开启!<span>【2013-03-08】</span></a></li> <li><a href="#">【心得】麻将大赛3月3日正式开启!<span>【2013-03-08】</span></a></li> <li><a href="#">【心得】麻将大赛3月3日正式开启!<span>【2013-03-08】</span></a></li> <li><a href="#">【心得】麻将大赛3月3日正式开启!<span>【2013-03-08】</span></a></li> </ul> </div> </div> <!--公告、比赛、心得 end--> <!--热门游戏 strat--> <div class="popular"> <ul class="popular_title"> <li>热门游戏</li> </ul> <div id="popular_list"> <div id="scrollPic"> <ul> <li class="ddz"><a href="#">斗地主</a></li> <li class="ppc"><a href="#">碰碰车</a></li> <li class="mj"><a href="#">麻将比赛</a></li> <li class="pj"><a href="#">牌九</a></li> <li class="nn"><a href="#">百人牛牛</a></li> <li class="shby"><a href="#">深海捕鱼</a></li> </ul> </div> </div> </div> <!--热门游戏 end--> </div> </div> <div class="content_right"> <!--财富排行榜开始--> <div class="wealth"> <ul class="wealth_title"> <li>财富排行榜</li> </ul> <ul class="wealth_header"> <li><span id="nc">昵称</span><span id="jp">奖品</span></li> </ul> <div class="wealth_list"> <ul> <li><span id="wealth_digital">01</span><span id="wealth_content">一二三四五六</span><span>99999999</span></li> <li><span id="wealth_digital">02</span><span id="wealth_content">一二三四五六</span><span>99999999</span></li> <li><span id="wealth_digital">03</span><span id="wealth_content">一二三四五六</span><span>99999999</span></li> <li><span id="wealth_digital">04</span><span id="wealth_content">一二三四五六</span><span>99999999</span></li> <li><span id="wealth_digital">05</span><span id="wealth_content">一二三四五六</span><span>99999999</span></li> <li><span id="wealth_digital">06</span><span id="wealth_content">一二三四五六</span><span>99999999</span></li> <li><span id="wealth_digital">07</span><span id="wealth_content">一二三四五六</span><span>99999999</span></li> <li><span id="wealth_digital">08</span><span id="wealth_content">一二三四五六</span><span>99999999</span></li> <li><span id="wealth_digital">09</span><span id="wealth_content">一二三四五六</span><span>99999999</span></li> <li><span id="wealth_digital">10</span><span id="wealth_content">一二三四五六</span><span>99999999</span></li> <li><span id="wealth_digital">11</span><span id="wealth_content">一二三四五六</span><span>99999999</span></li> <li><span id="wealth_digital">12</span><span id="wealth_content">一二三四五六</span><span>99999999</span></li> </ul> </div> </div> <!--财富排行榜结束--> </div> </div> </div> <!--main end--> <!--footer start--> <div class="footer"> <div class="links"> <ul> <li></li> </ul> </div> <div class="copyright"> <ul> <li>抵制不良游戏,拒绝盗版游戏。注意自我保护,谨防上当受骗。适度游戏益脑,沉迷游戏伤身。合理安排时间,享受健康生活。</li> <li>Copy Right@2012-2013 福建省网众网络科技有限公司 文网文 闽网文[2011]-0382-13号 互联网经营许可证 闽B2-20110073 版权所有:福建省网众网络科技有限公司</li> </ul> </div> </div> <!--footer end--> </body> </html> <!--热门游戏脚本--> <script src="Js/scrollPic.js" type="text/javascript"></script> <script type="text/javascript"> window.onload = function(){ scrollPic(); } function scrollPic() { var scrollPic = new ScrollPic(); scrollPic.scrollContId = "scrollPic"; //内容容器ID scrollPic.frameWidth = 510;//显示框宽度 scrollPic.pageWidth = 85; //翻页宽度 scrollPic.speed = 10; //移动速度(单位毫秒,越小越快) scrollPic.space = 10; //每次移动像素(单位px,越大越快) scrollPic.autoPlay = true; //自动播放 scrollPic.autoPlayTime = 2; //自动播放间隔时间(秒) scrollPic.initialize(); //初始化 } </script> <!--热门游戏脚本-->
0597wan
trunk/index.html
HTML
asf20
17,234
/* CSS Document */ a, abbr, acronym, address, applet, article, aside, audio, b, big, blockquote, body, canvas, caption, center, cite, code, dd, del, details, dfn, dialog, div, dl, dt, em, embed, fieldset, figcaption, figure, font, footer, form, h1, h2, h3, h4, h5, h6, header, hgroup, hr, html, i, iframe, img, ins, kbd, label, legend, li, main, mark, menu, meter, nav, object, ol, output, p, pre, progress, q, rp, rt, ruby, s, samp, section, small, span, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, time, tr, tt, u, ul, var, video, xmp { border: 0; margin: 0; padding: 0; font-size: 100%; } body { _text-align: center; font-family: "微软雅黑", "Microsoft YaHei UI"; font-size: 12px; background: #f3f3f3; height: auto; } ul li { margin: 0; padding: 0; list-style: none; } a { text-decoration: none; } .top { background: url(../images/top_bg.jpg) repeat; width: 100%; margin: 0px auto; } .guardianship { width: 956px; height: 25px; margin: 0px auto; overflow: hidden; } .guardianship li { float: right; } .nav { width: 956px; height: 83px; margin: 0px auto; overflow: hidden; } .logo { width: 210px; float: left; } .menu ul { font-weight: bold; padding-top: 53px; float: right; } .menu li { float: left; padding: 0px 10px 0px 10px; } .menu a { color: #fef7ef; } .menu a:hover { color: #F00; } .main { width: 100%; margin: 0px auto; } .content_top { width: 956px; margin: 0px auto; overflow: hidden; margin-top: 17px; } .banner { float: left; height: 274px; width: 720px; } #banner { height: 274px; } #banner div div { float: left; height: 250px; } #banner div div ul { width: 180px; margin-top: 90px; } #banner div div ul li { margin-left: 35px; height: 39px; line-height: 39px; } #banner div div ul li img { margin-top: 4px; } #banner_link { width: 540px; cursor: pointer; height: 250px; } #banner_ico { width: 720px; } #banner_ico li { float: right; } .honor { font-family: "微软雅黑", "Microsoft YaHei UI"; font-size: 12px; font-weight: bold; background: url(../images/honor.jpg) no-repeat; width: 217px; height: 274px; float: right; } .honor_title { color: #181818; padding: 8px 0px 0px 15px; } .honor_header { padding-top: 6px; color: #595959; } .honor_header span { padding: 0px 20px 0px 40px; } #honor_list { height: 274px; width: 217px; } .honor_content { line-height: 18px; border-bottom: 1px dashed #e5e5e5; padding: 3px 0px 3px 0px; color: #595959; } .honor_content span { margin-left: 15px; } .main_center { width: 956px; margin: 0px auto; overflow: hidden; margin-top: 8px; } .content_left { width: 720px; overflow: hidden; float: left; } .subnav { width: 172px; height: 339px; float: left; } .shortcut { background: url(../images/shortcut.jpg) no-repeat; width: 172px; height: 188px; font-family: "微软雅黑", "Microsoft YaHei UI"; font-size: 12px; font-weight: bold; padding-bottom: 7px; } .shortcut_title { color: #181818; padding: 5px 0px 5px 15px; } .shortcut_list li { padding: 5px 0px 5px 15px; border-bottom: 1px dashed #e5e5e5; } .shortcut_list a { color: #707070; } .shortcut_list a:hover { color: #F00; } /*.tab { background:url(../images/tab.jpg) no-repeat; width:529px; height:188px; }*/ .service { background: url(../images/service.jpg) no-repeat; width: 172px; height: 144px; font-family: "微软雅黑", "Microsoft YaHei UI"; font-size: 12px; font-weight: bold; color: #595959; } .service_title { color: #181818; padding: 5px 0px 5px 15px; } .service_list ul { padding: 10px 0px 0px 10px; } .service_list li { line-height: 22px; border-bottom: 1px dashed #e5e5e5; } .service_list a { color: #595959; } .service_list a:hover { color: #F00; } .service_list .tell { background: url(../images/tell.bmp) no-repeat left center; padding: 0px 0px 0px 25px; } .service_list .qq { background: url(../images/qq.bmp) no-repeat left center; padding: 0px 0px 0px 25px; } .service_list .qqonline { background: url(../images/qqonline.jpg) no-repeat left center; padding: 0px 0px 0px 50px; } .service_list .mail { background: url(../images/mail.bmp) no-repeat left center; padding: 0px 0px 0px 25px; } .guild { float: right; width: 529px; height: 339px; } .tab { background: url(../images/tab.jpg) no-repeat; height: 188px; width: 529px; padding-bottom: 7px; } .tab_title { height: 26px; font-family: "微软雅黑", "Microsoft YaHei UI"; font-size: 12px; font-weight: bold; padding: 2px 0px 0px 15px; } .tab_title li { padding: 0px 0px 0px 6px; float: left; width: 84px; } .tab_title li a { text-align: center; color: #181818; display: block; width: 84px; height: 21px; background: url(../images/link.jpg); padding-top: 4px; } .tab_title li a:hover { color: #09F; background: url(../images/hover.jpg); } .tab_list { font-family: "微软雅黑", "Microsoft YaHei UI"; font-size: 12px; font-weight: bold; } .tab_list ul { display: none; } .tab_list .block { display: block; } .tab_list li { padding: 4px 0px 4px 15px; border-bottom: 1px dashed #e5e5e5; } .tab_list li span { float: right; } .tab_list li a { color: #838383; } .tab_list .frist a { color: #fa7800; } .tab_list li a:hover { color: #ff0016; } .popular { background: url(../images/popular.jpg) no-repeat; font-family: "微软雅黑", "Microsoft YaHei UI"; font-size: 12px; font-weight: bold; color: #595959; width: 529px; height: 144px; } .popular_title { color: #181818; padding: 5px 0px 5px 15px; } #popular_list ul { font-family: "微软雅黑"; color: #595959; font-size: 12px; font-weight: bold; width: 510px; overflow: hidden; float: left; padding-top: 15px; } #popular_list ul a { color: #595959; } #popular_list ul a:hover { color: #F00; } #popular_list li { float: left; } #popular_list .ddz { background-image: url(../Images/ddz.bmp); background-repeat: no-repeat; width: 70px; text-align: center; padding-top: 75px; margin-left: 15px; } #popular_list .ppc { background-image: url(../Images/ppc.bmp); background-repeat: no-repeat; width: 70px; text-align: center; padding-top: 75px; margin-left: 15px; } #popular_list .mj { background-image: url(../Images/mj.bmp); background-repeat: no-repeat; width: 70px; text-align: center; padding-top: 75px; margin-left: 15px; } #popular_list .pj { background-image: url(../Images/pj.bmp); background-repeat: no-repeat; width: 70px; text-align: center; padding-top: 75px; margin-left: 15px; } #popular_list .nn { background-image: url(../Images/nn.bmp); background-repeat: no-repeat; width: 70px; text-align: center; padding-top: 75px; margin-left: 15px; } #popular_list .shby { background-image: url(../Images/shby.bmp); background-repeat: no-repeat; width: 70px; text-align: center; padding-top: 75px; margin-left: 15px; } .content_right { float: right; } .wealth { background: url(../images/wealth.jpg) no-repeat; width: 217px; height: 339px; font-family: "微软雅黑", "Microsoft YaHei UI"; font-size: 12px; font-weight: bold; } .wealth_title { color: #181818; padding: 5px 0px 5px 15px; } .wealth_header { color: #595959; padding: 5px 0px 5px 15px; } .wealth_header #nc { padding-left: 30px; } .wealth_header #jp { padding-left: 70px; } .wealth_list { } .wealth_list ul { font-family: "微软雅黑"; color: #595959; font-size: 12px; font-weight: bold; } .wealth_list li { padding: 2px 0px 2px 10px; border-bottom: 1px dashed #e5e5e5; line-height: 18px; } #wealth_digital { border: 1px solid #dbdbdb; padding-left: 5px; padding-right: 5px; } #wealth_title { margin-left: 35px; margin-right: 67px; } #wealth_content { margin-left: 10px; margin-right: 20px; } .footer { width: 100%; margin: 0px auto; } .links { width: 956px; margin: 0px auto; overflow: hidden; margin-top: 8px; height: 90px; } .copyright { width: 956px; margin: 0px auto; overflow: hidden; margin-top: 8px; height: 60px; } .copyright ul { font-family: "微软雅黑"; color: #595959; font-size: 12px; font-weight: bold; } .copyright li { text-align: center; } .download { width:956px; margin: 0px auto; overflow: hidden; margin-top:17px; } .main_left { float:left; width:236px; height:493px; background:url(../images/download_left.jpg) no-repeat;} .kjtd { } .kjtd_title { font-family: "微软雅黑", "Microsoft YaHei UI"; font-size: 14px; font-weight: bold; color:#181818; padding:15px 0px 10px 20px; } .kjtd_list { font-family: "微软雅黑", "Microsoft YaHei UI"; font-size: 14px; font-weight: bold; color:#595959; padding: 0px 0px 0px 30px; } .kjtd_list a { color:#595959; } .kjtd_list a:hover { color:#F00; } .kjtd_list li { _border-bottom: 1px dashed #e5e5e5; } .kjtd_list .account_ico { background:url(../images/account.bmp) no-repeat left center; padding: 10px 10px 10px 50px; } .kjtd_list .recharge_ico { background:url(../images/recharge.bmp) no-repeat left center; padding: 10px 10px 10px 50px; } .kjtd_list .award_ico { background:url(../images/award.bmp) no-repeat left center; padding: 10px 10px 10px 50px; } .kjtd_list .down_ico { background:url(../images/down.bmp) no-repeat left center; padding: 10px 10px 10px 50px; } .kjtd_list .help_ico { background:url(../images/help.bmp) no-repeat left center; padding: 10px 10px 10px 50px; } .zxkf_title { font-family: "微软雅黑", "Microsoft YaHei UI"; font-size: 14px; font-weight: bold; color:#181818; padding:15px 0px 10px 20px; } .zxkf_list { font-family: "微软雅黑", "Microsoft YaHei UI"; font-size: 14px; font-weight: bold; color:#595959; padding: 0px 0px 0px 30px; } .zxkf_list a { color:#595959; } .zxkf_list a:hover { color:#F00; } .zxkf_list li { padding: 0px 0px 10px 0px; _border-bottom: 1px dashed #e5e5e5; } .zxkf_list .qqonline_ico { background:url(../images/qqonline_ico.bmp) no-repeat; padding: 0px 0px 10px 70px; } .main_right { background:url(../images/download_right.jpg) no-repeat; width:720px; height:493px; float:right; } .localtion { float:left; padding-left:40px; font-family: "微软雅黑", "Microsoft YaHei UI"; font-size: 14px; font-weight: bold; } .localtion ul { padding:25px 0px 0px 10px; } .localtion li { float:left; padding: 0px 20px 0px 10px; } .localtion .arrow { background:url(../images/arrow.jpg) no-repeat left center; } .localtion a { color:#f59119; } .localtion a:hover { color:#F00; } .full, .lite { width:720px; float:left; font-family: "微软雅黑", "Microsoft YaHei UI"; font-size: 14px; font-weight: bold; padding-left:40px; padding-top:55px; } h3 { font-family: "微软雅黑", "Microsoft YaHei UI"; font-size: 18px; font-weight: bold; color:#066fbf; } h6 { font-family: "微软雅黑", "Microsoft YaHei UI"; font-size: 8px; color:#575757; } .full ul, .lite ul{ background:url(../images/download_bg.jpg) no-repeat; } .full ul li, .lite ul li { line-height:25px; } .lite { float:left; } .tips { float:left; }
0597wan
trunk/css/style.css
CSS
asf20
11,524
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Category Management</title> <link href="css/style.css" rel="stylesheet"> </head> <body> <?php require_once dirname(__FILE__) . '/dao_category.php'; $dao_category = new dao_category(); //Load table list $list_category = $dao_category->get_all(); //Load select list $list_parent_category = $dao_category->get_all(); //Load edit item if (!empty($_GET['e_id'])) { $edit_item = $dao_category->get_by_id($_GET['e_id']); } //If insert action if (!empty($_POST['btn_insert']) && empty($_GET['e_id'])) : $cat_name = $_POST['txt_cat_name']; $parent_id = $_POST['ddl_parent']; if ($dao_category->insert($cat_name, $parent_id)) : ?> <script type="text/javascript"> alert('Inserted new category successfully!'); window.location = "index.php"; </script> <?php else : ?> <script type="text/javascript"> alert('Failed, the category name existed!'); window.location = "index.php"; </script> <?php endif; endif; //If edit action if (!empty($_POST['btn_edit']) && !empty($_GET['e_id'])) : $cat_id = $_GET['e_id']; $cat_name = $_POST['txt_cat_name']; $parent_id = $_POST['ddl_parent']; $result = $dao_category->edit($cat_id, $cat_name, $parent_id); if ($result == 1) : ?> <script type="text/javascript"> alert('Edited category successfully!'); window.location = "index.php"; </script> <?php elseif ($result == 0) : ?> <script type="text/javascript"> alert('Failed, the category name existed!'); window.location = "index.php"; </script> <?php elseif ($result == -1) : ?> <script type="text/javascript"> alert('Failed, category is the same as parent!'); window.location = "index.php"; </script> <?php endif; endif; //If delete action if (!empty($_GET['d_id'])) { $d_id = $_GET['d_id']; if ($dao_category->delete($d_id)) : ?> <script type="text/javascript"> alert('Deleted category successfully!'); window.location = "index.php"; </script> <?php else: ?> <script type="text/javascript"> alert('Deleted category failed!'); window.location = "index.php"; </script> <?php endif; } ?> <form name="cat_form" method="POST"> <div class="container"> <div class="top"> <label for="txt_cat_name">Category Name:<span style="color: red;">*</span></label> <input name="txt_cat_name" type="text" value="<?php if (!empty($edit_item)) echo $edit_item['cat_name']; ?>" placeholder="Category Name" required=""> <br/> <br/> <label for="ddl_parent">Select Parent Category:</label> <select name="ddl_parent"> <?php if (empty($list_parent_category)): ?> <option value="-1">Default</option> <?php else: ?> <option value="-1">Default</option> <?php foreach ($list_parent_category as $item) : ?> <option value="<?php echo $item['cat_id']; ?>" <?php if (!empty($edit_item) && $edit_item['parent_id'] > -1 && $edit_item['parent_id'] == $item['cat_id']) echo 'selected="selected"'; ?> ><?php echo $item['cat_name']; ?></option> <?php endforeach; endif; ?> </select> <br/> <br/> <input type="submit" name="btn_insert" value="Insert"> <input type="submit" name="btn_edit" value="Edit"> </div> <div class="bottom"> <table> <tr> <th>Category ID</th> <th>Category Name</th> <th>Parent Category ID</th> <th>Parent Category Name</th> <th colspan="2">Action</th> </tr> <?php foreach ($list_category as $item): ?> <tr> <td><?php echo $item['cat_id'] ?></td> <td><?php echo $item['cat_name'] ?></td> <td><?php echo $item['parent_id'] ?></td> <td><?php echo $dao_category->get_name($item['parent_id']) ?></td> <td> <a href="index.php?e_id=<?php echo $item['cat_id'] ?>">edit</a> </td> <td> <a href="index.php?d_id=<?php echo $item['cat_id'] ?>" onclick="return confirm('Are you sure? All children of this category will aslo be deleted!');">delete</a> </td> </tr> <?php endforeach; ?> </table> </div> </div> </form> </body> </html>
05-category-management
trunk/source/index.php
PHP
gpl3
6,404
<?php require_once dirname(__FILE__) . '/config.php'; class db_connection { public function open_connect() { $config = new config(); $db_host = $config->get_db_host(); $db_user = $config->get_db_user(); $db_pass = $config->get_db_pass(); $db_name = $config->get_db_name(); $con = new mysqli($db_host, $db_user, $db_pass, $db_name) or die("Can't connect to database"); return $con; } public function close_connect($con) { mysqli_close($con); } }
05-category-management
trunk/source/db_connection.php
PHP
gpl3
551
<?php require_once dirname(__FILE__) . '/db_connection.php'; class dao_category { /** * * @return array of all category */ public function get_all() { $db = new db_connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_category"; $result = mysqli_query($con, $query) or die('Failed ' . mysqli_error()); $list = array(); while ($row = mysqli_fetch_array($result)) { array_push($list, $row); } $db->close_connect($con); return $list; } /** * * @param type $cat_id * @param type $cat_name * @return boolean */ public function check($cat_name) { $db = new db_connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_category WHERE cat_name = '" . $cat_name . "' "; $result = mysqli_query($con, $query) or die('Failed ' . mysqli_error()); if (mysqli_fetch_array($result) == TRUE) { $db->close_connect($con); return TRUE; } else { $db->close_connect($con); return FALSE; } } public function get_by_id($cat_id) { $db = new db_connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_category WHERE cat_id = " . $cat_id; $result = mysqli_query($con, $query) or die('Failed ' . mysqli_error()); $row = mysqli_fetch_array($result); $db->close_connect($con); return $row; } /** * * @param type $cat_name * @param type $parent_id * @return TRUE: insert success * @return FALSE: insert failed */ public function insert($cat_name, $parent_id) { $db = new db_connection(); $con = $db->open_connect(); if ($this->check($cat_name)) { $db->close_connect($con); return FALSE; } $query = "INSERT INTO tbl_category(cat_name, parent_id) VALUES ('" . $cat_name . "', " . $parent_id . ")"; mysqli_query($con, $query) or die('Insert Failed! : ' . mysqli_error()); $db->close_connect($con); return TRUE; } /** * * @param type $cat_id * @param type $cat_name * @param type $parent_id * @return boolean */ public function edit($cat_id, $cat_name, $parent_id) { $db = new db_connection(); $con = $db->open_connect(); $check_query = "SELECT * FROM tbl_category WHERE cat_id != " . $cat_id . " AND cat_name = '" . $cat_name . "'"; $result = mysqli_query($con, $check_query) or die('Failed query!'); $row = mysqli_fetch_array($result); if (!empty($row)) { return -1; } if($cat_id == $parent_id){ return 0; } $query = "UPDATE tbl_category SET cat_name = '" . $cat_name . "', parent_id = " . $parent_id . " WHERE cat_id = " . $cat_id; mysqli_query($con, $query) or die('Update Failed! : ' . mysqli_error()); $db->close_connect($con); return 1; } /** * * @param type $cat_id * @return array parent of Cat ID input */ public function get_children($cat_id){ $db = new db_connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_category WHERE parent_id = " . $cat_id; $result = mysqli_query($con, $query) or die('Select Failed! : ' . mysqli_error()); $list_children = array(); while ($row = mysqli_fetch_array($result)) { array_push($list_children, $row); } $db->close_connect($con); return $list_children; } public function delete_basic($cat_id) { $db = new db_connection(); $con = $db->open_connect(); $query = "DELETE FROM tbl_category WHERE cat_id = " . $cat_id; mysqli_query($con, $query) or die('Update Failed! : ' . mysqli_error()); $db->close_connect($con); } public function delete($cat_id) { $db = new db_connection(); $con = $db->open_connect(); $children = $this->get_children($cat_id); foreach ($children as $child): $list_child = $this->get_children($child['cat_id']); if (empty($list_child)) : $this->delete_basic($child['cat_id']); else : $this->delete($child['cat_id']); endif; endforeach; $this->delete_basic($cat_id); $db->close_connect($con); return TRUE; } public function get_name($cat_id) { $db = new db_connection(); $con = $db->open_connect(); if ($cat_id == -1) { return "NULL"; } $query = "SELECT * FROM tbl_category WHERE cat_id = " . $cat_id; $result = mysqli_query($con, $query) or die('Failed ' . mysqli_error()); $row = mysqli_fetch_array($result); $db->close_connect($con); return $row['cat_name']; } }
05-category-management
trunk/source/dao_category.php
PHP
gpl3
5,221
<?php class config { private $db_name = '1191_category_management'; private $db_host = 'localhost'; private $db_user = 'root'; private $db_pass = ''; public function get_db_name() { return $this->db_name; } public function get_db_host() { return $this->db_host; } public function get_db_user() { return $this->db_user; } public function get_db_pass() { return $this->db_pass; } }
05-category-management
trunk/source/config.php
PHP
gpl3
493
.container { width: 960px; margin-left: auto; margin-right: auto; } .top { margin-top: 100px; } .bottom { margin-top: 50px; } table, tr, th, td { border: 1px solid #000; padding: 10px; border-collapse: collapse; } th { color: red; }
05-category-management
trunk/source/css/style.css
CSS
gpl3
294
package b_Money; public class Currency { private String name; private Double rate; /** * New Currency * The rate argument of each currency indicates that Currency's "universal" exchange rate. * Imagine that we define the rate of each currency in relation to some universal currency. * This means that the rate of each currency defines its value compared to this universal currency. * * @param name The name of this Currency * @param rate The exchange rate of this Currency */ Currency (String name, Double rate) { this.name = name; this.rate = rate; } /** Convert an amount of this Currency to its value in the general "universal currency" * (As mentioned in the documentation of the Currency constructor) * * @param amount An amount of cash of this currency. * @return The value of amount in the "universal currency" */ public Integer universalValue(Integer amount) { } /** Get the name of this Currency. * @return name of Currency */ public String getName() { } /** Get the rate of this Currency. * * @return rate of this Currency */ public Double getRate() { } /** Set the rate of this currency. * * @param rate New rate for this Currency */ public void setRate(Double rate) { } /** Convert an amount from another Currency to an amount in this Currency * * @param amount Amount of the other Currency * @param othercurrency The other Currency */ public Integer valueInThisCurrency(Integer amount, Currency othercurrency) { } }
0703selab13
src/b_Money/Currency.java
Java
gpl3
1,532
package b_Money; public class AccountDoesNotExistException extends Exception { static final long serialVersionUID = 1L; }
0703selab13
src/b_Money/AccountDoesNotExistException.java
Java
gpl3
125
package b_Money; import java.util.Hashtable; public class Bank { private Hashtable<String, Account> accountlist = new Hashtable<String, Account>(); private String name; private Currency currency; /** * New Bank * @param name Name of this bank * @param currency Base currency of this bank (If this is a Swedish bank, this might be a currency class representing SEK) */ Bank(String name, Currency currency) { this.name = name; this.currency = currency; } /** * Get the name of this bank * @return Name of this bank */ public String getName() { return name; } /** * Get the Currency of this bank * @return The Currency of this bank */ public Currency getCurrency() { return currency; } /** * Open an account at this bank. * @param accountid The ID of the account * @throws AccountExistsException If the account already exists */ public void openAccount(String accountid) throws AccountExistsException { if (accountlist.containsKey(accountid)) { throw new AccountExistsException(); } else { accountlist.get(accountid); } } /** * Deposit money to an account * @param accountid Account to deposit to * @param money Money to deposit. * @throws AccountDoesNotExistException If the account does not exist */ public void deposit(String accountid, Money money) throws AccountDoesNotExistException { if (accountlist.containsKey(accountid)) { throw new AccountDoesNotExistException(); } else { Account account = accountlist.get(accountid); account.deposit(money); } } /** * Withdraw money from an account * @param accountid Account to withdraw from * @param money Money to withdraw * @throws AccountDoesNotExistException If the account does not exist */ public void withdraw(String accountid, Money money) throws AccountDoesNotExistException { if (!accountlist.containsKey(accountid)) { throw new AccountDoesNotExistException(); } else { Account account = accountlist.get(accountid); account.deposit(money); } } /** * Get the balance of an account * @param accountid Account to get balance from * @return Balance of the account * @throws AccountDoesNotExistException If the account does not exist */ public Integer getBalance(String accountid) throws AccountDoesNotExistException { if (!accountlist.containsKey(accountid)) { throw new AccountDoesNotExistException(); } else { return accountlist.get(accountid).getBalance().getAmount(); } } /** * Transfer money between two accounts * @param fromaccount Id of account to deduct from in this Bank * @param tobank Bank where receiving account resides * @param toaccount Id of receiving account * @param amount Amount of Money to transfer * @throws AccountDoesNotExistException If one of the accounts do not exist */ public void transfer(String fromaccount, Bank tobank, String toaccount, Money amount) throws AccountDoesNotExistException { if (!accountlist.containsKey(fromaccount) || !tobank.accountlist.containsKey(toaccount)) { throw new AccountDoesNotExistException(); } else { accountlist.get(fromaccount).withdraw(amount); tobank.accountlist.get(toaccount).deposit(amount); } } /** * Transfer money between two accounts on the same bank * @param fromaccount Id of account to deduct from * @param toaccount Id of receiving account * @param amount Amount of Money to transfer * @throws AccountDoesNotExistException If one of the accounts do not exist */ public void transfer(String fromaccount, String toaccount, Money amount) throws AccountDoesNotExistException { transfer(fromaccount, this, fromaccount, amount); } /** * Add a timed payment * @param accountid Id of account to deduct from in this Bank * @param payid Id of timed payment * @param interval Number of ticks between payments * @param next Number of ticks till first payment * @param amount Amount of Money to transfer each payment * @param tobank Bank where receiving account resides * @param toaccount Id of receiving account */ public void addTimedPayment(String accountid, String payid, Integer interval, Integer next, Money amount, Bank tobank, String toaccount) { Account account = accountlist.get(accountid); account.addTimedPayment(payid, interval, next, amount, tobank, toaccount); } /** * Remove a timed payment * @param accountid Id of account to remove timed payment from * @param id Id of timed payment */ public void removeTimedPayment(String accountid, String id) { Account account = accountlist.get(accountid); account.removeTimedPayment(id); } /** * A time unit passes in the system */ public void tick() throws AccountDoesNotExistException { for (Account account : accountlist.values()) { account.tick(); } } }
0703selab13
src/b_Money/Bank.java
Java
gpl3
4,814
package b_Money; import java.util.Hashtable; public class Account { private Money content; private Hashtable<String, TimedPayment> timedpayments = new Hashtable<String, TimedPayment>(); Account(String name, Currency currency) { this.content = new Money(0, currency); } /** * Add a timed payment * @param id Id of timed payment * @param interval Number of ticks between payments * @param next Number of ticks till first payment * @param amount Amount of Money to transfer each payment * @param tobank Bank where receiving account resides * @param toaccount Id of receiving account */ public void addTimedPayment(String id, Integer interval, Integer next, Money amount, Bank tobank, String toaccount) { TimedPayment tp = new TimedPayment(interval, next, amount, this, tobank, toaccount); timedpayments.put(id, tp); } /** * Remove a timed payment * @param id Id of timed payment to remove */ public void removeTimedPayment(String id) { timedpayments.remove(id); } /** * Check if a timed payment exists * @param id Id of timed payment to check for */ public boolean timedPaymentExists(String id) { return timedpayments.containsKey(id); } /** * A time unit passes in the system */ public void tick() { for (TimedPayment tp : timedpayments.values()) { tp.tick(); tp.tick(); } } /** * Deposit money to the account * @param money Money to deposit. */ public void deposit(Money money) { content = content.add(money); } /** * Withdraw money from the account * @param money Money to withdraw. */ public void withdraw(Money money) { content = content.sub(money); } /** * Get balance of account * @return Amount of Money currently on account */ public Money getBalance() { return content; } /* Everything below belongs to the private inner class, TimedPayment */ private class TimedPayment { private int interval, next; private Account fromaccount; private Money amount; private Bank tobank; private String toaccount; TimedPayment(Integer interval, Integer next, Money amount, Account fromaccount, Bank tobank, String toaccount) { this.interval = interval; this.next = next; this.amount = amount; this.fromaccount = fromaccount; this.tobank = tobank; this.toaccount = toaccount; } /* Return value indicates whether or not a transfer was initiated */ public Boolean tick() { if (next == 0) { next = interval; fromaccount.withdraw(amount); try { tobank.deposit(toaccount, amount); } catch (AccountDoesNotExistException e) { /* Revert transfer. * In reality, this should probably cause a notification somewhere. */ fromaccount.deposit(amount); } return true; } else { next--; return false; } } } }
0703selab13
src/b_Money/Account.java
Java
gpl3
2,811
package b_Money; public class AccountExistsException extends Exception { static final long serialVersionUID = 1L; }
0703selab13
src/b_Money/AccountExistsException.java
Java
gpl3
119
package b_Money; import java.util.*; public class Money implements Comparable { private int amount; private Currency currency; /** * New Money * @param amount The amount of money * @param currency The currency of the money */ Money (Integer amount, Currency currency) { this.amount = amount; this.currency = currency; } /** * Return the amount of money. * @return Amount of money in Double type. */ public Integer getAmount() { return this.amount; } /** * Returns the currency of this Money. * @return Currency object representing the currency of this Money */ public Currency getCurrency() { return this.currency; } /** * Returns the amount of the money in the string form "(amount) (currencyname)", e.g. "10.5 SEK". * Recall that we represent decimal numbers with integers. This means that the "10.5 SEK" mentioned * above is actually represented as the integer 1050 * @return String representing the amount of Money. */ public String toString() { } /** * Gets the universal value of the Money, according the rate of its Currency. * @return The value of the Money in the "universal currency". */ public Integer universalValue() { } /** * Check to see if the value of this money is equal to the value of another Money of some other Currency. * @param other The other Money that is being compared to this Money. * @return A Boolean indicating if the two monies are equal. */ public Boolean equals(Money other) { } /** * Adds a Money to this Money, regardless of the Currency of the other Money. * @param other The Money that is being added to this Money. * @return A new Money with the same Currency as this Money, representing the added value of the two. * (Remember to convert the other Money before adding the amounts) */ public Money add(Money other) { } /** * Subtracts a Money from this Money, regardless of the Currency of the other Money. * @param other The money that is being subtracted from this Money. * @return A new Money with the same Currency as this Money, representing the subtracted value. * (Again, remember converting the value of the other Money to this Currency) */ public Money sub(Money other) { } /** * Check to see if the amount of this Money is zero or not * @return True if the amount of this Money is equal to 0.0, False otherwise */ public Boolean isZero() { } /** * Negate the amount of money, i.e. if the amount is 10.0 SEK the negation returns -10.0 SEK * @return A new instance of the money class initialized with the new negated money amount. */ public Money negate() { } /** * Compare two Monies. * compareTo is required because the class implements the Comparable interface. * (Remember the universalValue method, and that Integers already implement Comparable). * Also, since compareTo must take an Object, you will have to explicitly downcast it to a Money. * @return 0 if the values of the monies are equal. * A negative integer if this Money is less valuable than the other Money. * A positive integer if this Money is more valuiable than the other Money. */ public int compareTo(Object other) { } }
0703selab13
src/b_Money/Money.java
Java
gpl3
3,223
using System; using System.Collections.Generic; using System.Text; using DAL; using Entities; namespace BUS { public class tbDoanhNghiepBus { public static void Insert_DoanhNghiep(tbDoanhNghiep doanhnghiep) { tbDoanhNghiepDAL doanhnghiepDAL = new tbDoanhNghiepDAL(); doanhnghiepDAL.Insert(doanhnghiep); } public static void Update_DoanhNghiep(tbDoanhNghiep doanhnghiep) { tbDoanhNghiepDAL doanhnghiepDAL = new tbDoanhNghiepDAL(); doanhnghiepDAL.Update(doanhnghiep); } public static void Delete_DoanhNghiep(int Id) { tbDoanhNghiepDAL doanhnghiepDAL = new tbDoanhNghiepDAL(); doanhnghiepDAL.Delete(Id); } public static tbDoanhNghiep.tbDoanhNghiepCollection Get(string Where, int pageindex, int pagesize, string orderby, string orderdirection, out int total) { tbDoanhNghiepDAL doanhnghiepDAL = new tbDoanhNghiepDAL(); return (doanhnghiepDAL.Get(Where, pageindex, pagesize, orderby, orderdirection, out total)); } public static tbDoanhNghiep.tbDoanhNghiepCollection GetAll() { int total = 0; tbDoanhNghiepDAL doanhnghiepDAL = new tbDoanhNghiepDAL(); return doanhnghiepDAL.Get("Where 1=1", 0, 0, tbDoanhNghiep.tbDoanhNghiepColumns.IDDoanhNghiep.ToString(), "ASC", out total); } public static tbDoanhNghiep GetByID(int iD) { int total = 0; tbDoanhNghiepDAL doanhnghiepDAL = new tbDoanhNghiepDAL(); tbDoanhNghiep.tbDoanhNghiepCollection doanhnghiepcollection = doanhnghiepDAL.Get("where " + tbDoanhNghiep.tbDoanhNghiepColumns.IDDoanhNghiep.ToString() + "=" + iD.ToString(), 0, 0, tbDoanhNghiep.tbDoanhNghiepColumns.IDDoanhNghiep.ToString(), "ASC", out total); if (doanhnghiepcollection.Count > 0) return doanhnghiepcollection[0]; return null; } } }
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/BUS/tbDoanhNghiepBUS.cs
C#
gpl3
2,063
using System; using System.Data; using System.Configuration; using System.Web; using System.Text; using DAL; using Entities; /// <summary> /// Summary description for tbChiTietDHBUS /// </summary> public class tbChiTietDHBUS { public static void Insert_ChiTietDH(tbChiTietDH chitietdh) { tbCTDonHangDAL chitietdhDAL = new tbCTDonHangDAL(); chitietdhDAL.Insert(chitietdh); } public static void Update_ChiTietDH(tbChiTietDH chitietdh) { tbCTDonHangDAL chitietdhDAL = new tbCTDonHangDAL(); chitietdhDAL.Update(chitietdh); } public static void Delete_ChiTietDH(int Id) { tbCTDonHangDAL chitietdhDAL = new tbCTDonHangDAL(); chitietdhDAL.Delete(Id); } public static tbChiTietDH.tbChiTietDHCollection Get(string Where, int pageindex, int pagesize, string orderby, string orderdirection, out int total) { tbCTDonHangDAL chitietdhDAL = new tbCTDonHangDAL(); return (chitietdhDAL.Get(Where, pageindex, pagesize, orderby, orderdirection, out total)); } public static tbChiTietDH.tbChiTietDHCollection GetAll() { int total = 0; tbCTDonHangDAL chitietdhDAL = new tbCTDonHangDAL(); return chitietdhDAL.Get("Where 1=1", 0, 0, tbChiTietDH.tbChiTietDHColumns.IDCTDH.ToString(), "ASC", out total); } public static tbChiTietDH GetByID(int iD) { int total = 0; tbCTDonHangDAL chitietdhDAL = new tbCTDonHangDAL(); tbChiTietDH.tbChiTietDHCollection chitietdhcollection = chitietdhDAL.Get("where " + tbChiTietDH.tbChiTietDHColumns.IDCTDH.ToString() + "=" + iD.ToString(), 0, 0, tbChiTietDH.tbChiTietDHColumns.IDCTDH.ToString(), "ASC", out total); if (chitietdhcollection.Count > 0) return chitietdhcollection[0]; return null; } }
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/BUS/tbChiTietDHBUS.cs
C#
gpl3
1,869
using System; using System.Collections.Generic; using System.Text; using DAL; using Entities; namespace BUS { public class tbHangSanXuatBUS { public static void Insert_HangSanXuat(tbHangSanXuat hangsanxuat) { tbHangSanXuatDAL hangsanxuatDAL = new tbHangSanXuatDAL(); hangsanxuatDAL.Insert(hangsanxuat); } public static void Update_HangSanXuat(tbHangSanXuat hangsanxuat) { tbHangSanXuatDAL hangsanxuatDAL = new tbHangSanXuatDAL(); hangsanxuatDAL.Update(hangsanxuat); } public static void Delete_HangSanXuat(int iD) { tbHangSanXuatDAL hangsanxuatDAL = new tbHangSanXuatDAL(); hangsanxuatDAL.Delete(iD); } public static Entities.tbHangSanXuat.tbHangSanXuatCollection Get(string where, int pageindex, int pagesize, string orderby, string orderdirection, out int total) { tbHangSanXuatDAL hangsanxuatDAL = new tbHangSanXuatDAL(); return hangsanxuatDAL.Get(where, pageindex, pagesize, orderby, orderdirection, out total); } public static Entities.tbHangSanXuat.tbHangSanXuatCollection GetAll() { int total = 0; tbHangSanXuatDAL hangsanxuatDAL = new tbHangSanXuatDAL(); return hangsanxuatDAL.Get("where 1=1", 0, 0, Entities.tbHangSanXuat.tbHangSanXuatColumns.IDHangSanXuat.ToString(), "ASC", out total); } public static tbHangSanXuat GetByID(int iD) { int total = 0; tbHangSanXuatDAL hangsanxuatDAL = new tbHangSanXuatDAL(); Entities.tbHangSanXuat.tbHangSanXuatCollection hangsanxuatCollection = hangsanxuatDAL.Get("where " + Entities.tbHangSanXuat.tbHangSanXuatColumns.IDHangSanXuat.ToString() + "=" + iD.ToString(), 0, 0, Entities.tbHangSanXuat.tbHangSanXuatColumns.IDHangSanXuat.ToString(), "ASC", out total); if (hangsanxuatCollection.Count > 0) return hangsanxuatCollection[0]; return null; } } }
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/BUS/tbHangSanXuatBUS.cs
C#
gpl3
2,107
using System; using System.Collections.Generic; using System.Text; using DAL; using Entities; namespace BUS { public class tbDonHangBUS { public static void Insert_DonHang(tbDonHang donhang) { tbDonHangDAL donhangDAL = new tbDonHangDAL(); donhangDAL.Insert(donhang); } public static void Update_DonHang(tbDonHang donhang) { tbDonHangDAL donhangDAL = new tbDonHangDAL(); donhangDAL.Update(donhang); } public static void Delete_DonHang(int iD) { tbDonHangDAL donhangDAL = new tbDonHangDAL(); donhangDAL.Delete(iD); } public static Entities.tbDonHang.tbDonHangCollection Get(string where, int pageindex, int pagesize, string orderby, string orderdirection, out int total) { tbDonHangDAL donhangDAL = new tbDonHangDAL(); return donhangDAL.Get(where, pageindex, pagesize, orderby, orderdirection, out total); } public static Entities.tbDonHang.tbDonHangCollection GetAll() { int total = 0; tbDonHangDAL donhangDAL = new tbDonHangDAL(); return donhangDAL.Get("where 1=1", 0, 0, tbDonHang.tbDonHangColumns.IDDonHang.ToString(), "ASC", out total); } public static tbDonHang GetByID(int iD) { int total = 0; tbDonHangDAL donhangDAL = new tbDonHangDAL(); tbDonHang.tbDonHangCollection donhangCollection = donhangDAL.Get("where " + tbDonHang.tbDonHangColumns.IDDonHang.ToString() + "=" + iD.ToString(), 0, 0, tbDonHang.tbDonHangColumns.IDDonHang.ToString(), "ASC", out total); if (donhangCollection.Count > 0) return donhangCollection[0]; return null; } } }
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/BUS/tbDonHangBUS.cs
C#
gpl3
1,859
using System; using System.Collections.Generic; using System.Text; using DAL; using Entities; namespace BUS { public class tbTTGiaoDichBus { public static void Insert_ChuDe(tbTTGiaoDich ttgiaodich) { tbTTGiaoDichDAL ttgiaodichDAL = new tbTTGiaoDichDAL(); ttgiaodichDAL.Insert(ttgiaodich); } public static void Update_ChuDe(tbTTGiaoDich ttgiaodich) { tbTTGiaoDichDAL ttgiaodichDAL = new tbTTGiaoDichDAL(); ttgiaodichDAL.Update(ttgiaodich); } public static void Delete_ChuDe(int Id) { tbTTGiaoDichDAL ttgiaodichDAL = new tbTTGiaoDichDAL(); ttgiaodichDAL.Delete(Id); } public static tbTTGiaoDich.tbTTGiaoDichCollection Get(string Where, int pageindex, int pagesize, string orderby, string orderdirection, out int total) { tbTTGiaoDichDAL ttgiaodichDAL = new tbTTGiaoDichDAL(); return (ttgiaodichDAL.Get(Where, pageindex, pagesize, orderby, orderdirection, out total)); } public static tbTTGiaoDich.tbTTGiaoDichCollection GetAll() { int total = 0; tbTTGiaoDichDAL ttgiaodichDAL = new tbTTGiaoDichDAL(); return ttgiaodichDAL.Get("Where 1=1", 0, 0, tbTTGiaoDich.tbTTGiaoDichColumns.IDTTGiaoDich.ToString(), "ASC", out total); } public static tbTTGiaoDich GetByID(int iD) { int total = 0; tbTTGiaoDichDAL ttgiaodichDAL = new tbTTGiaoDichDAL(); tbTTGiaoDich.tbTTGiaoDichCollection ttgiaodichcollection = ttgiaodichDAL.Get("where " + tbTTGiaoDich.tbTTGiaoDichColumns.IDTTGiaoDich.ToString() + "=" + iD.ToString(), 0, 0, tbTTGiaoDich.tbTTGiaoDichColumns.IDTTGiaoDich.ToString(), "ASC", out total); if (ttgiaodichcollection.Count > 0) return ttgiaodichcollection[0]; return null; } } }
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/BUS/tbTTGiaoDichBUS.cs
C#
gpl3
1,995
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BUS")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("CNTP")] [assembly: AssemblyProduct("BUS")] [assembly: AssemblyCopyright("Copyright © CNTP 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("78463d93-7ce7-402d-aa2b-54623a96983d")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/BUS/Properties/AssemblyInfo.cs
C#
gpl3
1,385
using System; using System.Collections.Generic; using System.Text; using Entities; using DAL; namespace BUS { public class tbTrangThaiSPBUS { public static void Insert_TrangThaiSP(tbTrangThaiSP trangthaisp) { tbTrangThaiSPDAL trangthaispDAL = new tbTrangThaiSPDAL(); trangthaispDAL.Insert(trangthaisp); } public static void Update_TrangThaiSP(tbTrangThaiSP trangthaisp) { tbTrangThaiSPDAL trangthaispDAL = new tbTrangThaiSPDAL(); trangthaispDAL.Update(trangthaisp); } public static void Delete_TrangThaiSP(int iD) { tbTrangThaiSPDAL trangthaispDAL = new tbTrangThaiSPDAL(); trangthaispDAL.Delete(iD); } public static tbTrangThaiSP.tbTrangThaiSPCollection Get(string where, int pageindex, int pagesize, string orderby, string orderdirection, out int total) { tbTrangThaiSPDAL trangthaispDAL = new tbTrangThaiSPDAL(); return trangthaispDAL.Get(where, pageindex, pagesize, orderby, orderdirection, out total); } public static tbTrangThaiSP.tbTrangThaiSPCollection GetAll() { int total = 0; tbTrangThaiSPDAL trangthaispDAL = new tbTrangThaiSPDAL(); return trangthaispDAL.Get("where 1=1", 0, 0, Entities.tbTrangThaiSP.tbTrangThaiSPColumns.IDTrangThaiSP.ToString(), "ASC", out total); } public static tbTrangThaiSP GetByID(int iD) { int total = 0; tbTrangThaiSPDAL trangthaispDAL = new tbTrangThaiSPDAL(); tbTrangThaiSP.tbTrangThaiSPCollection trangthaispCollection = trangthaispDAL.Get("where " + tbTrangThaiSP.tbTrangThaiSPColumns.IDTrangThaiSP.ToString() + "=" + iD.ToString(), 0, 0, tbTrangThaiSP.tbTrangThaiSPColumns.IDTrangThaiSP.ToString(), "ASC", out total); if (trangthaispCollection.Count > 0) return trangthaispCollection[0]; return null; } } }
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/BUS/tbTrangThaiSPBUS.cs
C#
gpl3
2,062
using System; using System.Collections.Generic; using System.Text; using Entities; using DAL; namespace BUS { public class tbKhachHangBUS { public static void Insert(tbKhachHang khachhang) { tbKhachHangDAL khachhangDAL = new tbKhachHangDAL(); khachhangDAL.Insert(khachhang); } public static void Update(tbKhachHang khachhang) { tbKhachHangDAL khachhangDAL = new tbKhachHangDAL(); khachhangDAL.Update(khachhang); } public static void Delete(int iD) { tbKhachHangDAL khachhangDAL = new tbKhachHangDAL(); khachhangDAL.Delete(iD); } public static tbKhachHang.tbKhachHangCollection Get(string where, int pageindex, int pagesize, string orderby, string orderdirection, out int total) { tbKhachHangDAL khachhangDAL = new tbKhachHangDAL(); return khachhangDAL.Get(where, pageindex, pagesize, orderby, orderdirection, out total); } public static tbKhachHang.tbKhachHangCollection GetAll() { int total = 0; tbKhachHangDAL khachhangDAL = new tbKhachHangDAL(); return khachhangDAL.Get("where 1=1", 0, 0, tbKhachHang.tbKhachHangColumns.IDKhachHang.ToString(), "ASC", out total); } public static tbKhachHang GetByID(int iD) { int total = 0; tbKhachHangDAL khachhangDAL = new tbKhachHangDAL(); tbKhachHang.tbKhachHangCollection khachhangCollection = khachhangDAL.Get("where " + tbKhachHang.tbKhachHangColumns.IDKhachHang.ToString() + "=" + iD.ToString(), 0, 0, tbKhachHang.tbKhachHangColumns.IDKhachHang.ToString(), "ASC", out total); if (khachhangCollection.Count > 0) return khachhangCollection[0]; return null; } } }
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/BUS/tbKhachHangBUS.cs
C#
gpl3
1,917
using System; using System.Collections.Generic; using System.Text; using System.Configuration; using Entities; using System.Data.SqlClient; using System.Data; using DAL; namespace BUS { public class tbLoaiSPBUS { public static void Insert_LoaiSP(tbLoaiSP loaisp) { tbLoaiSPDAL loaispDAL = new tbLoaiSPDAL(); loaispDAL.Insert(loaisp); } public static void Update_LoaiSP(tbLoaiSP loaisp) { tbLoaiSPDAL loaispDAL = new tbLoaiSPDAL(); loaispDAL.Update(loaisp); } public static void Delete_LoaiSP(int iD) { tbLoaiSPDAL loaispDAL = new tbLoaiSPDAL(); loaispDAL.Delete(iD); } public static tbLoaiSP.tbLoaiSPCollection Get(string where, int pageindex, int pagesize, string orderby, string orderdirection, out int total) { tbLoaiSPDAL loaispDAL = new tbLoaiSPDAL(); return loaispDAL.Get(where, pageindex, pagesize, orderby, orderdirection, out total); } public static Entities.tbLoaiSP.tbLoaiSPCollection GetAll() { int total = 0; tbLoaiSPDAL loaispDAL = new tbLoaiSPDAL(); return loaispDAL.Get("where 1=1", 0, 0, Entities.tbLoaiSP.tbLoaiSPColumns.IDLoaiSP.ToString(), "ASC", out total); } public static tbLoaiSP GetByID(int iD) { int total = 0; tbLoaiSPDAL loaispDAL = new tbLoaiSPDAL(); tbLoaiSP.tbLoaiSPCollection loaispCollection = loaispDAL.Get("where " + Entities.tbLoaiSP.tbLoaiSPColumns.IDLoaiSP.ToString() + "=" + iD.ToString(), 0, 0, Entities.tbLoaiSP.tbLoaiSPColumns.IDLoaiSP.ToString(), "ASC", out total); if (loaispCollection.Count > 0) return loaispCollection[0]; return null; } } }
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/BUS/tbLoaiSPBUS.cs
C#
gpl3
1,902
using System; using System.Collections.Generic; using System.Text; namespace BUS { public class Class1 { } }
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/BUS/Class1.cs
C#
gpl3
132
using System; using System.Collections.Generic; using System.Text; using DAL; using Entities; namespace BUS { public class tbHTThanhToanBus { public static void Insert_HTThanhtoan(tbHTThanhToan htthanhtoan) { tbHTThanhToanDAL htthanhtoanDAL = new tbHTThanhToanDAL(); htthanhtoanDAL.Insert(htthanhtoan); } public static void Update_HTThanhtoan(tbHTThanhToan htthanhtoan) { tbHTThanhToanDAL htthanhtoanDAL = new tbHTThanhToanDAL(); htthanhtoanDAL.Update(htthanhtoan); } public static void Delete_HTThanhtoan(int Id) { tbHTThanhToanDAL htthanhtoanDAL = new tbHTThanhToanDAL(); htthanhtoanDAL.Delete(Id); } public static tbHTThanhToan.tbHTThanhToanCollection Get(string Where, int pageindex, int pagesize, string orderby, string orderdirection, out int total) { tbHTThanhToanDAL htthanhtoanDAL = new tbHTThanhToanDAL(); return (htthanhtoanDAL.Get(Where, pageindex, pagesize, orderby, orderdirection, out total)); } public static tbHTThanhToan.tbHTThanhToanCollection GetAll() { int total = 0; tbHTThanhToanDAL htthanhtoanDAL = new tbHTThanhToanDAL(); return htthanhtoanDAL.Get("Where 1=1", 0, 0, tbHTThanhToan.tbHTThanhToanColumns.IDHinhThuc.ToString(), "ASC", out total); } public static tbHTThanhToan GetByID(int iD) { int total = 0; tbHTThanhToanDAL htthanhtoanDAL = new tbHTThanhToanDAL(); tbHTThanhToan.tbHTThanhToanCollection htthanhtoancollection = htthanhtoanDAL.Get("where " + tbHTThanhToan.tbHTThanhToanColumns.IDHinhThuc.ToString() + "=" + iD.ToString(), 0, 0, tbHTThanhToan.tbHTThanhToanColumns.IDHinhThuc.ToString(), "ASC", out total); if (htthanhtoancollection.Count > 0) return htthanhtoancollection[0]; return null; } } }
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/BUS/tbHTThanhToanBUS.cs
C#
gpl3
2,054
using System; using System.Collections.Generic; using System.Text; using DAL; using Entities; namespace BUS { public class tbHinhAnhBus { public static void Insert_HinhAnh(tbHinhAnh hinhanh) { tbHinhAnhDAL hinhanhDAL = new tbHinhAnhDAL(); hinhanhDAL.Insert(hinhanh); } public static void Update_HinhAnh(tbHinhAnh hinhanh) { tbHinhAnhDAL hinhanhDAL = new tbHinhAnhDAL(); hinhanhDAL.Update(hinhanh); } public static void Delete_HinhAnh(int Id) { tbHinhAnhDAL hinhanhDAL = new tbHinhAnhDAL(); hinhanhDAL.Delete(Id); } public static tbHinhAnh.tbHinhAnhCollection Get(string Where, int pageindex, int pagesize, string orderby, string orderdirection, out int total) { tbHinhAnhDAL hinhanhDAL = new tbHinhAnhDAL(); return (hinhanhDAL.Get(Where, pageindex, pagesize, orderby, orderdirection, out total)); } public static tbHinhAnh.tbHinhAnhCollection GetAll() { int total = 0; tbHinhAnhDAL hinhanhDAL = new tbHinhAnhDAL(); return hinhanhDAL.Get("Where 1=1", 0, 0, tbHinhAnh.tbHinhAnhColumns.IDHinhAnh.ToString(), "ASC", out total); } public static tbHinhAnh GetByID(int iD) { int total = 0; tbHinhAnhDAL hinhanhDAL = new tbHinhAnhDAL(); tbHinhAnh.tbHinhAnhCollection hinhanhcollection = hinhanhDAL.Get("where " + tbHinhAnh.tbHinhAnhColumns.IDHinhAnh.ToString() + "=" + iD.ToString(), 0, 0, tbHinhAnh.tbHinhAnhColumns.IDHinhAnh.ToString(), "ASC", out total); if (hinhanhcollection.Count > 0) return hinhanhcollection[0]; return null; } } }
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/BUS/tbHinhAnhBUS.cs
C#
gpl3
1,851
using System; using System.Collections.Generic; using System.Text; using Entities; using DAL; using System.Data.SqlClient; namespace BUS { public class tbTTDonHangBus { public static void Insert_ChuDe(tbTTDonHang ttdonhang) { tbTTDonHangDAL ttdonhangDAL = new tbTTDonHangDAL(); ttdonhangDAL.Insert(ttdonhang); } public static void Update_ChuDe(tbTTDonHang ttdonhang) { tbTTDonHangDAL ttdonhangDAL = new tbTTDonHangDAL(); ttdonhangDAL.Update(ttdonhang); } public static void Delete_ChuDe(int Id) { tbTTDonHangDAL ttdonhangDAL = new tbTTDonHangDAL(); ttdonhangDAL.Delete(Id); } public static tbTTDonHang.tbTTDonHangCollection Get(string Where, int pageindex, int pagesize, string orderby, string orderdirection, out int total) { tbTTDonHangDAL ttdonhangDAL = new tbTTDonHangDAL(); return (ttdonhangDAL.Get(Where, pageindex, pagesize, orderby, orderdirection, out total)); } public static tbTTDonHang.tbTTDonHangCollection GetAll() { int total = 0; tbTTDonHangDAL ttdonhangDAL = new tbTTDonHangDAL(); return ttdonhangDAL.Get("Where 1=1", 0, 0, tbTTDonHang.tbTTDonHangColumns.IDTTDonHang.ToString(), "ASC", out total); } public static tbTTDonHang GetByID(int iD) { int total = 0; tbTTDonHangDAL ttdonhangDAL = new tbTTDonHangDAL(); tbTTDonHang.tbTTDonHangCollection ttdonhangcollection = ttdonhangDAL.Get("where " + tbTTDonHang.tbTTDonHangColumns.IDTTDonHang.ToString() + "=" + iD.ToString(), 0, 0, tbTTDonHang.tbTTDonHangColumns.IDTTDonHang.ToString(), "ASC", out total); if (ttdonhangcollection.Count > 0) return ttdonhangcollection[0]; return null; } } }
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/BUS/tbTTDonHangBUS.cs
C#
gpl3
1,975
using System; using System.Collections.Generic; using System.Text; using DAL; using Entities; namespace BUS { public class tbSanPhamBus { public static void Insert_SanPham(tbSanPham sanpham) { tbsanphamDAL sanphamDAL = new tbsanphamDAL(); sanphamDAL.Insert(sanpham); } public static void Update_SanPham(tbSanPham sanpham) { tbsanphamDAL sanphamDAL = new tbsanphamDAL(); sanphamDAL.Update(sanpham); } public static void Delete_SanPham(int Id) { tbsanphamDAL sanphamDAL = new tbsanphamDAL(); sanphamDAL.Delete(Id); } public static tbSanPham.tbSanPhamCollection Get(string Where, int pageindex, int pagesize, string orderby, string orderdirection, out int total) { tbsanphamDAL sanphamDAL = new tbsanphamDAL(); return (sanphamDAL.Get(Where, pageindex, pagesize, orderby, orderdirection, out total)); } public static tbSanPham.tbSanPhamCollection GetAll() { int total = 0; tbsanphamDAL sanphamDAL = new tbsanphamDAL(); return sanphamDAL.Get("Where 1=1", 0, 0, tbSanPham.tbSanPhamColumns.IDSanPham.ToString(), "ASC", out total); } public static tbSanPham GetByID(int iD) { int total = 0; tbsanphamDAL sanphamDAL = new tbsanphamDAL(); tbSanPham.tbSanPhamCollection sanphamcollection = sanphamDAL.Get("where " + tbSanPham.tbSanPhamColumns.IDSanPham.ToString() + "=" + iD.ToString(), 0, 0, tbSanPham.tbSanPhamColumns.IDSanPham.ToString(), "ASC", out total); if (sanphamcollection.Count > 0) return sanphamcollection[0]; return null; } } }
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/BUS/tbSanPhamBUS.cs
C#
gpl3
1,851
using System; using System.Collections.Generic; using System.Text; using DAL; using Entities; namespace BUS { public class tbMaSoSPBUS { public static void Insert_MaSoSP(tbMaSoSP masosp) { tbMaSoSPDAL masospDAL = new tbMaSoSPDAL(); masospDAL.Insert(masosp); } public static void Update_MaSoSP(tbMaSoSP masosp) { tbMaSoSPDAL masospDAL = new tbMaSoSPDAL(); masospDAL.Update(masosp); } public static void Delete_MaSoSP(int Id) { tbMaSoSPDAL masospDAL = new tbMaSoSPDAL(); masospDAL.Delete(Id); } public static tbMaSoSP.tbMaSoSPCollection Get(string Where, int pageindex, int pagesize, string orderby, string orderdirection, out int total) { tbMaSoSPDAL masospDAL = new tbMaSoSPDAL(); return (masospDAL.Get(Where, pageindex, pagesize, orderby, orderdirection, out total)); } public static tbMaSoSP.tbMaSoSPCollection GetAll() { int total = 0; tbMaSoSPDAL masospDAL = new tbMaSoSPDAL(); return masospDAL.Get("Where 1=1", 0, 0, tbMaSoSP.tbMaSoSPColumns.IDMSSP.ToString(), "ASC", out total); } public static tbMaSoSP GetByID(int iD) { int total = 0; tbMaSoSPDAL masospDAL = new tbMaSoSPDAL(); tbMaSoSP.tbMaSoSPCollection masospcollection = masospDAL.Get("where " + tbMaSoSP.tbMaSoSPColumns.IDMSSP.ToString() + "=" + iD.ToString(), 0, 0, tbMaSoSP.tbMaSoSPColumns.IDMSSP.ToString(), "ASC", out total); if (masospcollection.Count > 0) return masospcollection[0]; return null; } } }
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/BUS/tbMaSoSPBUS.cs
C#
gpl3
1,792
using System; using System.Collections.Generic; using System.Text; using Entities; using DAL; using System.Data.SqlClient; namespace BUS { public class tbNhanVienBUS { public static void Insert(tbNhanVien nhanvien) { tbNhanVienDAL nhanvienDAL = new tbNhanVienDAL(); nhanvienDAL.Insert(nhanvien); } public static void Update(tbNhanVien nhanvien) { tbNhanVienDAL nhanvienDAL = new tbNhanVienDAL(); nhanvienDAL.Update(nhanvien); } public static void Delete(int iD) { tbNhanVienDAL nhanvienDAL = new tbNhanVienDAL(); nhanvienDAL.Delete(iD); } public static Entities.tbNhanVien.tbNhanVienCollection Get(string where, int pageindex, int pagesize, string orderby, string orderdirection, out int total) { tbNhanVienDAL nhanvienDAL = new tbNhanVienDAL(); return nhanvienDAL.Get(where, pageindex, pagesize, orderby, orderdirection, out total); } public static Entities.tbNhanVien.tbNhanVienCollection GetAll() { int total = 0; tbNhanVienDAL nhanvienDAL = new tbNhanVienDAL(); return nhanvienDAL.Get("where 1=1", 0, 0, tbNhanVien.tbNhanVienColumns.IDNhanVien.ToString(), "ASC", out total); } public static tbNhanVien GetByID(int iD) { int total = 0; tbNhanVienDAL nhanvienDAL = new tbNhanVienDAL(); tbNhanVien.tbNhanVienCollection nhanvienCollection = nhanvienDAL.Get("where " + tbNhanVien.tbNhanVienColumns.IDNhanVien.ToString() + "=" + iD.ToString(), 0, 0, tbNhanVien.tbNhanVienColumns.IDNhanVien.ToString(), "ASC", out total); if (nhanvienCollection.Count > 0) return nhanvienCollection[0]; return null; } } }
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/BUS/tbNhanVienBUS.cs
C#
gpl3
1,917
using System; using System.Collections.Generic; using System.Text; using DAL; using Entities; namespace BUS { public class tbDiaDiemBUS { public static void Insert(tbDiaDiem diadiem) { tbDiaDiemDAL diadiemDAL = new tbDiaDiemDAL(); diadiemDAL.Insert(diadiem); } public static void Update_DiaDiem(tbDiaDiem diadiem) { tbDiaDiemDAL diadiemDAL = new tbDiaDiemDAL(); diadiemDAL.Update(diadiem); } public static void Delete_DiaDiem(int iD) { tbDiaDiemDAL diadiemDAL = new tbDiaDiemDAL(); diadiemDAL.Delete(iD); } public static tbDiaDiem.tbDiaDiemCollection Get(string where, int pageindex, int pagesize, string orderby, string orderdirection, out int total) { tbDiaDiemDAL diadiemDAL = new tbDiaDiemDAL(); return diadiemDAL.Get(where, pageindex, pagesize, orderby, orderdirection, out total); } public static tbDiaDiem.tbDiaDiemCollection GetAll() { int total = 0; tbDiaDiemDAL diadiemDAL = new tbDiaDiemDAL(); return diadiemDAL.Get("where 1=1", 0, 0, tbDiaDiem.tbDiaDiemColumns.IDDiaDiem.ToString(), "ASC", out total); } public static tbDiaDiem GetByID(int iD) { int total = 0; tbDiaDiemDAL diadiemDAL = new tbDiaDiemDAL(); tbDiaDiem.tbDiaDiemCollection diadiemcollection = diadiemDAL.Get("where " + tbDiaDiem.tbDiaDiemColumns.IDDiaDiem.ToString() + "=" + iD.ToString(), 0, 0, tbDiaDiem.tbDiaDiemColumns.IDDiaDiem.ToString(), "ASC", out total); if (diadiemcollection.Count > 0) return diadiemcollection[0]; return null; } public static void Delete_LoaiSP(int id) { throw new Exception("The method or operation is not implemented."); } } }
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/BUS/tbDiaDiemBUS.cs
C#
gpl3
1,988
Create Table SanPham ( IDSanPham int identity(1,1), TenSanPham nvarchar(255), IDLoaiSP int, IDDiaDiem int, IDHangSanXuat int, GiaBan int, GiaTriThuc int, DieuKienSuDung nvarchar(255), MoTaSP nvarchar(255), SoLuongSP int, SoLuongBan int, SoLuongDaBan int, IDTrangThaiSP int, NgayBDBan datetime, NgayKTBan datetime, NgayCapNhat datetime, IDNhanVien int, IDDoanhNghiep int, TiLeHoaHong float, primary key (IDSanPham) ) Create Table LoaiSP ( IDLoaiSP int identity(1,1), TenLoaiSP nvarchar(255), primary key (IDLoaiSP) ) Create Table HangSanXuat ( IDHangSanXuat int identity(1,1), TenHangSanxuat nvarchar(255), DiaChi nvarchar(255), DienThoai int, Email nvarchar(255), primary key (IDHangSanXuat) ) Create Table TrangThaiSP ( IDTrangThaiSP int identity(1,1), TrangThai varchar(50), primary key (IDTrangThaiSP) ) Create Table DiaDiem ( IDDiaDiem int identity(1,1), DiaDiem nvarchar(255), primary key (IDDiaDiem) ) Create Table DoanhNghiep ( IDDoanhNghiep int identity(1,1), TenDoanhNghiep nvarchar(255), DiaChi nvarchar(255), DienThoai int, Email nvarchar(255), primary key (IDDoanhNghiep) ) Create Table NhanVien ( IDNhanVien int identity(1,1), TenNV nvarchar(255), DiaChi nvarchar(255), DienThoai int, Email nvarchar(255), primary key (IDNhanVien) ) Create Table HinhAnh ( IDHinhAnh int identity(1,1), IDSanPham int, TenHinh nvarchar(255), primary key (IDHinhAnh) ) Create Table KhachHang ( IDKhachHang int identity(1,1), TenKH nvarchar(255), DiaChi nvarchar(255), DienThoai int, Email nvarchar(255), primary key (IDKhachHang) ) Create Table DonHang ( IDDonHang int identity(1,1), IDKhachHang int, NgayDH datetime, IDTTDonHang int, TriGia int, NgayGiaoHang datetime, primary key (IDDonHang) ) Create Table ChiTietDH ( IDCTDH int identity (1,1), IDSanPham int, IDDonHang int, SoLuong int, ThanhTien int, primary key (IDCTDH) ) Create Table TTDonHang ( IDTTDonHang int identity(1,1), TrangThaiDH char(10), primary key (IDTTDonHang) ) Create Table MaSoSP ( IDMSSP int identity(1,1), IDCTDH int, MaSo int, TrangThai char(10), primary key (IDMSSP) ) Create Table TTGiaoDich ( IDTTGiaoDich int identity(1,1), IDDonHang int, IDHinhThuc int, ThanhTien int, primary key(IDTTGiaoDich) ) Create Table HTThanhToan ( IDHinhThuc int identity (1,1), TenHinhThuc nvarchar (50), primary key (IDHinhThuc) ) ----xoa san pham------------------------------------------------ CREATE PROCEDURE dbo.SanPham_Delete @IDSanPham INT AS DECLARE @TOTAL INT SELECT @TOTAL = COUNT(*) FROM tbCTDonHang WHERE IDSanPham = @IDSanPham IF @TOTAL = 0 BEGIN DELETE FROM SanPham where IDSanPham = @IDSanPham END -----xoa dia diem------------------------------------------------- CREATE PROCEDURE dbo.DiaDiem_Delete @IDDiaDiem INT AS DECLARE @TOTAL INT SELECT @TOTAL = COUNT(*) FROM tbSanPham WHERE IDDiaDiem = @IDDiaDiem IF @TOTAL = 0 BEGIN DELETE FROM IDDiaDiem where IDDiaDiem= @IDDiaDiem END -----xoa doanh nghiep---------------------------------------------- CREATE PROCEDURE dbo.DoanhNghiep_Delete @IDDoanhNghiep INT AS DECLARE @TOTAL INT SELECT @TOTAL = COUNT(*) FROM tbSanPham WHERE IDDoanhNghiep = @IDDoanhNghiep IF @TOTAL = 0 BEGIN DELETE FROM IDDoanhNghiep where IDDoanhNghiep= @IDDoanhNghiep END -----xoa hang san xuat----------------------------------------------- CREATE PROCEDURE dbo.HangSanXuat_Delete @IDHangSanXuat INT AS DECLARE @TOTAL INT SELECT @TOTAL = COUNT(*) FROM tbSanPham WHERE IDHangSanXuat = @IDHangSanXuat IF @TOTAL = 0 BEGIN DELETE FROM IDHangSanXuat where IDHangSanXuat= @IDHangSanXuat END -----xoa hinh anh----------------------------------------------------- CREATE PROCEDURE dbo.HinhAnh_Delete @IDHinhAnh INT AS DECLARE @TOTAL INT SELECT @TOTAL = COUNT(*) FROM tbSanPham WHERE IDHinhAnh = @IDHinhAnh IF @TOTAL = 0 BEGIN DELETE FROM IDHinhAnh where IDHinhAnh= @IDHinhAnh END -----xoa bang khach hang----------------------------------------------------- CREATE PROCEDURE dbo.KhachHang_Delete @IDKhachHang INT AS DECLARE @TOTAL INT SELECT @TOTAL = COUNT(*) FROM tbDonHang WHERE IDKhachHang = @IDKhachHang IF @TOTAL = 0 BEGIN DELETE FROM IDKhachHang where IDKhachHang= @IDKhachHang END -----xoa bang loai san pham--------------------------------------------------- CREATE PROCEDURE dbo.LoaiSP_Delete @IDLoaiSP INT AS DECLARE @TOTAL INT SELECT @TOTAL = COUNT(*) FROM tbSanPham WHERE IDLoaiSP = @IDLoaiSP IF @TOTAL = 0 BEGIN DELETE FROM IDLoaiSP where IDLoaiSP= @IDLoaiSP END -----xoa bang nhan vien-------------------------------------------------------- CREATE PROCEDURE dbo.NhanVien_Delete @IDNhanVien INT AS DECLARE @TOTAL INT SELECT @TOTAL = COUNT(*) FROM tbSanPham WHERE IDNhanVien = @IDNhanVien IF @TOTAL = 0 BEGIN DELETE FROM IDNhanVien where IDNhanVien= @IDNhanVien END ------------------cap nhat loai san pham ----------------------- CREATE PROCEDURE dbo.LoaiSP_Update @MaLoai int, @TenLoai NVARCHAR(255) AS UPDATE LoaiSP SET TenLoaiSP=@TenLoai WHERE IDLoaiSP = @MaLoai ---------------cap nhat hSX-------------------------- CREATE PROCEDURE dbo.HangSanXuat_Update @MaHangSX int, @TenHangSX NVARCHAR(255), @DiaChi NVARCHAR(255), @DienThoai int, @Email NVARCHAR(255) AS UPDATE HangSanXuat SET TenHangSanXuat=@TenHangSX , DiaChi=@DiaChi, DienThoai=@DienThoai, Email=@Email WHERE IDHangSanXuat = @MaHangSX -------------cap nhat nhan vien ---------------------------- CREATE PROCEDURE dbo.NhanVien_Update @MaNV int, @TenNV NVARCHAR(255), @DiaChi NVARCHAR(255), @DienThoai int, @Email NVARCHAR(255) AS UPDATE NhanVien SET TenNV=@TenNV , DiaChi=@DiaChi, DienThoai=@DienThoai, Email=@Email WHERE IDNhanVien = @MaNV --------------cap nhat doanh nghiep--------------------------- CREATE PROCEDURE dbo.DoanhNghiep_Update @MaDN int, @TenDN NVARCHAR(255), @DiaChi NVARCHAR(255), @DienThoai int, @Email NVARCHAR(255) AS UPDATE DoanhNghiep SET TenDoanhNghiep=@TenDN , DiaChi=@DiaChi, DienThoai=@DienThoai, Email=@Email WHERE IDDoanhNghiep = @MaDN ------------cap nhat ctdh------------------------------ CREATE PROCEDURE dbo.ChiTietDH_Update @IDCTDH int, @IDSanPham int, @IDDonHang int, @SoLuong int, @ThanhTien int AS UPDATE ChiTietDH SET IDSanPham=@IDSanPham, IDDonHang=@IDDonHang, SoLuong=@SoLuong, ThanhTien=@ThanhTien WHERE IDCTDH = @IDCTDH ------------cap nhat dia diem-------------- CREATE PROCEDURE dbo.DiaDiem_Update @IDDiaDiem int, @DiaDiem nvarchar(255) AS UPDATE DiaDiem SET DiaDiem=@DiaDiem WHERE IDDiaDiem = @IDDiaDiem -------------cap nhat don hang------------- CREATE PROCEDURE dbo.DonHang_Update @IDDonHang int, @IDKhachHang int, @NgayDH datetime, @IDTTDonHang int, @TriGia int, @NgayGiaoHang datetime AS UPDATE DonHang SET IDKhachHang=@IDKhachHang, NgayDH=@NgayDH, IDTTDonHang=@IDTTDonHang, TriGia=@TriGia, NgayGiaoHang=@NgayGiaoHang WHERE IDDonHang=@IDDonHang -----------cap nhat hinh anh------------ CREATE PROCEDURE dbo.HinhAnh_Update @IDHinhAnh int, @IDSanPham int, @TenHinh nvarchar(255) AS UPDATE HinhAnh SET IDSanPham=@IDSanPham, TenHinh=@TenHinh WHERE IDHinhAnh = @IDHinhAnh ----------cap nhat HTThanhtoan------------- CREATE PROCEDURE dbo.HTThanhToan_Update @IDHinhThuc int, @TenHinhThuc nvarchar(50) AS UPDATE HTThanhToan SET TenHinhThuc=@TenHinhThuc WHERE IDHinhThuc = @IDHinhThuc -----------cap nhat khach hang---- CREATE PROCEDURE dbo.KhachHang_Update @IDKhachHang int, @TenKH NVARCHAR(255), @DiaChi NVARCHAR(255), @DienThoai int, @Email NVARCHAR(255) AS UPDATE KhachHang SET TenKH=@TenKH , DiaChi=@DiaChi, DienThoai=@DienThoai, Email=@Email WHERE IDKhachHang = @IDKhachHang ------------cap nhat mSSSP--------- CREATE PROCEDURE dbo.MaSoSP_Update @IDMSSP int, @IDCTDH int, @MaSo int, @TrangThai char (10) AS UPDATE MaSoSP SET IDCTDH=@IDCTDH , MaSo=@MaSo, TrangThai=@TrangThai WHERE IDMSSP = @IDMSSP --------cap nhat san pham ---- CREATE PROCEDURE dbo.SanPham_Update @IDSP int, @TenSP Nvarchar(250), @IDL int, @IDDiaDiem int, @IDHangSanXuat int, @GiaBan int, @GiaTriThuc int, @DKSuDung Nvarchar(255), @MoTaSP Nvarchar(255), @SLSanPham int, @SLBan int, @SLDaBan int, @IDTrangThaiSP int, @NgayBDBan datetime, @NgayKTBan datetime, @NgayCapNhat datetime, @IDNhanVien int, @IDDoanhNghiep int, @TiLeHoaHong float As Update SanPham Set TenSanPham = @TenSP, IDLoaiSP = @IDL, IDDiaDiem =@IDDiaDiem, IDHangSanXuat=@IDHangSanXuat, GiaBan=@GiaBan, GiaTriThuc=@GiaTriThuc, DieuKienSuDung=@DKSuDung, MoTaSP=@MoTaSP, SoLuongSP=@SLSanPham, SoLuongBan=@SLBan, SoLuongDaBan=@SLDaBan, IDTrangThaiSP=@IDTrangThaiSP, NgayBDBan=@NgayBDBan, NgayKTBan=@NgayKTBan, NgayCapNhat=@NgayCapNhat, IDNhanVien=@IDNhanVien, IDDoanhNghiep=@IDDoanhNghiep, TiLeHoaHong=@TiLeHoaHong Where IDSanPham = @IDSP ----------cap nhat ttdh------------- CREATE PROCEDURE dbo.TTDonHang_Update @IDTTDonHang int, @TrangThaiDH char(10) AS UPDATE TTDonHang SET TrangThaiDH=@TrangThaiDH WHERE IDTTDonHang = @IDTTdonHang ----------cap nhat ttsp------------- CREATE PROCEDURE dbo.TrangThaiSP_Update @IDTrangThaiSP int, @TrangThai varchar(50) AS UPDATE TrangThaiSP SET TrangThai=@TrangThai WHERE IDTrangThaiSP = @IDTrangThaiSP ----------cap nhat ttgd------------- CREATE PROCEDURE dbo.TTGiaoDich_Update @IDTTGiaoDich int, @IDDonHang int, @IDHinhThuc int, @ThanhTien int AS UPDATE TTGiaoDich SET IDDonHang=@IDDonHang, IDHinhThuc=@IDHinhThuc, ThanhTien=@ThanhTien WHERE IDTTGiaoDich = @IDTTGiaoDich ---------------insert ctdh---------------- CREATE PROCEDURE dbo.ChiTietDH_Insert @IDSanPham int, @IDDonHang int, @SoLuong int, @ThanhTien int AS INSERT INTO ChiTietDH VALUES( @IDSanPham, @IDDonHang, @SoLuong, @ThanhTien ) -----------------insert dd--------------- CREATE PROCEDURE dbo.DiaDiem_Insert @DiaDiem nvarchar(255) AS INSERT INTO DiaDiem VALUES( @DiaDiem ) -----------------insert dn--------------- CREATE PROCEDURE dbo.DoanhNghiep_Insert @TenDoanhNghiep nvarchar(255), @DiaChi nvarchar(255), @DienThoai int, @Email nvarchar(255) AS INSERT INTO DoanhNghiep VALUES( @TenDoanhNghiep, @DiaChi, @DienThoai, @Email ) -----------------insert dh--------------- CREATE PROCEDURE dbo.DonHang_Insert @IDKhachHang int, @NgayDH datetime, @IDTTDonHang int, @TriGia int, @NgayGiaoHang datetime AS INSERT INTO DonHang VALUES( @IDKhachHang, @NgayDH, @IDTTDonHang, @TriGia, @NgayGiaoHang ) ----------------insert ha---------------- create procedure dbo.HinhAnh_insert @IDSanPham int, @TenHinh nvarchar(255) as insert into HinhAnh values ( @IDSanPham , @TenHinh ) ----------------insert htthanhtoan---------------- create procedure dbo.HTThanhToan_insert @TenHinhThuc nvarchar(50) as insert into HTThanhToan values ( @TenHinhThuc ) ----------------insert khach hang---------------- create procedure dbo.KhachHang_insert @TenKH nvarchar(255), @DiaChi nvarchar(255), @DienThoai int, @Email nvarchar(255) as insert into KhachHang values ( @TenKH , @DiaChi , @DienThoai , @Email ) ----------------insert loai sp---------------- create procedure dbo.LoaiSP_insert @TenLoaiSP nvarchar (255) as insert into LoaiSP values ( @TenLoaiSP ) ----------------insert Massp---------------- create procedure dbo.MaSoSP_insert @IDCTDH int, @MaSo int, @TrangThai char(10) as insert into MaSoSP values ( @IDCTDH, @MaSo, @TrangThai ) ----------------insert nhanvien---------------- create procedure dbo.NhanVien_insert @TenNV nvarchar (255), @DiaChi nvarchar (255), @DienThoai int, @Email nvarchar(255) as insert into NhanVien values ( @TenNV , @DiaChi , @DienThoai , @Email ) ----------------insert sanpham---------------- create procedure dbo.SanPham_insert @TenSanPham nvarchar (255), @IDLoaiSP int, @IDDiaDiem int, @IDHangSanXuat int, @GiaBan int, @GiaTriThuc int, @DieuKienSuDung nvarchar(255), @MoTaSP nvarchar(255), @SoLuongSP int, @SoLuongBan int, @SoLuongDaBan int, @IDTrangThaiSP int, @NgayBDBan datetime, @NgayKTBan datetime, @NgayCapNhat datetime, @IDNhanVien int, @IDDoanhNghiep int, @TiLeHoaHong float as insert into SanPham values ( @TenSanPham , @IDLoaiSP , @IDDiaDiem , @IDHangSanXuat, @GiaBan , @GiaTriThuc , @DieuKienSuDung, @MoTaSP , @SoLuongSP, @SoLuongBan , @SoLuongDaBan, @IDTrangThaiSP, @NgayBDBan , @NgayKTBan, @NgayCapNhat, @IDNhanVien, @IDDoanhNghiep, @TiLeHoaHong ) ----------------insert ttsp---------------- create procedure dbo.TrangThaiSP_insert @TrangThai varchar(50) as insert into TrangThaiSP values ( @TrangThai ) ----------------insert ttdh---------------- create procedure dbo.TTDonHang_insert @TrangThaiDH char(10) as insert into TTDonHang values ( @TrangThaiDH ) ----------------insert ttgd---------------- create procedure dbo.TTGiaoDich_insert @IDDonHang int, @IDHinhThuc int, @ThanhTien int as insert into TTGiaoDich values ( @IDDonHang, @IDHinhThuc, @ThanhTien ) ----------------insert hsx---------------- create procedure dbo.HangSanXuat_insert @TenHangSanxuat nvarchar (255), @DiaChi nvarchar (255), @DienThoai int, @Email nvarchar(255) as insert into HangSanXuat values ( @TenHangSanxuat , @DiaChi, @DienThoai, @Email ) ----------------phuong thuc get------------- create Procedure dbo.tbChiTietDH_Get @Where NVarchar(255), @PageIndex int, @PageSize int, @OrderBy NVarchar(25), @OrderDirection NVarchar(4), @TotalRecords int output As set transaction isolation level read committed Create Table #Temp ( IDTemp int identity(1,1), IDCTDH int ) Declare @sql NVarchar(1000) Set @sql = 'Insert Into #Temp ([IDCTDH]) Select [IDCTDH] From ChiTietDH ' + @Where + ' Order By ' + @OrderBy + ' ' + @OrderDirection Exec (@sql) Select @TotalRecords = count (*) from #Temp Select ctdh.IDCTDH,ctdh.IDSanPham,ctdh.IDDonHang,ctdh.SoLuong,ctdh.ThanhTien From #Temp as t Join DonHang as ctdh on t.IDCTDH = ctdh.IDCTDH Where (@PageIndex = 0) Or t.IDTemp > (@PageIndex - 1) * @PageSize and t.IDTemp <= @PageIndex * @PageSize Drop table #Temp ---------------------------------- create procedure dbo.tbDiaDiem_Get @Where Nvarchar(250), @PageIndex int, @PageSize int, @OrderBy Nvarchar(250), @OrderDirection Nvarchar(250), @TotalRecords int output As set transaction isolation level read committed create table #Temp ( IDTemp int identity(1,1), IDDiaDiem int ) Declare @sql Nvarchar(1000) Set @sql = 'Insert Into #Temp ([IDDiaDiem]) Select [IDDiaDiem] From DiaDiem ' + @Where + ' Order By ' + @OrderBy + ' ' + @OrderDirection Exec(@sql) Select @TotalRecords = count(*) from #Temp Select dd.IDDiaDiem,dd.DiaDiem From #Temp as T Join DiaDiem as dd On T.IDDiaDiem = dd.IDDiaDiem Where (@PageIndex = 0) Or (T.IDTemp > (@PageIndex - 1)*@PageSize And T.IDTemp <= @PageIndex * @PageSize) Drop table #Temp ------------------------------ create procedure dbo.tbDoanhNghiep_Get @Where NVARCHAR(255), @PageIndex INT, @PageSize INT, @OrderBy NVARCHAR(25), @OrderDirection NVARCHAR(4), @TotalRecords INT OUTPUT as set transaction isolation level read committed create table #Temp( IDTemp int identity(1,1), IDDoanhNghiep int ) declare @sql nvarchar (1000) set @sql = 'insert into #temp ([IDDN]) selete [IDDN] from DoanhNghiep ' + @Where + 'ORDER BY ' + @OrderBy + ' ' + @OrderDirection EXEC (@sql) select @ToTalRecords = COUNT(*) From #Temp select dn.IDDoanhNghiep, dn.TenDoanhNghiep, dn.DiaChi, dn.DienThoai, dn.Email from #Temp as T join DoanhNghiep as S on T.IDDoanhNghiep = S.IDDoanhNghiep where (@PageIndex = 0 ) or (T.IDTemp > (@PageIndex - 1 ) * @PageSize and T.IDTemp <= @PageIndex * @PageSize) drop table #temp ----------------------------------- create Procedure dbo.tbDonHang_Get @Where NVarchar(255), @PageIndex int, @PageSize int, @OrderBy NVarchar(25), @OrderDirection NVarchar(4), @TotalRecords int output As set transaction isolation level read committed Create Table #Temp ( IDTemp int identity(1,1), IDDonHang int ) Declare @sql NVarchar(1000) Set @sql = 'Insert Into #Temp ([IDDonHang]) Select [IDDonHang] From DonHang ' + @Where + ' Order By ' + @OrderBy + ' ' + @OrderDirection Exec (@sql) Select @TotalRecords = count (*) from #Temp Select dh.IDDonHang,dh.IDKhachHang,dh.NgayDH,dh.IDTTDonHang,dh.TriGia,dh.NgayGiaoHang From #Temp as t Join DonHang as dh on t.IDDonHang = dh.IDDonHang Where (@PageIndex = 0) Or t.IDTemp > (@PageIndex - 1) * @PageSize and t.IDTemp <= @PageIndex * @PageSize Drop table #Temp ---------------------------------- create procedure dbo.tbHinhAnh_Get @Where Nvarchar(250), @PageIndex int, @PageSize int, @OrderBy Nvarchar(250), @OrderDirection Nvarchar(250), @TotalRecords int output As set transaction isolation level read committed create table #Temp ( IDTemp int identity(1,1), IDHinhAnh int ) Declare @sql Nvarchar(1000) Set @sql = 'Insert Into #Temp ([IDHinhAnh] Select [IDHinhAnh] From HinhAnh) ' + @Where + 'Order By ' + @OrderBy + ' ' + @OrderDirection Exec(@sql) Select @TotalRecords = count(*) from #Temp Select ha.IDHinhAnh, ha.TenHinh, ha.IDSanPham From #Temp as T Join HinhAnh as ha on T.IDHinhAnh = ha.IDHinhAnh Where (@PageIndex = 0) Or (T.IDTemp > (@PageIndex - 1) * @PageSize And T.IDTemp <= @pageIndex * @PageSize) Drop table #Temp ----------------------------------- create procedure dbo.tbHTThanhToan_Get @Where Nvarchar(250), @PageIndex int, @PageSize int, @OrderBy Nvarchar(250), @OrderDirection Nvarchar(4), @TotalRecords int output As set transaction isolation level read committed create table #Temp ( IDTemp int identity(1,1), IDHinhThuc int ) Declare @sql Nvarchar(1000) Set @sql = 'Insert Into #Temp ([IDHinhThuc]) Select [IDHinhThuc] From HTThanhToan ' + @Where + ' Order By ' + @OrderBy + ' ' + @OrderDirection Exec(@sql) Select @TotalRecords = count(*) from #Temp Select tt.IDHinhThuc, tt.TenHinhThuc From #Temp as T Join HTThanhToan as tt On T.IDHinhThuc = tt.IDHinhThuc Where (@PageIndex = 0) Or ( (T.IDTemp > (@PageIndex - 1) * @PageSize And T.IDTemp <= @PageIndex * @PageSize) ) Drop table #Temp ------------------------------ create procedure dbo.tbKhachHang_Get @Where NVARCHAR(255), @PageIndex INT, @PageSize INT, @OrderBy NVARCHAR(25), @OrderDirection NVARCHAR(4), @TotalRecords INT OUTPUT as set transaction isolation level read committed create table #Temp( IDTemp int identity(1,1), IDKhachHang int ) declare @sql nvarchar (1000) set @sql = 'insert into #temp ([IDKhachHang]) selete [IDKhachHang] from KhachHang ' + @Where + 'ORDER BY ' + @OrderBy + ' ' + @OrderDirection EXEC (@sql) select @ToTalRecords = COUNT(*) From #Temp select kh.IDKhachHang, kh.TenKH, kh.GioiTinh, kh.DiaChi, kh.DienThoai, kh.Email from #Temp as T join KhachHang as S on T.IDKhachHang = S.IDKhachHang where (@PageIndex = 0 ) or (T.IDTemp > (@PageIndex - 1 ) * @PageSize and T.IDTemp <= @PageIndex * @PageSize) drop table #temp --------------------------- create procedure dbo.tbLoaiSP_Get @Where Nvarchar(250), @PageIndex int, @PageSize int, @OrderBy Nvarchar(250), @OrderDirection Nvarchar(250), @TotalRecords int output As set transaction isolation level read committed create table #Temp ( IDTemp int identity(1,1), IDLoaiSP int ) Declare @sql Nvarchar(1000) Set @sql = 'Insert Into #Temp ([IDLoaiSP]) Select [IDLoaiSP] From LoaiSP ' + @Where + ' Order By ' + @OrderBy + ' ' + @OrderDirection Exec(@sql) Select @TotalRecords = count(*) from #Temp Select lsp.IDLoaiSP,lsp.TenLoaiSP From #Temp as T Join LoaiSP as lsp On T.IDLoaiSP = lsp.IDLoaiSP Where (@PageIndex = 0) Or (T.IDTemp > (@PageIndex - 1)* @PageSize And T.IDTemp <= @PageIndex * @PageSize) Drop table #Temp ------------------------- create procedure dbo.tbMaSoSP_Get @Where Nvarchar(250), @PageIndex int, @PageSize int, @OrderBy Nvarchar(250), @OrderDirection Nvarchar(250), @TotalRecords int output As set transaction isolation level read committed create table #Temp ( IDTemp int identity(1,1), IDMSSP int ) Declare @sql Nvarchar(1000) Set @sql = 'Insert Into #Temp ([IDMSSP] Select [IDMSSP] From MaSoSP )' + @Where + ' Order By ' + @OrderBy + ' ' + @OrderDirection Exec(@sql) Select @TotalRecords = count(*) from #Temp Select maso_sp.IDMSSP,maso_sp.IDCTDH,maso_sp.MaSo,maso_sp.TrangThai From #Temp as T Join MaSoSP as maso_sp On T.IDMSSP = maso_sp.IDMSSP Where (@PageIndex = 0) Or (T.IDTemp > (@PageIndex - 1) * @PageSize And T.IDTemp <= @PageIndex * @PageSize) Drop table #Temp --------------------- create procedure dbo.tbNhanVien_Get @Where NVARCHAR(255), @PageIndex INT, @PageSize INT, @OrderBy NVARCHAR(25), @OrderDirection NVARCHAR(4), @TotalRecords INT OUTPUT as set transaction isolation level read committed create table #Temp( IDTemp int identity(1,1), IDNhanVien int ) declare @sql nvarchar (1000) set @sql = 'insert into #temp ([IDNhanVien]) selete [IDNhanVien] from NhanVien ' + @Where + 'ORDER BY ' + @OrderBy + ' ' + @OrderDirection EXEC (@sql) select @ToTalRecords = COUNT(*) From #Temp select S.IDNhanVien, S.TenNV, S.DiaChi, S.DienThoai, S.Email from #Temp as T join NhanVien as S on T.IDNhanVien = S.IDNhanVien where (@PageIndex = 0 ) or (T.IDTemp > (@PageIndex - 1 ) * @PageSize and T.IDTemp <= @PageIndex * @PageSize) drop table #Temp --------------------- create procedure dbo.tbSanPham_Get @Where Nvarchar(250), @PageIndex int, @PageSize int, @OrderBy Nvarchar(250), @OrderDirection Nvarchar(250), @TotalRecords int output As set transaction isolation level read committed create table #Temp ( IDTemp int identity(1,1), IDSanPham int ) Declare @sql Nvarchar(1000) Set @sql = 'Insert Into #Temp ([IDSanPham]) Select [IDSanPham] From SanPham )' + @Where + ' Order By ' + @OrderBy + ' ' + @OrderDirection Exec(@sql) Select @TotalRecords = count(*) from #Temp Select sp.IDSanPham,sp.TenSanPham,sp.IDLoaiSP,sp.IDDiaDiem,sp.IDHangSanXuat,sp.GiaBan,sp.GiaTriThuc,sp.DieuKienSuDung,sp.MoTaSP, sp.SLBaSoLuongSP,sp.SoLuongBan,sp.SoLuongDaBan,sp.IDTrangThaiSP,sp.NgayBDBan,sp.NgayKTBan,sp.NgayCapNhat, sp.IDNhanVien,sp.IDDoanhNghiep,sp.TiLeHoaHong From #Temp as T Join SanPham as sp On T.IDSanPham = sp.IDSanPham Where (@PageIndex = 0) Or (T.IDTemp > (@PageIndex - 1) * @PageSize And T.IDTemp <= @PageIndex * @PageSize) Drop table #Temp ----------------------- create procedure dbo.tbTrangThaiDH_Get @Where Nvarchar(250), @PageIndex int, @PageSize int, @OrderBy Nvarchar(250), @OrderDirection Nvarchar(4), @TotalRecords int output As set transaction isolation level read committed create table #Temp ( IDTemp int identity(1,1), IDTTDonHang int ) Declare @sql Nvarchar(1000) Set @sql = 'Insert Into #Temp ([IDTTDonHang]) Select [IDTTDonHang] From TTDonHang ' + @Where + ' Order By ' + @OrderBy + ' ' + @OrderDirection Exec(@sql) Select @TotalRecords = count(*) from #Temp Select tt.IDTTDonHang,tt.TrangThaiDH From #Temp as T Join TTDonHang as tt On T.IDTTDonHang = tt.IDTTDonHang Where (@PageIndex = 0) Or (T.IDTemp > (@PageIndex - 1) * @PageSize and T.IDTemp <= @PageIndex * @PageSize) Drop table #Temp -------------------- create procedure dbo.tbTrangThaiSP_Get @Where Nvarchar(250), @PageIndex int, @PageSize int, @OrderBy Nvarchar(250), @OrderDirection Nvarchar(250), @TotalRecords int output As set transaction isolation level read committed create table #Temp ( IDTemp int identity(1,1), IDTrangThaiSP int ) Declare @sql Nvarchar(1000) Set @sql = 'Insert Into #Temp ([IDTrangThaiSP]) Select [IDTrangThaiSP] From TrangThaiSP ' + @Where + ' Order By ' + @OrderBy + ' ' + @OrderDirection Exec(@sql) Select @TotalRecords = count(*) from #Temp Select tt_sp.IDTrangThaiSP, tt_sp.TrangThai From #Temp as T Join TrangThaiSP as tt_sp On T.IDTrangThaiSP = tt_sp.IDTrangThaiSP Where (@PageIndex = 0) Or (T.IDTemp > (@PageIndex - 1)* @PageSize And T.IDTemp <= @PageIndex * @PageSize) Drop table #Temp ---------------- create procedure dbo.tbTTGiaoDich_Get @Where Nvarchar(250), @PageIndex int, @PageSize int, @OrderBy Nvarchar(250), @OrderDirection Nvarchar(250), @TotalRecords int output As set transaction isolation level read committed create table #Temp ( IDTemp int identity(1,1), IDTTGiaoDich int ) Declare @sql Nvarchar(1000) Set @sql = 'Insert Into #Temp ([IDTTGiaoDich]) Select [IDTTGiaoDich] From TTGiaoDich ' + @Where + ' Order By ' + @OrderBy + ' ' + @OrderDirection Exec(@sql) Select @TotalRecords = count(*) from #Temp Select tt_gd.IDTTGiaoDich,tt_gd.IDDonHang,tt_gd.IDHinhThuc,tt_gd.ThanhTien From #Temp as T Join TTGiaoDich as tt_gd On T.IDTTGiaoDich = tt_gd.IDTTGiaoDich Where (@PageIndex = 0) Or (T.IDTemp > (@PageIndex - 1) * @PageSize And T.IDTemp <= @PageIndex * @PageSize) Drop table #Temp ------------------------- create procedure dbo.tbHangSanXuat_Get @Where Nvarchar(250), @PageIndex int, @PageSize int, @OrderBy Nvarchar(250), @OrderDirection Nvarchar(250), @TotalRecords int output As set transaction isolation level read committed create table #Temp ( IDTemp int identity(1,1), IDHangSanXuat int ) Declare @sql Nvarchar(1000) Set @sql = 'Insert Into #Temp ([IDHangSanXuat]) Select [IDHangSanXuat] From HangSanXuat ' + @Where + ' Order By ' + @OrderBy + ' ' + @OrderDirection Exec(@sql) Select @TotalRecords = count(*) from #Temp Select tt_gd.IDHangSanXuat,tt_gd.TenHangSanxuat,tt_gd.DiaChi,tt_gd.DienThoai,tt_gd.Email From #Temp as T Join HangSanXuat as tt_gd On T.IDHangSanXuat = tt_gd.IDHangSanXuat Where (@PageIndex = 0) Or (T.IDTemp > (@PageIndex - 1) * @PageSize And T.IDTemp <= @PageIndex * @PageSize) Drop table #Temp
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/App_Data/groupon_nhom1.sql
TSQL
gpl3
26,448
<%@ Page Language="C#" MasterPageFile="~/Admin/MasterPage.master" AutoEventWireup="true" CodeFile="DoanhNghiepList.aspx.cs" Inherits="Admin_DoanhNghiepList" Title="Untitled Page" %> <asp:Content ID="Content1" ContentPlaceHolderID="menuPlaceHolder" Runat="Server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="contentPlaceHolder" Runat="Server"> </asp:Content>
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/Admin/DoanhNghiepList.aspx
ASP.NET
gpl3
386
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Admin_NhanVienAdd : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } }
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/Admin/NhanVienAdd.aspx.cs
C#
gpl3
415
<%@ Page Language="C#" MasterPageFile="~/Admin/MasterPage.master" AutoEventWireup="true" CodeFile="NhanVienList.aspx.cs" Inherits="Admin_NhanVienList" Title="Untitled Page" %> <asp:Content ID="Content1" ContentPlaceHolderID="menuPlaceHolder" Runat="Server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="contentPlaceHolder" Runat="Server"> </asp:Content>
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/Admin/NhanVienList.aspx
ASP.NET
gpl3
380
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using Entities; using BUS; using DAL; using Utility; public partial class Admin_LoaiSPList : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { LoadData1(); } } private void LoadData1() { Criteria cri = new Criteria(); int total = 0; if (txt_tlsp.Text != "") { cri.add(Condition.AND, tbLoaiSP.tbLoaiSPColumns.TenLoaiSP.ToString(), Condition.LIKE, txt_tlsp.Text); } tbLoaiSP.tbLoaiSPCollection loaispcollection = tbLoaiSPBUS.Get(cri.Criter, Pager.CurrentIndex, Pager.PageSize, tbLoaiSP.tbLoaiSPColumns.IDLoaiSP.ToString(), OrderDirection.ASC.ToString(), out total); Repeater1.DataSource = loaispcollection; Repeater1.DataBind(); Pager.ItemCount = total; } protected void btn_Search_Click(object sender, EventArgs e) { LoadData1(); } protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) { tbLoaiSP tlsp = (tbLoaiSP)e.Item.DataItem; HyperLink hyp_tlsp = (HyperLink)e.Item.FindControl("hyp_tlsp"); Literal lit_mlsp = (Literal)e.Item.FindControl("lit_mlsp"); HiddenField hf_id = (HiddenField)e.Item.FindControl("hf_id"); lit_mlsp.Text = tlsp.IDLoaiSP.ToString(); hf_id.Value = tlsp.IDLoaiSP.ToString(); hyp_tlsp.Text = tlsp.TenLoaiSP.ToString(); hyp_tlsp.NavigateUrl = "LoaiSPList.aspx"; HyperLink hpl_Edit = (HyperLink)e.Item.FindControl("hpl_Edit"); hpl_Edit.NavigateUrl = "LoaiSPUpdate.aspx?id=" + tlsp.IDLoaiSP.ToString(); } } protected void Pager_Command(object sender, CommandEventArgs e) { Pager.CurrentIndex = int.Parse(e.CommandArgument.ToString()); LoadData1(); } protected void lbt_Xoa_Click(object sender, EventArgs e) { for (int i = 0; i < Repeater1.Items.Count; i++) { CheckBox cb_Xoa = (CheckBox)Repeater1.Items[i].FindControl("cb_Xoa"); if (cb_Xoa.Checked == true) { HiddenField hf_id = (HiddenField)Repeater1.Items[i].FindControl("hf_id"); int id = int.Parse(hf_id.Value); tbLoaiSP lsp = tbLoaiSPBUS.GetByID(id); tbLoaiSPBUS.Delete_LoaiSP(id); } } Response.Redirect(Request.RawUrl); } }
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/Admin/LoaiSPList.aspx.cs
C#
gpl3
2,945
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using Entities; using BUS; using DAL; using Utility; public partial class Admin_LoaiSPAdd : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { } } protected void btdd_them_Click(object sender, EventArgs e) { tbLoaiSP lsp = new tbLoaiSP(); lsp.TenLoaiSP = txt_tlsp.Text; tbLoaiSPBUS .Insert_LoaiSP(lsp); Response.Redirect("~/Admin/LoaiSPList.aspx"); } }
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/Admin/LoaiSPAdd.aspx.cs
C#
gpl3
774
<%@ Page Language="C#" MasterPageFile="~/Admin/MasterPage.master" AutoEventWireup="true" CodeFile="LoaiSPAdd.aspx.cs" Inherits="Admin_LoaiSPAdd" Title="Untitled Page" %> <asp:Content ID="Content1" ContentPlaceHolderID="menuPlaceHolder" Runat="Server"> <h5>Menu</h5> <ul class ="Actions"> <li><a href ="sanphamlist.aspx">Danh sách sản phẩm</a></li> <li><a href ="SanPhamAdd.aspx">Thêm mới sản phẩm</a></li> </ul> <ul class ="Actions"> <li ><a href ="LoaiSPList.aspx">Danh sách loại sản phẩm</a></li> <li class="Selected"><a href ="LoaiSPAdd.aspx">Thêm mới loại sản phẩm</a></li> </ul> <ul class ="Actions"> <li><a href ="DiaDiemList.aspx">Thông tin địa điểm</a></li> <li><a href ="DiaDiemAdd.aspx">Thêm mới địa điểm</a></li> </ul> <ul class ="Actions"> <li><a href ="DoanhNghiepList.aspx">Danh sách doanh nghiệp</a></li> <li><a href ="DoanhNghiepAdd.aspx">Thêm mới doanh nghiệp</a></li> </ul> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="contentPlaceHolder" Runat="Server"> <div > <div class ="title" > THÊM MỚI LOẠI SẢN PHẨM </div> <div > <table width ="100%" cellspacing ="1" cellpadding ="3" border ="0" > <tr> <td style ="width :30%"> Tên loại sản phẩm</td> <td style ="width :70%"><asp:TextBox ID ="txt_tlsp" runat ="server" ></asp:TextBox></td> </tr> <tr align="center"> <td style="width :30%; height: 30px;"></td> <td style="width :70%; height: 30px;"><asp:Button ID ="btdd_them" runat ="server" Text ="Thêm mới loại sản phẩm" OnClick ="btdd_them_Click" ></asp:Button></td> </tr> </table> </div> </div> </asp:Content>
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/Admin/LoaiSPAdd.aspx
ASP.NET
gpl3
1,813
function $(str){ return document.getElementById(str); } function CheckAll(obj) { var checkAll = true; var checkList = document.getElementsByTagName("input"); if(obj == 2) { $("cb_All").checked = !$("cb_All").checked; } if(!$("cb_All").checked) checkAll = false; for(var i = 0 ; i < checkList.length ; i++) { if(checkList[i].type == 'checkbox' && checkList[i].id.indexOf("cb_Xoa") >= 0 ) { checkList[i].checked = checkAll; } } }
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/Admin/js/JScript.js
JavaScript
gpl3
533
<%@ Page Language="C#" MasterPageFile="~/Admin/MasterPage.master" AutoEventWireup="true" CodeFile="DoanhNghiepAdd.aspx.cs" Inherits="Admin_DoanhNghiepAdd" Title="Untitled Page" %> <asp:Content ID="Content1" ContentPlaceHolderID="menuPlaceHolder" Runat="Server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="contentPlaceHolder" Runat="Server"> </asp:Content>
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/Admin/DoanhNghiepAdd.aspx
ASP.NET
gpl3
384
<%@ Page Language="C#" MasterPageFile="~/Admin/MasterPage.master" AutoEventWireup="true" CodeFile="LoaiSPList.aspx.cs" Inherits="Admin_LoaiSPList" Title="Untitled Page" %> <%@ Register Assembly="ASPnetPagerV2_8" Namespace="ASPnetControls" TagPrefix="cc1" %> <asp:Content ID="Content1" ContentPlaceHolderID="menuPlaceHolder" Runat="Server"> <h5>Menu</h5> <ul class ="Actions"> <li><a href ="sanphamlist.aspx">Danh sách sản phẩm</a></li> <li><a href ="SanPhamAdd.aspx">Thêm mới sản phẩm</a></li> </ul> <ul class ="Actions"> <li class ="Selected" ><a href ="LoaiSPList.aspx">Danh sách loại sản phẩm</a></li> <li><a href ="LoaiSPAdd.aspx">Thêm mới loại sản phẩm</a></li> </ul> <ul class ="Actions"> <li><a href ="DiaDiemList.aspx">Thông tin địa điểm</a></li> <li><a href ="DiaDiemAdd.aspx">Thêm mới địa điểm</a></li> </ul> <ul class ="Actions"> <li><a href ="DoanhNghiepList.aspx">Danh sách doanh nghiệp</a></li> <li><a href ="DoanhNghiepAdd.aspx">Thêm mới doanh nghiệp</a></li> </ul> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="contentPlaceHolder" Runat="Server"> <div style="padding:12px 12px 12px 12px;"> <div> <div class="title"> Danh Sách Loại Sản Phẩm </div> <div style="width:100%;"> <div style="display:table-cell; width:75%;float:left;"> Mã loại sản phẩm: <asp:TextBox ID="txt_idlsp" runat="server" Width="122px"></asp:TextBox> Tên loại sản phẩm: <asp:TextBox ID="txt_tlsp" runat="server" Width = "122px"></asp:TextBox> <asp:Button ID="btn_Search" runat="server" Text="Tìm kiếm" OnClick="btn_Search_Click" /> </div> <div class="addnewrow" style="display:table-cell; width:23%;float:right;"> <a href="LoaiSPAdd.aspx">Thêm mới loại sản phẩm</a> | <asp:LinkButton ID="lbt_Xoa" runat="server" OnClick="lbt_Xoa_Click">Xóa</asp:LinkButton> </div> </div> <div> <asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound"> <HeaderTemplate> <table cellspacing="1" cellpadding="3" width="100%" border="0"> <thead> <tr class="listtableheader"> <th>Mã Loại Sản Phẩm</th> <th>Tên Loại Sản Phẩm</th> <th>Sửa</th> <th> <input id="cb_All" type="checkbox" onclick="CheckAll(1);" /> <a href="javascript:CheckAll(2)">Chọn hết</a> </th> </tr> </thead> <tbody> </HeaderTemplate> <ItemTemplate> <tr> <td><asp:Literal ID="lit_mlsp" runat="server" /></td> <td><asp:HyperLink ID="hyp_tlsp" runat="server"></asp:HyperLink></td> <td><asp:HyperLink ID="hpl_Edit" Text="Edit" runat="server" /></td> <td> <asp:CheckBox ID="cb_Xoa" runat="server" /> <asp:HiddenField ID="hf_id" runat="server" /> </td> </tr> </ItemTemplate> <FooterTemplate> </tbody> </table> </FooterTemplate> </asp:Repeater> </div> <div style="width:100%;"> <div style="float:left;"> <cc1:PagerV2_8 ID="Pager" runat="server" OnCommand="Pager_Command" /> </div> </div> </div> </div> </asp:Content>
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/Admin/LoaiSPList.aspx
ASP.NET
gpl3
3,866
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Admin_DoanhNghiepAdd : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } }
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/Admin/DoanhNghiepAdd.aspx.cs
C#
gpl3
418
<%@ Page Language="C#" MasterPageFile="~/Admin/MasterPage.master" AutoEventWireup="true" CodeFile="DiaDiemList.aspx.cs" Inherits="Admin_DiaDiemList" Title="Untitled Page" %> <%@ Register Assembly="ASPnetPagerV2_8" Namespace="ASPnetControls" TagPrefix="cc1" %> <asp:Content ID="Content1" ContentPlaceHolderID="menuPlaceHolder" Runat="Server"> <h5>Menu</h5> <ul class ="Actions"> <li><a href ="sanphamlist.aspx">Danh sách sản phẩm</a></li> <li><a href ="SanPhamAdd.aspx">Thêm mới sản phẩm</a></li> </ul> <ul class ="Actions"> <li ><a href ="LoaiSPList.aspx">Danh sách loại sản phẩm</a></li> <li><a href ="LoaiSPAdd.aspx">Thêm mới loại sản phẩm</a></li> </ul> <ul class ="Actions"> <li class="Selected"><a href ="DiaDiemList.aspx">Thông tin địa điểm</a></li> <li><a href ="DiaDiemAdd.aspx">Thêm mới địa điểm</a></li> </ul> <ul class ="Actions"> <li><a href ="DoanhNghiepList.aspx">Danh sách doanh nghiệp</a></li> <li><a href ="DoanhNghiepAdd.aspx">Thêm mới doanh nghiệp</a></li> </ul> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="contentPlaceHolder" Runat="Server"> <div style="padding:12px 12px 12px 12px;"> <div> <div class="title"> Danh sách Địa Điểm </div> <div style="width:100%;"> <div style="display:table-cell; width:75%;float:left;"> Mã Địa Điểm: <asp:TextBox ID="txt_id_dd" runat="server" Width="122px"></asp:TextBox> Địa điểm: <asp:TextBox ID="txt_dd" runat="server" Width = "122px"> </asp:TextBox> <asp:Button ID="btn_Search" runat="server" Text="Tìm kiếm" OnClick="btn_Search_Click" /> </div> <div class="addnewrow" style="display:table-cell; width:23%;float:right;"> <a href="DiaDiemAdd.aspx">Thêm Địa Điểm Mới</a> | <asp:LinkButton ID="lbt_Xoa" runat="server" OnClick="lbt_Xoa_Click1">Xóa</asp:LinkButton> </div> </div> <div> <asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound"> <HeaderTemplate> <table cellspacing="1" cellpadding="3" width="100%" bgcolor="#cccccc" border="0"> <thead> <tr class="listtableheader"> <th>Mã Địa Điểm</th> <th>Địa Điểm</th> <th>Sửa</th> <th> <input id="cb_All" type="checkbox" onclick="CheckAll(1);" /> <a href="javascript:CheckAll(2)">Chọn hết</a> </th> </tr> </thead> <tbody> </HeaderTemplate> <ItemTemplate> <tr> <td><asp:Literal ID="lit_Ma" runat="server" /></td> <td><asp:HyperLink ID="hyp_dd" runat="server"></asp:HyperLink></td> <td><asp:HyperLink ID="hpl_Edit" Text="Edit" runat="server" /></td> <td> <asp:CheckBox ID="cb_Xoa" runat="server" /> <asp:HiddenField ID="hf_id" runat="server" /> </td> </tr> </ItemTemplate> <FooterTemplate> </tbody> </table> </FooterTemplate> </asp:Repeater> </div> <div style="width:100%;"> <div style="float:left;"> <cc1:PagerV2_8 ID="Pager" runat="server" OnCommand="Pager_Command" /> </div> </div> </div> </div> </asp:Content>
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/Admin/DiaDiemList.aspx
ASP.NET
gpl3
3,879
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using Entities; using Utility; using BUS; public partial class Admin_DiaDiemAdd : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { } } protected void btdd_them_Click(object sender, EventArgs e) { tbDiaDiem dd = new tbDiaDiem(); dd.DiaDiem = txt_tendd.Text ; tbDiaDiemBUS.Insert(dd); Response.Redirect("~/Admin/DiaDiemList.aspx"); } }
02cdnth2-nhom1
trunk/source/02cdnth2_nhom1 _ them diadiem,loaisp/02cdnth2_nhom1_vantuan/Website/Admin/DiaDiemAdd.aspx.cs
C#
gpl3
759