code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
package com.ch_linghu.fanfoudroid.db;
import java.text.ParseException;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.util.Log;
import com.ch_linghu.fanfoudroid.data.Dm;
/**
* Table - Direct Messages
*
*/
public final class MessageTable implements BaseColumns {
public static final String TAG = "MessageTable";
public static final int TYPE_GET = 0;
public static final int TYPE_SENT = 1;
public static final String TABLE_NAME = "message";
public static final int MAX_ROW_NUM = 20;
public static final String FIELD_USER_ID = "uid";
public static final String FIELD_USER_SCREEN_NAME = "screen_name";
public static final String FIELD_PROFILE_IMAGE_URL = "profile_image_url";
public static final String FIELD_CREATED_AT = "created_at";
public static final String FIELD_TEXT = "text";
public static final String FIELD_IN_REPLY_TO_STATUS_ID = "in_reply_to_status_id";
public static final String FIELD_IN_REPLY_TO_USER_ID = "in_reply_to_user_id";
public static final String FIELD_IN_REPLY_TO_SCREEN_NAME = "in_reply_to_screen_name";
public static final String FIELD_IS_UNREAD = "is_unread";
public static final String FIELD_IS_SENT = "is_send";
public static final String[] TABLE_COLUMNS = new String[] { _ID,
FIELD_USER_SCREEN_NAME, FIELD_TEXT, FIELD_PROFILE_IMAGE_URL,
FIELD_IS_UNREAD, FIELD_IS_SENT, FIELD_CREATED_AT, FIELD_USER_ID };
public static final String CREATE_TABLE = "CREATE TABLE "
+ TABLE_NAME + " ("
+ _ID + " text primary key on conflict replace, "
+ FIELD_USER_SCREEN_NAME + " text not null, "
+ FIELD_TEXT + " text not null, "
+ FIELD_PROFILE_IMAGE_URL + " text not null, "
+ FIELD_IS_UNREAD + " boolean not null, "
+ FIELD_IS_SENT + " boolean not null, "
+ FIELD_CREATED_AT + " date not null, "
+ FIELD_USER_ID + " text)";
/**
* TODO: 将游标解析为一条私信
*
* @param cursor 该方法不会关闭游标
* @return 成功返回Dm类型的单条数据, 失败返回null
*/
public static Dm parseCursor(Cursor cursor) {
if (null == cursor || 0 == cursor.getCount()) {
Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty.");
return null;
}
Dm dm = new Dm();
dm.id = cursor.getString(cursor.getColumnIndex(MessageTable._ID));
dm.screenName = cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_USER_SCREEN_NAME));
dm.text = cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_TEXT));
dm.profileImageUrl = cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_PROFILE_IMAGE_URL));
dm.isSent = (0 == cursor.getInt(cursor.getColumnIndex(MessageTable.FIELD_IS_SENT))) ? false : true ;
try {
dm.createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_CREATED_AT)));
} catch (ParseException e) {
Log.w(TAG, "Invalid created at data.");
}
dm.userId = cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_USER_ID));
return dm;
}
} | Java |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.fanfou.User;
import com.ch_linghu.fanfoudroid.http.HttpAuthException;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskFeedback;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
//登录页面需要个性化的菜单绑定, 不直接继承 BaseActivity
public class LoginActivity extends Activity {
private static final String TAG = "LoginActivity";
private static final String SIS_RUNNING_KEY = "running";
private String mUsername;
private String mPassword;
// Views.
private EditText mUsernameEdit;
private EditText mPasswordEdit;
private TextView mProgressText;
private Button mSigninButton;
private ProgressDialog dialog;
// Preferences.
private SharedPreferences mPreferences;
// Tasks.
private GenericTask mLoginTask;
private User user;
private TaskListener mLoginTaskListener = new TaskAdapter(){
@Override
public void onPreExecute(GenericTask task) {
onLoginBegin();
}
@Override
public void onProgressUpdate(GenericTask task, Object param) {
updateProgress((String)param);
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
onLoginSuccess();
} else {
onLoginFailure(((LoginTask)task).getMsg());
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return "Login";
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);
// No Title bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
requestWindowFeature(Window.FEATURE_PROGRESS);
mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
setContentView(R.layout.login);
// TextView中嵌入HTML链接
TextView registerLink = (TextView) findViewById(R.id.register_link);
registerLink.setMovementMethod(LinkMovementMethod.getInstance());
mUsernameEdit = (EditText) findViewById(R.id.username_edit);
mPasswordEdit = (EditText) findViewById(R.id.password_edit);
// mUsernameEdit.setOnKeyListener(enterKeyHandler);
mPasswordEdit.setOnKeyListener(enterKeyHandler);
mProgressText = (TextView) findViewById(R.id.progress_text);
mProgressText.setFreezesText(true);
mSigninButton = (Button) findViewById(R.id.signin_button);
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(SIS_RUNNING_KEY)) {
if (savedInstanceState.getBoolean(SIS_RUNNING_KEY)) {
Log.d(TAG, "Was previously logging in. Restart action.");
doLogin();
}
}
}
mSigninButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
doLogin();
}
});
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestory");
if (mLoginTask != null && mLoginTask.getStatus() == GenericTask.Status.RUNNING) {
mLoginTask.cancel(true);
}
// dismiss dialog before destroy
// to avoid android.view.WindowLeaked Exception
TaskFeedback.getInstance(TaskFeedback.DIALOG_MODE,
LoginActivity.this).cancel();
super.onDestroy();
}
@Override
protected void onStop() {
Log.d(TAG, "onStop");
// TODO Auto-generated method stub
super.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mLoginTask != null
&& mLoginTask.getStatus() == GenericTask.Status.RUNNING) {
// If the task was running, want to start it anew when the
// Activity restarts.
// This addresses the case where you user changes orientation
// in the middle of execution.
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
// UI helpers.
private void updateProgress(String progress) {
mProgressText.setText(progress);
}
private void enableLogin() {
mUsernameEdit.setEnabled(true);
mPasswordEdit.setEnabled(true);
mSigninButton.setEnabled(true);
}
private void disableLogin() {
mUsernameEdit.setEnabled(false);
mPasswordEdit.setEnabled(false);
mSigninButton.setEnabled(false);
}
// Login task.
private void doLogin() {
mUsername = mUsernameEdit.getText().toString();
mPassword = mPasswordEdit.getText().toString();
if (mLoginTask != null && mLoginTask.getStatus() == GenericTask.Status.RUNNING){
return;
}else{
if (!TextUtils.isEmpty(mUsername) & !TextUtils.isEmpty(mPassword) ) {
mLoginTask = new LoginTask();
mLoginTask.setListener(mLoginTaskListener);
TaskParams params = new TaskParams();
params.put("username", mUsername);
params.put("password", mPassword);
mLoginTask.execute(params);
} else {
updateProgress(getString(R.string.login_status_null_username_or_password));
}
}
}
private void onLoginBegin() {
disableLogin();
TaskFeedback.getInstance(TaskFeedback.DIALOG_MODE,
LoginActivity.this).start(
getString(R.string.login_status_logging_in));
}
private void onLoginSuccess() {
TaskFeedback.getInstance(TaskFeedback.DIALOG_MODE,
LoginActivity.this).success("");
updateProgress("");
mUsernameEdit.setText("");
mPasswordEdit.setText("");
Log.d(TAG, "Storing credentials.");
TwitterApplication.mApi.setCredentials(mUsername, mPassword);
Intent intent = getIntent().getParcelableExtra(Intent.EXTRA_INTENT);
String action = intent.getAction();
if (intent.getAction() == null || !Intent.ACTION_SEND.equals(action)) {
// We only want to reuse the intent if it was photo send.
// Or else default to the main activity.
intent = new Intent(this, TwitterActivity.class);
}
//发送消息给widget
Intent reflogin = new Intent(this.getBaseContext(), FanfouWidget.class);
reflogin.setAction("android.appwidget.action.APPWIDGET_UPDATE");
PendingIntent l = PendingIntent.getBroadcast(this.getBaseContext(), 0, reflogin,
PendingIntent.FLAG_UPDATE_CURRENT);
try {
l.send();
} catch (CanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startActivity(intent);
finish();
}
private void onLoginFailure(String reason) {
TaskFeedback.getInstance(TaskFeedback.DIALOG_MODE,
LoginActivity.this).failed(reason);
enableLogin();
}
private class LoginTask extends GenericTask {
private String msg = getString(R.string.login_status_failure);
public String getMsg(){
return msg;
}
@Override
protected TaskResult _doInBackground(TaskParams...params) {
TaskParams param = params[0];
publishProgress(getString(R.string.login_status_logging_in) + "...");
try {
String username = param.getString("username");
String password = param.getString("password");
user= TwitterApplication.mApi.login(username, password);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
//TODO:确切的应该从HttpException中返回的消息中获取错误信息
//Throwable cause = e.getCause(); // Maybe null
// if (cause instanceof HttpAuthException) {
if (e instanceof HttpAuthException) {
// Invalid userName/password
msg = getString(R.string.login_status_invalid_username_or_password);
} else {
msg = getString(R.string.login_status_network_or_connection_error);
}
publishProgress(msg);
return TaskResult.FAILED;
}
SharedPreferences.Editor editor = mPreferences.edit();
editor.putString(Preferences.USERNAME_KEY, mUsername);
editor.putString(Preferences.PASSWORD_KEY,
encryptPassword(mPassword));
// add 存储当前用户的id
editor.putString(Preferences.CURRENT_USER_ID, user.getId());
editor.commit();
return TaskResult.OK;
}
}
private View.OnKeyListener enterKeyHandler = new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER
|| keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
if (event.getAction() == KeyEvent.ACTION_UP) {
doLogin();
}
return true;
}
return false;
}
};
public static String encryptPassword(String password) {
//return Base64.encodeToString(password.getBytes(), Base64.DEFAULT);
return password;
}
public static String decryptPassword(String password) {
//return new String(Base64.decode(password, Base64.DEFAULT));
return password;
}
} | Java |
package com.ch_linghu.fanfoudroid.task;
import java.util.Observable;
import java.util.Observer;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
public abstract class GenericTask extends
AsyncTask<TaskParams, Object, TaskResult> implements Observer {
private static final String TAG = "TaskManager";
private TaskListener mListener = null;
private Feedback mFeedback = null;
private boolean isCancelable = true;
abstract protected TaskResult _doInBackground(TaskParams... params);
public void setListener(TaskListener taskListener) {
mListener = taskListener;
}
public TaskListener getListener() {
return mListener;
}
public void doPublishProgress(Object... values) {
super.publishProgress(values);
}
@Override
protected void onCancelled() {
super.onCancelled();
if (mListener != null) {
mListener.onCancelled(this);
}
Log.d(TAG, mListener.getName() + " has been Cancelled.");
Toast.makeText(TwitterApplication.mContext, mListener.getName()
+ " has been cancelled", Toast.LENGTH_SHORT);
}
@Override
protected void onPostExecute(TaskResult result) {
super.onPostExecute(result);
if (mListener != null) {
mListener.onPostExecute(this, result);
}
if (mFeedback != null) {
mFeedback.success("");
}
/*
Toast.makeText(TwitterApplication.mContext, mListener.getName()
+ " completed", Toast.LENGTH_SHORT);
*/
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if (mListener != null) {
mListener.onPreExecute(this);
}
if (mFeedback != null) {
mFeedback.start("");
}
}
@Override
protected void onProgressUpdate(Object... values) {
super.onProgressUpdate(values);
if (mListener != null) {
if (values != null && values.length > 0) {
mListener.onProgressUpdate(this, values[0]);
}
}
if (mFeedback != null) {
mFeedback.update(values[0]);
}
}
@Override
protected TaskResult doInBackground(TaskParams... params) {
TaskResult result = _doInBackground(params);
if (mFeedback != null) {
mFeedback.update(99);
}
return result;
}
public void update(Observable o, Object arg) {
if (TaskManager.CANCEL_ALL == (Integer) arg && isCancelable) {
if (getStatus() == GenericTask.Status.RUNNING) {
cancel(true);
}
}
}
public void setCancelable(boolean flag) {
isCancelable = flag;
}
public void setFeedback(Feedback feedback) {
mFeedback = feedback;
}
}
| Java |
package com.ch_linghu.fanfoudroid.task;
import java.util.HashMap;
import org.json.JSONException;
import com.ch_linghu.fanfoudroid.http.HttpException;
/**
* 暂未使用,待观察是否今后需要此类
* @author lds
*
*/
public class TaskParams {
private HashMap<String, Object> params = null;
public TaskParams() {
params = new HashMap<String, Object>();
}
public TaskParams(String key, Object value) {
this();
put(key, value);
}
public void put(String key, Object value) {
params.put(key, value);
}
public Object get(String key) {
return params.get(key);
}
/**
* Get the boolean value associated with a key.
*
* @param key A key string.
* @return The truth.
* @throws HttpException
* if the value is not a Boolean or the String "true" or "false".
*/
public boolean getBoolean(String key) throws HttpException {
Object object = get(key);
if (object.equals(Boolean.FALSE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("true"))) {
return true;
}
throw new HttpException(key + " is not a Boolean.");
}
/**
* Get the double value associated with a key.
* @param key A key string.
* @return The numeric value.
* @throws HttpException if the key is not found or
* if the value is not a Number object and cannot be converted to a number.
*/
public double getDouble(String key) throws HttpException {
Object object = get(key);
try {
return object instanceof Number ?
((Number)object).doubleValue() :
Double.parseDouble((String)object);
} catch (Exception e) {
throw new HttpException(key + " is not a number.");
}
}
/**
* Get the int value associated with a key.
*
* @param key A key string.
* @return The integer value.
* @throws HttpException if the key is not found or if the value cannot
* be converted to an integer.
*/
public int getInt(String key) throws HttpException {
Object object = get(key);
try {
return object instanceof Number ?
((Number)object).intValue() :
Integer.parseInt((String)object);
} catch (Exception e) {
throw new HttpException(key + " is not an int.");
}
}
/**
* Get the string associated with a key.
*
* @param key A key string.
* @return A string which is the value.
* @throws JSONException if the key is not found.
*/
public String getString(String key) throws HttpException {
Object object = get(key);
return object == null ? null : object.toString();
}
/**
* Determine if the JSONObject contains a specific key.
* @param key A key string.
* @return true if the key exists in the JSONObject.
*/
public boolean has(String key) {
return this.params.containsKey(key);
}
}
| Java |
package com.ch_linghu.fanfoudroid.task;
import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.ui.base.WithHeaderActivity;
public abstract class TaskFeedback {
private static TaskFeedback _instance = null;
public static final int DIALOG_MODE = 0x01;
public static final int REFRESH_MODE = 0x02;
public static final int PROGRESS_MODE = 0x03;
public static TaskFeedback getInstance(int type, Context context) {
switch (type) {
case DIALOG_MODE:
_instance = DialogFeedback.getInstance();
break;
case REFRESH_MODE:
_instance = RefreshAnimationFeedback.getInstance();
break;
case PROGRESS_MODE:
_instance = ProgressBarFeedback.getInstance();
}
_instance.setContext(context);
return _instance;
}
protected Context _context;
protected void setContext(Context context) {
_context = context;
}
public Context getContent() {
return _context;
}
// default do nothing
public void start(String prompt) {};
public void cancel() {};
public void success(String prompt) {};
public void success() { success(""); };
public void failed(String prompt) {};
public void showProgress(int progress) {};
}
/**
*
*/
class DialogFeedback extends TaskFeedback {
private static DialogFeedback _instance = null;
public static DialogFeedback getInstance() {
if (_instance == null) {
_instance = new DialogFeedback();
}
return _instance;
}
private ProgressDialog _dialog = null;
@Override
public void cancel() {
if (_dialog != null) {
_dialog.dismiss();
}
}
@Override
public void failed(String prompt) {
if (_dialog != null) {
_dialog.dismiss();
}
Toast toast = Toast.makeText(_context, prompt, Toast.LENGTH_LONG);
toast.show();
}
@Override
public void start(String prompt) {
_dialog = ProgressDialog.show(_context, "", prompt, true);
_dialog.setCancelable(true);
}
@Override
public void success(String prompt) {
if (_dialog != null) {
_dialog.dismiss();
}
}
}
/**
*
*/
class RefreshAnimationFeedback extends TaskFeedback {
private static RefreshAnimationFeedback _instance = null;
public static RefreshAnimationFeedback getInstance() {
if (_instance == null) {
_instance = new RefreshAnimationFeedback();
}
return _instance;
}
private WithHeaderActivity _activity;
@Override
protected void setContext(Context context) {
super.setContext(context);
_activity = (WithHeaderActivity) context;
}
@Override
public void cancel() {
_activity.setRefreshAnimation(false);
}
@Override
public void failed(String prompt) {
_activity.setRefreshAnimation(false);
Toast toast = Toast.makeText(_context, prompt, Toast.LENGTH_LONG);
toast.show();
}
@Override
public void start(String prompt) {
_activity.setRefreshAnimation(true);
}
@Override
public void success(String prompt) {
_activity.setRefreshAnimation(false);
}
}
/**
*
*/
class ProgressBarFeedback extends TaskFeedback {
private static ProgressBarFeedback _instance = null;
public static ProgressBarFeedback getInstance() {
if (_instance == null) {
_instance = new ProgressBarFeedback();
}
return _instance;
}
private WithHeaderActivity _activity;
@Override
protected void setContext(Context context) {
super.setContext(context);
_activity = (WithHeaderActivity) context;
}
@Override
public void cancel() {
_activity.setGlobalProgress(0);
}
@Override
public void failed(String prompt) {
cancel();
Toast toast = Toast.makeText(_context, prompt, Toast.LENGTH_LONG);
toast.show();
}
@Override
public void start(String prompt) {
_activity.setGlobalProgress(10);
}
@Override
public void success(String prompt) {
Log.d("LDS", "ON SUCCESS");
_activity.setGlobalProgress(0);
}
@Override
public void showProgress(int progress) {
_activity.setGlobalProgress(progress);
}
// mProgress.setIndeterminate(true);
}
| Java |
package com.ch_linghu.fanfoudroid.task;
public enum TaskResult {
OK,
FAILED,
CANCELLED,
NOT_FOLLOWED_ERROR,
IO_ERROR,
AUTH_ERROR
} | Java |
package com.ch_linghu.fanfoudroid.task;
public interface TaskListener {
String getName();
void onPreExecute(GenericTask task);
void onPostExecute(GenericTask task, TaskResult result);
void onProgressUpdate(GenericTask task, Object param);
void onCancelled(GenericTask task);
}
| Java |
package com.ch_linghu.fanfoudroid.task;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
public class TweetCommonTask {
public static class DeleteTask extends GenericTask{
public static final String TAG="DeleteTask";
private BaseActivity activity;
public DeleteTask(BaseActivity activity){
this.activity = activity;
}
@Override
protected TaskResult _doInBackground(TaskParams... params) {
TaskParams param = params[0];
try {
String id = param.getString("id");
com.ch_linghu.fanfoudroid.fanfou.Status status = null;
status = activity.getApi().destroyStatus(id);
// 对所有相关表的对应消息都进行删除(如果存在的话)
activity.getDb().deleteTweet(status.getId(), "", -1);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
public static class FavoriteTask extends GenericTask{
private static final String TAG = "FavoriteTask";
private BaseActivity activity;
public static final String TYPE_ADD = "add";
public static final String TYPE_DEL = "del";
private String type;
public String getType(){
return type;
}
public FavoriteTask(BaseActivity activity){
this.activity = activity;
}
@Override
protected TaskResult _doInBackground(TaskParams...params){
TaskParams param = params[0];
try {
String action = param.getString("action");
String id = param.getString("id");
com.ch_linghu.fanfoudroid.fanfou.Status status = null;
if (action.equals(TYPE_ADD)) {
status = activity.getApi().createFavorite(id);
activity.getDb().setFavorited(id, "true");
type = TYPE_ADD;
} else {
status = activity.getApi().destroyFavorite(id);
activity.getDb().setFavorited(id, "false");
type = TYPE_DEL;
}
Tweet tweet = Tweet.create(status);
// if (!Utils.isEmpty(tweet.profileImageUrl)) {
// // Fetch image to cache.
// try {
// activity.getImageManager().put(tweet.profileImageUrl);
// } catch (IOException e) {
// Log.e(TAG, e.getMessage(), e);
// }
// }
if(action.equals(TYPE_DEL)){
activity.getDb().deleteTweet(tweet.id, TwitterApplication.getMyselfId(), StatusTable.TYPE_FAVORITE);
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
// public static class UserTask extends GenericTask{
//
// @Override
// protected TaskResult _doInBackground(TaskParams... params) {
// // TODO Auto-generated method stub
// return null;
// }
//
// }
}
| Java |
package com.ch_linghu.fanfoudroid.task;
public abstract class TaskAdapter implements TaskListener {
public abstract String getName();
public void onPreExecute(GenericTask task) {};
public void onPostExecute(GenericTask task, TaskResult result) {};
public void onProgressUpdate(GenericTask task, Object param) {};
public void onCancelled(GenericTask task) {};
}
| Java |
package com.ch_linghu.fanfoudroid.task;
import java.util.Observable;
import java.util.Observer;
import android.util.Log;
public class TaskManager extends Observable {
private static final String TAG = "TaskManager";
public static final Integer CANCEL_ALL = 1;
public void cancelAll() {
Log.d(TAG, "All task Cancelled.");
setChanged();
notifyObservers(CANCEL_ALL);
}
public void addTask(Observer task) {
super.addObserver(task);
}
} | Java |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity;
public class MentionActivity extends TwitterCursorBaseActivity {
private static final String TAG = "MentionActivity";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.REPLIES";
static final int DIALOG_WRITE_ID = 0;
public static Intent createIntent(Context context) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
return intent;
}
public static Intent createNewTaskIntent(Context context) {
Intent intent = createIntent(context);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState)){
mNavbar.setHeaderTitle("@提到我的");
return true;
}else{
return false;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
@Override
protected Cursor fetchMessages() {
return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_MENTION);
}
@Override
protected void markAllRead() {
getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_MENTION);
}
@Override
protected String getActivityTitle() {
return getResources().getString(R.string.page_title_mentions);
}
// for Retrievable interface
@Override
public String fetchMaxId() {
return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_MENTION);
}
@Override
public List<Status> getMessageSinceId(String maxId) throws HttpException {
if (maxId != null){
return getApi().getMentions(new Paging(maxId));
}else{
return getApi().getMentions();
}
}
@Override
public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) {
return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_MENTION, isUnread);
}
@Override
public String fetchMinId() {
return getDb().fetchMinTweetId(getUserId(), StatusTable.TYPE_MENTION);
}
@Override
public List<Status> getMoreMessageFromId(String minId)
throws HttpException {
Paging paging = new Paging(1, 20);
paging.setMaxId(minId);
return getApi().getMentions(paging);
}
@Override
public int getDatabaseType() {
return StatusTable.TYPE_MENTION;
}
@Override
public String getUserId() {
return TwitterApplication.getMyselfId();
}
} | Java |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.task.TweetCommonTask;
import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity;
public class TwitterActivity extends TwitterCursorBaseActivity {
private static final String TAG = "TwitterActivity";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.TWEETS";
protected GenericTask mDeleteTask;
private TaskListener mDeleteTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "DeleteTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
onDeleteSuccess();
} else if (result == TaskResult.IO_ERROR) {
onDeleteFailure();
}
}
};
static final int DIALOG_WRITE_ID = 0;
public static Intent createIntent(Context context) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
return intent;
}
public static Intent createNewTaskIntent(Context context) {
Intent intent = createIntent(context);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState)) {
mNavbar.setHeaderTitle("饭否fanfou.com");
//仅在这个页面进行schedule的处理
manageUpdateChecks();
return true;
} else {
return false;
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (mDeleteTask != null
&& mDeleteTask.getStatus() == GenericTask.Status.RUNNING) {
mDeleteTask.cancel(true);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mDeleteTask != null
&& mDeleteTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
// Menu.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
private int CONTEXT_DELETE_ID = getLastContextMenuId() + 1;
@Override
protected int getLastContextMenuId() {
return CONTEXT_DELETE_ID;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
Tweet tweet = getContextItemTweet(info.position);
if (null != tweet) {// 当按钮为 刷新/更多的时候为空
if (tweet.userId.equals(TwitterApplication.getMyselfId())) {
menu.add(0, CONTEXT_DELETE_ID, 0, R.string.cmenu_delete);
}
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
Tweet tweet = getContextItemTweet(info.position);
if (tweet == null) {
Log.w(TAG, "Selected item not available.");
return super.onContextItemSelected(item);
}
if (item.getItemId() == CONTEXT_DELETE_ID) {
doDelete(tweet.id);
return true;
} else {
return super.onContextItemSelected(item);
}
}
@SuppressWarnings("deprecation")
@Override
protected Cursor fetchMessages() {
return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_HOME);
}
@Override
protected String getActivityTitle() {
return getResources().getString(R.string.page_title_home);
}
@Override
protected void markAllRead() {
getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_HOME);
}
// hasRetrieveListTask interface
@Override
public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) {
// 获取消息的时候,将status里获取的user也存储到数据库
// ::MARK::
for (Tweet t : tweets) {
getDb().createWeiboUserInfo(t.user);
}
return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_HOME,
isUnread);
}
@Override
public String fetchMaxId() {
return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_HOME);
}
@Override
public List<Status> getMessageSinceId(String maxId) throws HttpException {
if (maxId != null) {
return getApi().getFriendsTimeline(new Paging(maxId));
} else {
return getApi().getFriendsTimeline();
}
}
public void onDeleteFailure() {
Log.e(TAG, "Delete failed");
}
public void onDeleteSuccess() {
mTweetAdapter.refresh();
}
private void doDelete(String id) {
if (mDeleteTask != null
&& mDeleteTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mDeleteTask = new TweetCommonTask.DeleteTask(this);
mDeleteTask.setListener(mDeleteTaskListener);
TaskParams params = new TaskParams();
params.put("id", id);
mDeleteTask.execute(params);
}
}
@Override
public String fetchMinId() {
return getDb().fetchMinTweetId(getUserId(), StatusTable.TYPE_HOME);
}
@Override
public List<Status> getMoreMessageFromId(String minId) throws HttpException {
Paging paging = new Paging(1, 20);
paging.setMaxId(minId);
return getApi().getFriendsTimeline(paging);
}
@Override
public int getDatabaseType() {
return StatusTable.TYPE_HOME;
}
@Override
public String getUserId() {
return TwitterApplication.getMyselfId();
}
} | Java |
package com.ch_linghu.fanfoudroid.data2;
import java.util.Date;
public class Status {
private Date created_at;
private String id;
private String text;
private String source;
private boolean truncated;
private String in_reply_to_status_id;
private String in_reply_to_user_id;
private boolean favorited;
private String in_reply_to_screen_name;
private Photo photo_url;
private User user;
private boolean isUnRead = false;
private int type = -1;
private String owner_id;
public Status() {}
public Date getCreatedAt() {
return created_at;
}
public void setCreatedAt(Date created_at) {
this.created_at = created_at;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public boolean isTruncated() {
return truncated;
}
public void setTruncated(boolean truncated) {
this.truncated = truncated;
}
public String getInReplyToStatusId() {
return in_reply_to_status_id;
}
public void setInReplyToStatusId(String in_reply_to_status_id) {
this.in_reply_to_status_id = in_reply_to_status_id;
}
public String getInReplyToUserId() {
return in_reply_to_user_id;
}
public void setInReplyToUserId(String in_reply_to_user_id) {
this.in_reply_to_user_id = in_reply_to_user_id;
}
public boolean isFavorited() {
return favorited;
}
public void setFavorited(boolean favorited) {
this.favorited = favorited;
}
public String getInReplyToScreenName() {
return in_reply_to_screen_name;
}
public void setInReplyToScreenName(String in_reply_to_screen_name) {
this.in_reply_to_screen_name = in_reply_to_screen_name;
}
public Photo getPhotoUrl() {
return photo_url;
}
public void setPhotoUrl(Photo photo_url) {
this.photo_url = photo_url;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public boolean isUnRead() {
return isUnRead;
}
public void setUnRead(boolean isUnRead) {
this.isUnRead = isUnRead;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getOwnerId() {
return owner_id;
}
public void setOwnerId(String owner_id) {
this.owner_id = owner_id;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Status other = (Status) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (owner_id == null) {
if (other.owner_id != null)
return false;
} else if (!owner_id.equals(other.owner_id))
return false;
if (type != other.type)
return false;
if (user == null) {
if (other.user != null)
return false;
} else if (!user.equals(other.user))
return false;
return true;
}
@Override
public String toString() {
return "Status [created_at=" + created_at + ", id=" + id + ", text="
+ text + ", source=" + source + ", truncated=" + truncated
+ ", in_reply_to_status_id=" + in_reply_to_status_id
+ ", in_reply_to_user_id=" + in_reply_to_user_id
+ ", favorited=" + favorited + ", in_reply_to_screen_name="
+ in_reply_to_screen_name + ", photo_url=" + photo_url
+ ", user=" + user + "]";
}
}
| Java |
package com.ch_linghu.fanfoudroid.data2;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class DataUtils {
static SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
public static Date parseDate(String str, String format) throws ParseException {
if (str == null || "".equals(str)) {
return null;
}
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
return sdf.parse(str);
}
}
| Java |
package com.ch_linghu.fanfoudroid.data2;
import java.util.Date;
public class User {
private String id;
private String name;
private String screen_name;
private String location;
private String desription;
private String profile_image_url;
private String url;
private boolean isProtected;
private int friends_count;
private int followers_count;
private int favourites_count;
private Date created_at;
private boolean following;
private boolean notifications;
private int utc_offset;
private Status status; // null
public User() {}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getScreenName() {
return screen_name;
}
public void setScreenName(String screen_name) {
this.screen_name = screen_name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDesription() {
return desription;
}
public void setDesription(String desription) {
this.desription = desription;
}
public String getProfileImageUrl() {
return profile_image_url;
}
public void setProfileImageUrl(String profile_image_url) {
this.profile_image_url = profile_image_url;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public boolean isProtected() {
return isProtected;
}
public void setProtected(boolean isProtected) {
this.isProtected = isProtected;
}
public int getFriendsCount() {
return friends_count;
}
public void setFriendsCount(int friends_count) {
this.friends_count = friends_count;
}
public int getFollowersCount() {
return followers_count;
}
public void setFollowersCount(int followers_count) {
this.followers_count = followers_count;
}
public int getFavouritesCount() {
return favourites_count;
}
public void setFavouritesCount(int favourites_count) {
this.favourites_count = favourites_count;
}
public Date getCreatedAt() {
return created_at;
}
public void setCreatedAt(Date created_at) {
this.created_at = created_at;
}
public boolean isFollowing() {
return following;
}
public void setFollowing(boolean following) {
this.following = following;
}
public boolean isNotifications() {
return notifications;
}
public void setNotifications(boolean notifications) {
this.notifications = notifications;
}
public int getUtcOffset() {
return utc_offset;
}
public void setUtcOffset(int utc_offset) {
this.utc_offset = utc_offset;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", screen_name="
+ screen_name + ", location=" + location + ", desription="
+ desription + ", profile_image_url=" + profile_image_url
+ ", url=" + url + ", isProtected=" + isProtected
+ ", friends_count=" + friends_count + ", followers_count="
+ followers_count + ", favourites_count=" + favourites_count
+ ", created_at=" + created_at + ", following=" + following
+ ", notifications=" + notifications + ", utc_offset="
+ utc_offset + ", status=" + status + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
| Java |
package com.ch_linghu.fanfoudroid.data2;
public class Photo {
private String thumburl;
private String imageurl;
private String largeurl;
public Photo() {}
public String getThumburl() {
return thumburl;
}
public void setThumburl(String thumburl) {
this.thumburl = thumburl;
}
public String getImageurl() {
return imageurl;
}
public void setImageurl(String imageurl) {
this.imageurl = imageurl;
}
public String getLargeurl() {
return largeurl;
}
public void setLargeurl(String largeurl) {
this.largeurl = largeurl;
}
@Override
public String toString() {
return "Photo [thumburl=" + thumburl + ", imageurl=" + imageurl
+ ", largeurl=" + largeurl + "]";
}
}
| Java |
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.fanfou.User;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.HttpRefusedException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.Refreshable;
import com.ch_linghu.fanfoudroid.ui.base.TwitterListBaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.MyListView;
import com.ch_linghu.fanfoudroid.ui.module.TweetArrayAdapter;
public class UserTimelineActivity extends TwitterListBaseActivity implements
MyListView.OnNeedMoreListener, Refreshable {
private static final String TAG = UserTimelineActivity.class
.getSimpleName();
private Feedback mFeedback;
private static final String EXTRA_USERID = "userID";
private static final String EXTRA_NAME_SHOW = "showName";
private static final String SIS_RUNNING_KEY = "running";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.USERTIMELINE";
public static Intent createIntent(String userID, String showName) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.putExtra(EXTRA_USERID, userID);
intent.putExtra(EXTRA_NAME_SHOW, showName);
return intent;
}
// State.
private User mUser;
private String mUserID;
private String mShowName;
private ArrayList<Tweet> mTweets;
private int mNextPage = 1;
// Views.
private TextView headerView;
private TextView footerView;
private MyListView mTweetList;
// 记录服务器拒绝访问的信息
private String msg;
private static final int LOADINGFLAG = 1;
private static final int SUCCESSFLAG = 2;
private static final int NETWORKERRORFLAG = 3;
private static final int AUTHERRORFLAG = 4;
private TweetArrayAdapter mAdapter;
// Tasks.
private GenericTask mRetrieveTask;
private GenericTask mLoadMoreTask;
private TaskListener mRetrieveTaskListener = new TaskAdapter() {
@Override
public void onPreExecute(GenericTask task) {
onRetrieveBegin();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
mFeedback.failed("登录失败, 请重新登录.");
updateHeader(AUTHERRORFLAG);
return;
} else if (result == TaskResult.OK) {
updateHeader(SUCCESSFLAG);
updateFooter(SUCCESSFLAG);
draw();
goTop();
} else if (result == TaskResult.IO_ERROR) {
mFeedback.failed("更新失败.");
updateHeader(NETWORKERRORFLAG);
}
mFeedback.success("");
}
@Override
public String getName() {
return "UserTimelineRetrieve";
}
};
private TaskListener mLoadMoreTaskListener = new TaskAdapter() {
@Override
public void onPreExecute(GenericTask task) {
onLoadMoreBegin();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
mFeedback.success("");
updateFooter(SUCCESSFLAG);
draw();
}
}
@Override
public String getName() {
return "UserTimelineLoadMoreTask";
}
};
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "_onCreate()...");
if (super._onCreate(savedInstanceState)) {
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
Intent intent = getIntent();
// get user id
mUserID = intent.getStringExtra(EXTRA_USERID);
// show username in title
mShowName = intent.getStringExtra(EXTRA_NAME_SHOW);
// Set header title
mNavbar.setHeaderTitle("@" + mShowName);
boolean wasRunning = isTrue(savedInstanceState, SIS_RUNNING_KEY);
// 此处要求mTweets不为空,最好确保profile页面消息为0时不能进入这个页面
if (!mTweets.isEmpty() && !wasRunning) {
updateHeader(SUCCESSFLAG);
draw();
} else {
doRetrieve();
}
return true;
} else {
return false;
}
}
@Override
protected void onResume() {
super.onResume();
checkIsLogedIn();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
mRetrieveTask.cancel(true);
}
if (mLoadMoreTask != null
&& mLoadMoreTask.getStatus() == GenericTask.Status.RUNNING) {
mLoadMoreTask.cancel(true);
}
super.onDestroy();
}
@Override
protected void draw() {
mAdapter.refresh(mTweets);
}
public void goTop() {
Log.d(TAG, "goTop.");
mTweetList.setSelection(1);
}
public void doRetrieve() {
Log.d(TAG, "Attempting retrieve.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mRetrieveTask = new UserTimelineRetrieveTask();
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.execute();
}
}
private void doLoadMore() {
Log.d(TAG, "Attempting load more.");
if (mLoadMoreTask != null
&& mLoadMoreTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mLoadMoreTask = new UserTimelineLoadMoreTask();
mLoadMoreTask.setListener(mLoadMoreTaskListener);
mLoadMoreTask.execute();
}
}
private void onRetrieveBegin() {
mFeedback.start("");
// 更新查询状态显示
updateHeader(LOADINGFLAG);
updateFooter(LOADINGFLAG);
}
private void onLoadMoreBegin() {
mFeedback.start("");
}
private class UserTimelineRetrieveTask extends GenericTask {
ArrayList<Tweet> mTweets = new ArrayList<Tweet>();
@Override
protected TaskResult _doInBackground(TaskParams... params) {
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
try {
statusList = getApi().getUserTimeline(mUserID,
new Paging(mNextPage));
mUser = getApi().showUser(mUserID);
mFeedback.update(60);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
Throwable cause = e.getCause();
if (cause instanceof HttpRefusedException) {
// AUTH ERROR
msg = ((HttpRefusedException) cause).getError()
.getMessage();
return TaskResult.AUTH_ERROR;
} else {
return TaskResult.IO_ERROR;
}
}
mFeedback.update(100 - (int)Math.floor(statusList.size()*2)); // 60~100
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Tweet tweet;
tweet = Tweet.create(status);
mTweets.add(tweet);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
addTweets(mTweets);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
return TaskResult.OK;
}
}
private class UserTimelineLoadMoreTask extends GenericTask {
ArrayList<Tweet> mTweets = new ArrayList<Tweet>();
@Override
protected TaskResult _doInBackground(TaskParams... params) {
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
try {
statusList = getApi().getUserTimeline(mUserID,
new Paging(mNextPage));
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
Throwable cause = e.getCause();
if (cause instanceof HttpRefusedException) {
// AUTH ERROR
msg = ((HttpRefusedException) cause).getError()
.getMessage();
return TaskResult.AUTH_ERROR;
} else {
return TaskResult.IO_ERROR;
}
}
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Tweet tweet;
tweet = Tweet.create(status);
mTweets.add(tweet);
}
if (isCancelled()) {
return TaskResult.CANCELLED;
}
addTweets(mTweets);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
return TaskResult.OK;
}
}
@Override
public void needMore() {
if (!isLastPage()) {
doLoadMore();
}
}
public boolean isLastPage() {
return mNextPage == -1;
}
private synchronized void addTweets(ArrayList<Tweet> tweets) {
// do more时没有更多时
if (tweets.size() == 0) {
mNextPage = -1;
return;
}
mTweets.addAll(tweets);
++mNextPage;
}
@Override
protected String getActivityTitle() {
return "@" + mShowName;
}
@Override
protected Tweet getContextItemTweet(int position) {
if (position >= 1 && position <= mAdapter.getCount()) {
return (Tweet) mAdapter.getItem(position - 1);
} else {
return null;
}
}
@Override
protected int getLayoutId() {
return R.layout.user_timeline;
}
@Override
protected com.ch_linghu.fanfoudroid.ui.module.TweetAdapter getTweetAdapter() {
return mAdapter;
}
@Override
protected ListView getTweetList() {
return mTweetList;
}
@Override
protected void setupState() {
mTweets = new ArrayList<Tweet>();
mAdapter = new TweetArrayAdapter(this);
mTweetList = (MyListView) findViewById(R.id.tweet_list);
// Add Header to ListView
headerView = (TextView) TextView.inflate(this,
R.layout.user_timeline_header, null);
mTweetList.addHeaderView(headerView);
// Add Footer to ListView
footerView = (TextView) TextView.inflate(this,
R.layout.user_timeline_footer, null);
mTweetList.addFooterView(footerView);
mTweetList.setAdapter(mAdapter);
mTweetList.setOnNeedMoreListener(this);
}
@Override
protected void updateTweet(Tweet tweet) {
// 该方法作用?
}
@Override
protected boolean useBasicMenu() {
return true;
}
private void updateHeader(int flag) {
if (flag == LOADINGFLAG) {
// 重新刷新页面时从第一页开始获取数据 --- phoenix
mNextPage = 1;
mTweets.clear();
mAdapter.refresh(mTweets);
headerView.setText(getResources()
.getString(R.string.search_loading));
}
if (flag == SUCCESSFLAG) {
headerView.setText(getResources().getString(
R.string.user_query_status_success));
}
if (flag == NETWORKERRORFLAG) {
headerView.setText(getResources().getString(
R.string.login_status_network_or_connection_error));
}
if (flag == AUTHERRORFLAG) {
headerView.setText(msg);
}
}
private void updateFooter(int flag) {
if (flag == LOADINGFLAG) {
footerView.setText("该用户总共?条消息");
}
if (flag == SUCCESSFLAG) {
footerView.setText("该用户总共" + mUser.getStatusesCount() + "条消息,当前显示"
+ mTweets.size() + "条。");
}
}
} | Java |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.data.Dm;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.fanfou.DirectMessage;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.ui.module.TweetEdit;
//FIXME: 将WriteDmActivity和WriteActivity进行整合。
/**
* 撰写私信界面
* @author lds
*
*/
public class WriteDmActivity extends BaseActivity {
public static final String NEW_TWEET_ACTION = "com.ch_linghu.fanfoudroid.NEW";
public static final String EXTRA_TEXT = "text";
public static final String REPLY_ID = "reply_id";
private static final String TAG = "WriteActivity";
private static final String SIS_RUNNING_KEY = "running";
private static final String PREFS_NAME = "com.ch_linghu.fanfoudroid";
// View
private TweetEdit mTweetEdit;
private EditText mTweetEditText;
private TextView mProgressText;
private Button mSendButton;
//private AutoCompleteTextView mToEdit;
private TextView mToEdit;
private NavBar mNavbar;
// Task
private GenericTask mSendTask;
private TaskListener mSendTaskListener = new TaskAdapter() {
@Override
public void onPreExecute(GenericTask task) {
disableEntry();
updateProgress(getString(R.string.page_status_updating));
}
@Override
public void onPostExecute(GenericTask task,
TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
mToEdit.setText("");
mTweetEdit.setText("");
updateProgress("");
enableEntry();
// 发送成功就直接关闭界面
finish();
// 关闭软键盘
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mTweetEdit.getEditText().getWindowToken(), 0);
} else if (result == TaskResult.NOT_FOLLOWED_ERROR) {
updateProgress(getString(R.string.direct_meesage_status_the_person_not_following_you));
enableEntry();
} else if (result == TaskResult.IO_ERROR) {
// TODO: 什么情况下会抛出IO_ERROR?需要给用户更为具体的失败原因
updateProgress(getString(R.string.page_status_unable_to_update));
enableEntry();
}
}
@Override
public String getName() {
return "DMSend";
}
};
private FriendsAdapter mFriendsAdapter; // Adapter for To: recipient
// autocomplete.
private static final String EXTRA_USER = "user";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.DMSW";
public static Intent createIntent(String user) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (!TextUtils.isEmpty(user)) {
intent.putExtra(EXTRA_USER, user);
}
return intent;
}
// sub menu
// protected void createInsertPhotoDialog() {
//
// final CharSequence[] items = {
// getString(R.string.write_label_take_a_picture),
// getString(R.string.write_label_choose_a_picture) };
//
// AlertDialog.Builder builder = new AlertDialog.Builder(this);
// builder.setTitle(getString(R.string.write_label_insert_picture));
// builder.setItems(items, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int item) {
// // Toast.makeText(getApplicationContext(), items[item],
// // Toast.LENGTH_SHORT).show();
// switch (item) {
// case 0:
// openImageCaptureMenu();
// break;
// case 1:
// openPhotoLibraryMenu();
// }
// }
// });
// AlertDialog alert = builder.create();
// alert.show();
// }
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)){
// init View
setContentView(R.layout.write_dm);
mNavbar = new NavBar(NavBar.HEADER_STYLE_WRITE, this);
// Intent & Action & Extras
Intent intent = getIntent();
Bundle extras = intent.getExtras();
// View
mProgressText = (TextView) findViewById(R.id.progress_text);
mTweetEditText = (EditText) findViewById(R.id.tweet_edit);
TwitterDatabase db = getDb();
//FIXME: 暂时取消收件人自动完成功能
//FIXME: 可根据目前以后内容重新完成自动完成功能
//mToEdit = (AutoCompleteTextView) findViewById(R.id.to_edit);
//Cursor cursor = db.getFollowerUsernames("");
//// startManagingCursor(cursor);
//mFriendsAdapter = new FriendsAdapter(this, cursor);
//mToEdit.setAdapter(mFriendsAdapter);
mToEdit = (TextView) findViewById(R.id.to_edit);
// Update status
mTweetEdit = new TweetEdit(mTweetEditText,
(TextView) findViewById(R.id.chars_text));
mTweetEdit.setOnKeyListener(editEnterHandler);
mTweetEdit
.addTextChangedListener(new MyTextWatcher(WriteDmActivity.this));
// With extras
if (extras != null) {
String to = extras.getString(EXTRA_USER);
if (!TextUtils.isEmpty(to)) {
mToEdit.setText(to);
mTweetEdit.requestFocus();
}
}
View.OnClickListener sendListenner = new View.OnClickListener() {
public void onClick(View v) {
doSend();
}
};
mSendButton = (Button) findViewById(R.id.send_button);
mSendButton.setOnClickListener(sendListenner);
Button mTopSendButton = (Button) findViewById(R.id.top_send_btn);
mTopSendButton.setOnClickListener(sendListenner);
return true;
}else{
return false;
}
}
@Override
protected void onRestoreInstanceState(Bundle bundle) {
super.onRestoreInstanceState(bundle);
mTweetEdit.updateCharsRemain();
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause.");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart.");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume.");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart.");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop.");
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mSendTask != null
&& mSendTask.getStatus() == GenericTask.Status.RUNNING) {
// Doesn't really cancel execution (we let it continue running).
// See the SendTask code for more details.
mSendTask.cancel(true);
}
// Don't need to cancel FollowersTask (assuming it ends properly).
super.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mSendTask != null
&& mSendTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
public static Intent createNewTweetIntent(String text) {
Intent intent = new Intent(NEW_TWEET_ACTION);
intent.putExtra(EXTRA_TEXT, text);
return intent;
}
private class MyTextWatcher implements TextWatcher {
private WriteDmActivity _activity;
public MyTextWatcher(WriteDmActivity activity) {
_activity = activity;
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
if (s.length() == 0) {
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
}
private void doSend() {
if (mSendTask != null
&& mSendTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
String to = mToEdit.getText().toString();
String status = mTweetEdit.getText().toString();
if (!TextUtils.isEmpty(status) && !TextUtils.isEmpty(to)) {
mSendTask = new DmSendTask();
mSendTask.setListener(mSendTaskListener);
mSendTask.execute();
} else if (TextUtils.isEmpty(status)) {
updateProgress(getString(R.string.direct_meesage_status_texting_is_null));
} else if (TextUtils.isEmpty(to)) {
updateProgress(getString(R.string.direct_meesage_status_user_is_null));
}
}
}
private class DmSendTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
String user = mToEdit.getText().toString();
String text = mTweetEdit.getText().toString();
DirectMessage directMessage = getApi().sendDirectMessage(user,
text);
Dm dm = Dm.create(directMessage, true);
// if (!Utils.isEmpty(dm.profileImageUrl)) {
// // Fetch image to cache.
// try {
// getImageManager().put(dm.profileImageUrl);
// } catch (IOException e) {
// Log.e(TAG, e.getMessage(), e);
// }
// }
getDb().createDm(dm, false);
} catch (HttpException e) {
Log.d(TAG, e.getMessage());
// TODO: check is this is actually the case.
return TaskResult.NOT_FOLLOWED_ERROR;
}
return TaskResult.OK;
}
}
private static class FriendsAdapter extends CursorAdapter {
public FriendsAdapter(Context context, Cursor cursor) {
super(context, cursor);
mInflater = LayoutInflater.from(context);
mUserTextColumn = cursor
.getColumnIndexOrThrow(StatusTable.USER_SCREEN_NAME);
}
private LayoutInflater mInflater;
private int mUserTextColumn;
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = mInflater
.inflate(R.layout.dropdown_item, parent, false);
ViewHolder holder = new ViewHolder();
holder.userText = (TextView) view.findViewById(android.R.id.text1);
view.setTag(holder);
return view;
}
class ViewHolder {
public TextView userText;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = (ViewHolder) view.getTag();
holder.userText.setText(cursor.getString(mUserTextColumn));
}
@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
String filter = constraint == null ? "" : constraint.toString();
return TwitterApplication.mDb.getFollowerUsernames(filter);
}
@Override
public String convertToString(Cursor cursor) {
return cursor.getString(mUserTextColumn);
}
}
private void enableEntry() {
mTweetEdit.setEnabled(true);
mSendButton.setEnabled(true);
}
private void disableEntry() {
mTweetEdit.setEnabled(false);
mSendButton.setEnabled(false);
}
// UI helpers.
private void updateProgress(String progress) {
mProgressText.setText(progress);
}
private View.OnKeyListener editEnterHandler = new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER
|| keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
if (event.getAction() == KeyEvent.ACTION_UP) {
doSend();
}
return true;
}
return false;
}
};
} | Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing search API response
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class QueryResult extends WeiboResponse {
private long sinceId;
private long maxId;
private String refreshUrl;
private int resultsPerPage;
private int total = -1;
private String warning;
private double completedIn;
private int page;
private String query;
private List<Status> tweets;
private static final long serialVersionUID = -9059136565234613286L;
/*package*/ QueryResult(Response res, WeiboSupport weiboSupport) throws HttpException {
super(res);
// 饭否search API直接返回 "[{JSONObejet},{JSONObejet},{JSONObejet}]"的JSONArray
//System.out.println("TAG " + res.asString());
JSONArray array = res.asJSONArray();
try {
tweets = new ArrayList<Status>(array.length());
for (int i = 0; i < array.length(); i++) {
JSONObject tweet = array.getJSONObject(i);
tweets.add(new Status(tweet));
}
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + array.toString(), jsone);
}
}
/*package*/ QueryResult(Query query) throws HttpException {
super();
sinceId = query.getSinceId();
resultsPerPage = query.getRpp();
page = query.getPage();
tweets = new ArrayList<Status>(0);
}
public long getSinceId() {
return sinceId;
}
public long getMaxId() {
return maxId;
}
public String getRefreshUrl() {
return refreshUrl;
}
public int getResultsPerPage() {
return resultsPerPage;
}
/**
* returns the number of hits
* @return number of hits
* @deprecated The Weibo API doesn't return total anymore
* @see <a href="http://yusuke.homeip.net/jira/browse/TFJ-108">TRJ-108 deprecate QueryResult#getTotal()</a>
*/
@Deprecated
public int getTotal() {
return total;
}
public String getWarning() {
return warning;
}
public double getCompletedIn() {
return completedIn;
}
public int getPage() {
return page;
}
public String getQuery() {
return query;
}
public List<Status> getStatus() {
return tweets;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
QueryResult that = (QueryResult) o;
if (Double.compare(that.completedIn, completedIn) != 0) return false;
if (maxId != that.maxId) return false;
if (page != that.page) return false;
if (resultsPerPage != that.resultsPerPage) return false;
if (sinceId != that.sinceId) return false;
if (total != that.total) return false;
if (!query.equals(that.query)) return false;
if (refreshUrl != null ? !refreshUrl.equals(that.refreshUrl) : that.refreshUrl != null)
return false;
if (tweets != null ? !tweets.equals(that.tweets) : that.tweets != null)
return false;
if (warning != null ? !warning.equals(that.warning) : that.warning != null)
return false;
return true;
}
@Override
public int hashCode() {
int result;
long temp;
result = (int) (sinceId ^ (sinceId >>> 32));
result = 31 * result + (int) (maxId ^ (maxId >>> 32));
result = 31 * result + (refreshUrl != null ? refreshUrl.hashCode() : 0);
result = 31 * result + resultsPerPage;
result = 31 * result + total;
result = 31 * result + (warning != null ? warning.hashCode() : 0);
temp = completedIn != +0.0d ? Double.doubleToLongBits(completedIn) : 0L;
result = 31 * result + (int) (temp ^ (temp >>> 32));
result = 31 * result + page;
result = 31 * result + query.hashCode();
result = 31 * result + (tweets != null ? tweets.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "QueryResult{" +
"sinceId=" + sinceId +
", maxId=" + maxId +
", refreshUrl='" + refreshUrl + '\'' +
", resultsPerPage=" + resultsPerPage +
", total=" + total +
", warning='" + warning + '\'' +
", completedIn=" + completedIn +
", page=" + page +
", query='" + query + '\'' +
", tweets=" + tweets +
'}';
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.AccessControlException;
import java.util.Properties;
/**
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class Configuration {
private static Properties defaultProperty;
static {
init();
}
/*package*/ static void init() {
defaultProperty = new Properties();
//defaultProperty.setProperty("fanfoudroid.debug", "false");
defaultProperty.setProperty("fanfoudroid.debug", "true");
defaultProperty.setProperty("fanfoudroid.source", "fanfoudroid");
//defaultProperty.setProperty("fanfoudroid.clientVersion","");
defaultProperty.setProperty("fanfoudroid.clientURL", "http://sandin.tk/fanfoudroid.xml");
defaultProperty.setProperty("fanfoudroid.http.userAgent", "fanfoudroid 1.0");
//defaultProperty.setProperty("fanfoudroid.user","");
//defaultProperty.setProperty("fanfoudroid.password","");
defaultProperty.setProperty("fanfoudroid.http.useSSL", "false");
//defaultProperty.setProperty("fanfoudroid.http.proxyHost","");
defaultProperty.setProperty("fanfoudroid.http.proxyHost.fallback", "http.proxyHost");
//defaultProperty.setProperty("fanfoudroid.http.proxyUser","");
//defaultProperty.setProperty("fanfoudroid.http.proxyPassword","");
//defaultProperty.setProperty("fanfoudroid.http.proxyPort","");
defaultProperty.setProperty("fanfoudroid.http.proxyPort.fallback", "http.proxyPort");
defaultProperty.setProperty("fanfoudroid.http.connectionTimeout", "20000");
defaultProperty.setProperty("fanfoudroid.http.readTimeout", "120000");
defaultProperty.setProperty("fanfoudroid.http.retryCount", "3");
defaultProperty.setProperty("fanfoudroid.http.retryIntervalSecs", "10");
//defaultProperty.setProperty("fanfoudroid.oauth.consumerKey","");
//defaultProperty.setProperty("fanfoudroid.oauth.consumerSecret","");
defaultProperty.setProperty("fanfoudroid.async.numThreads", "1");
defaultProperty.setProperty("fanfoudroid.clientVersion", "1.0");
try {
// Android platform should have dalvik.system.VMRuntime in the classpath.
// @see http://developer.android.com/reference/dalvik/system/VMRuntime.html
Class.forName("dalvik.system.VMRuntime");
defaultProperty.setProperty("fanfoudroid.dalvik", "true");
} catch (ClassNotFoundException cnfe) {
defaultProperty.setProperty("fanfoudroid.dalvik", "false");
}
DALVIK = getBoolean("fanfoudroid.dalvik");
String t4jProps = "fanfoudroid.properties";
boolean loaded = loadProperties(defaultProperty, "." + File.separatorChar + t4jProps) ||
loadProperties(defaultProperty, Configuration.class.getResourceAsStream("/WEB-INF/" + t4jProps)) ||
loadProperties(defaultProperty, Configuration.class.getResourceAsStream("/" + t4jProps));
}
private static boolean loadProperties(Properties props, String path) {
try {
File file = new File(path);
if(file.exists() && file.isFile()){
props.load(new FileInputStream(file));
return true;
}
} catch (Exception ignore) {
}
return false;
}
private static boolean loadProperties(Properties props, InputStream is) {
try {
props.load(is);
return true;
} catch (Exception ignore) {
}
return false;
}
private static boolean DALVIK;
public static boolean isDalvik() {
return DALVIK;
}
public static boolean useSSL() {
return getBoolean("fanfoudroid.http.useSSL");
}
public static String getScheme(){
return useSSL() ? "https://" : "http://";
}
public static String getCilentVersion() {
return getProperty("fanfoudroid.clientVersion");
}
public static String getCilentVersion(String clientVersion) {
return getProperty("fanfoudroid.clientVersion", clientVersion);
}
public static String getSource() {
return getProperty("fanfoudroid.source");
}
public static String getSource(String source) {
return getProperty("fanfoudroid.source", source);
}
public static String getProxyHost() {
return getProperty("fanfoudroid.http.proxyHost");
}
public static String getProxyHost(String proxyHost) {
return getProperty("fanfoudroid.http.proxyHost", proxyHost);
}
public static String getProxyUser() {
return getProperty("fanfoudroid.http.proxyUser");
}
public static String getProxyUser(String user) {
return getProperty("fanfoudroid.http.proxyUser", user);
}
public static String getClientURL() {
return getProperty("fanfoudroid.clientURL");
}
public static String getClientURL(String clientURL) {
return getProperty("fanfoudroid.clientURL", clientURL);
}
public static String getProxyPassword() {
return getProperty("fanfoudroid.http.proxyPassword");
}
public static String getProxyPassword(String password) {
return getProperty("fanfoudroid.http.proxyPassword", password);
}
public static int getProxyPort() {
return getIntProperty("fanfoudroid.http.proxyPort");
}
public static int getProxyPort(int port) {
return getIntProperty("fanfoudroid.http.proxyPort", port);
}
public static int getConnectionTimeout() {
return getIntProperty("fanfoudroid.http.connectionTimeout");
}
public static int getConnectionTimeout(int connectionTimeout) {
return getIntProperty("fanfoudroid.http.connectionTimeout", connectionTimeout);
}
public static int getReadTimeout() {
return getIntProperty("fanfoudroid.http.readTimeout");
}
public static int getReadTimeout(int readTimeout) {
return getIntProperty("fanfoudroid.http.readTimeout", readTimeout);
}
public static int getRetryCount() {
return getIntProperty("fanfoudroid.http.retryCount");
}
public static int getRetryCount(int retryCount) {
return getIntProperty("fanfoudroid.http.retryCount", retryCount);
}
public static int getRetryIntervalSecs() {
return getIntProperty("fanfoudroid.http.retryIntervalSecs");
}
public static int getRetryIntervalSecs(int retryIntervalSecs) {
return getIntProperty("fanfoudroid.http.retryIntervalSecs", retryIntervalSecs);
}
public static String getUser() {
return getProperty("fanfoudroid.user");
}
public static String getUser(String userId) {
return getProperty("fanfoudroid.user", userId);
}
public static String getPassword() {
return getProperty("fanfoudroid.password");
}
public static String getPassword(String password) {
return getProperty("fanfoudroid.password", password);
}
public static String getUserAgent() {
return getProperty("fanfoudroid.http.userAgent");
}
public static String getUserAgent(String userAgent) {
return getProperty("fanfoudroid.http.userAgent", userAgent);
}
public static String getOAuthConsumerKey() {
return getProperty("fanfoudroid.oauth.consumerKey");
}
public static String getOAuthConsumerKey(String consumerKey) {
return getProperty("fanfoudroid.oauth.consumerKey", consumerKey);
}
public static String getOAuthConsumerSecret() {
return getProperty("fanfoudroid.oauth.consumerSecret");
}
public static String getOAuthConsumerSecret(String consumerSecret) {
return getProperty("fanfoudroid.oauth.consumerSecret", consumerSecret);
}
public static boolean getBoolean(String name) {
String value = getProperty(name);
return Boolean.valueOf(value);
}
public static int getIntProperty(String name) {
String value = getProperty(name);
try {
return Integer.parseInt(value);
} catch (NumberFormatException nfe) {
return -1;
}
}
public static int getIntProperty(String name, int fallbackValue) {
String value = getProperty(name, String.valueOf(fallbackValue));
try {
return Integer.parseInt(value);
} catch (NumberFormatException nfe) {
return -1;
}
}
public static long getLongProperty(String name) {
String value = getProperty(name);
try {
return Long.parseLong(value);
} catch (NumberFormatException nfe) {
return -1;
}
}
public static String getProperty(String name) {
return getProperty(name, null);
}
public static String getProperty(String name, String fallbackValue) {
String value;
try {
value = System.getProperty(name, fallbackValue);
if (null == value) {
value = defaultProperty.getProperty(name);
}
if (null == value) {
String fallback = defaultProperty.getProperty(name + ".fallback");
if (null != fallback) {
value = System.getProperty(fallback);
}
}
} catch (AccessControlException ace) {
// Unsigned applet cannot access System properties
value = fallbackValue;
}
return replace(value);
}
private static String replace(String value) {
if (null == value) {
return value;
}
String newValue = value;
int openBrace = 0;
if (-1 != (openBrace = value.indexOf("{", openBrace))) {
int closeBrace = value.indexOf("}", openBrace);
if (closeBrace > (openBrace + 1)) {
String name = value.substring(openBrace + 1, closeBrace);
if (name.length() > 0) {
newValue = value.substring(0, openBrace) + getProperty(name)
+ value.substring(closeBrace + 1);
}
}
}
if (newValue.equals(value)) {
return value;
} else {
return replace(newValue);
}
}
public static int getNumberOfAsyncThreads() {
return getIntProperty("fanfoudroid.async.numThreads");
}
public static boolean getDebug() {
return getBoolean("fanfoudroid.debug");
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing Treands.
*
* @author Yusuke Yamamoto - yusuke at mac.com
* @since Weibo4J 2.0.2
*/
public class Trends extends WeiboResponse implements Comparable<Trends> {
private Date asOf;
private Date trendAt;
private Trend[] trends;
private static final long serialVersionUID = -7151479143843312309L;
public int compareTo(Trends that) {
return this.trendAt.compareTo(that.trendAt);
}
/*package*/ Trends(Response res, Date asOf, Date trendAt, Trend[] trends)
throws HttpException {
super(res);
this.asOf = asOf;
this.trendAt = trendAt;
this.trends = trends;
}
/*package*/
static List<Trends> constructTrendsList(Response res) throws
HttpException {
JSONObject json = res.asJSONObject();
List<Trends> trends;
try {
Date asOf = parseDate(json.getString("as_of"));
JSONObject trendsJson = json.getJSONObject("trends");
trends = new ArrayList<Trends>(trendsJson.length());
Iterator ite = trendsJson.keys();
while (ite.hasNext()) {
String key = (String) ite.next();
JSONArray array = trendsJson.getJSONArray(key);
Trend[] trendsArray = jsonArrayToTrendArray(array);
if (key.length() == 19) {
// current trends
trends.add(new Trends(res, asOf, parseDate(key
, "yyyy-MM-dd HH:mm:ss"), trendsArray));
} else if (key.length() == 16) {
// daily trends
trends.add(new Trends(res, asOf, parseDate(key
, "yyyy-MM-dd HH:mm"), trendsArray));
} else if (key.length() == 10) {
// weekly trends
trends.add(new Trends(res, asOf, parseDate(key
, "yyyy-MM-dd"), trendsArray));
}
}
Collections.sort(trends);
return trends;
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + res.asString(), jsone);
}
}
/*package*/
static Trends constructTrends(Response res) throws HttpException {
JSONObject json = res.asJSONObject();
try {
Date asOf = parseDate(json.getString("as_of"));
JSONArray array = json.getJSONArray("trends");
Trend[] trendsArray = jsonArrayToTrendArray(array);
return new Trends(res, asOf, asOf, trendsArray);
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + res.asString(), jsone);
}
}
private static Date parseDate(String asOfStr) throws HttpException {
Date parsed;
if (asOfStr.length() == 10) {
parsed = new Date(Long.parseLong(asOfStr) * 1000);
} else {
// parsed = WeiboResponse.parseDate(asOfStr, "EEE, d MMM yyyy HH:mm:ss z");
parsed = WeiboResponse.parseDate(asOfStr, "EEE MMM WW HH:mm:ss z yyyy");
}
return parsed;
}
private static Trend[] jsonArrayToTrendArray(JSONArray array) throws JSONException {
Trend[] trends = new Trend[array.length()];
for (int i = 0; i < array.length(); i++) {
JSONObject trend = array.getJSONObject(i);
trends[i] = new Trend(trend);
}
return trends;
}
public Trend[] getTrends() {
return this.trends;
}
public Date getAsOf() {
return asOf;
}
public Date getTrendAt() {
return trendAt;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Trends)) return false;
Trends trends1 = (Trends) o;
if (asOf != null ? !asOf.equals(trends1.asOf) : trends1.asOf != null)
return false;
if (trendAt != null ? !trendAt.equals(trends1.trendAt) : trends1.trendAt != null)
return false;
if (!Arrays.equals(trends, trends1.trends)) return false;
return true;
}
@Override
public int hashCode() {
int result = asOf != null ? asOf.hashCode() : 0;
result = 31 * result + (trendAt != null ? trendAt.hashCode() : 0);
result = 31 * result + (trends != null ? Arrays.hashCode(trends) : 0);
return result;
}
@Override
public String toString() {
return "Trends{" +
"asOf=" + asOf +
", trendAt=" + trendAt +
", trends=" + (trends == null ? null : Arrays.asList(trends)) +
'}';
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONException;
import org.json.JSONObject;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* 模仿JSONObject的XML实现
* @author jmx
*
*/
class XmlObject{
private String str;
public XmlObject(String s){
this.str = s;
}
//FIXME: 这里用的是一个专有的ugly实现
public String getString(String name) throws Exception {
Pattern p = Pattern.compile(String.format("<%s>(.*?)</%s>", name, name));
Matcher m = p.matcher(this.str);
if (m.find()){
return m.group(1);
}else{
throw new Exception(String.format("<%s> value not found", name));
}
}
@Override
public String toString(){
return this.str;
}
}
/**
* 服务器响应的错误信息
*/
public class RefuseError extends WeiboResponse implements java.io.Serializable {
// TODO: get error type
public static final int ERROR_A = 1;
public static final int ERROR_B = 1;
public static final int ERROR_C = 1;
private int mErrorCode = -1;
private String mRequestUrl = "";
private String mResponseError = "";
private static final long serialVersionUID = -2105422180879273058L;
public RefuseError(Response res) throws HttpException {
String error = res.asString();
try{
//先尝试作为json object进行处理
JSONObject json = new JSONObject(error);
init(json);
}catch(Exception e1){
//如果失败,则作为XML再进行处理
try{
XmlObject xml = new XmlObject(error);
init(xml);
}catch(Exception e2){
//再失败就作为普通字符串进行处理,这个处理保证不会出错
init(error);
}
}
}
public void init(JSONObject json) throws HttpException {
try {
mRequestUrl = json.getString("request");
mResponseError = json.getString("error");
parseError(mResponseError);
} catch (JSONException je) {
throw new HttpException(je.getMessage() + ":" + json.toString(), je);
}
}
public void init(XmlObject xml) throws HttpException {
try {
mRequestUrl = xml.getString("request");
mResponseError = xml.getString("error");
parseError(mResponseError);
} catch (Exception e) {
throw new HttpException(e.getMessage() + ":" + xml.toString(), e);
}
}
public void init(String error){
mRequestUrl = "";
mResponseError = error;
parseError(mResponseError);
}
private void parseError(String error) {
if (error.equals("")) {
mErrorCode = ERROR_A;
}
}
public int getErrorCode() {
return mErrorCode;
}
public String getRequestUrl() {
return mRequestUrl;
}
public String getMessage() {
return mResponseError;
}
} | Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import com.ch_linghu.fanfoudroid.http.HttpClient;
/**
* @author Yusuke Yamamoto - yusuke at mac.com
*/
/*protected*/ class WeiboSupport {
protected HttpClient http = null;
protected String source = Configuration.getSource();
protected final boolean USE_SSL;
/*package*/ WeiboSupport(){
USE_SSL = Configuration.useSSL();
http = new HttpClient(); // In case that the user is not logged in
}
/*package*/ WeiboSupport(String userId, String password){
USE_SSL = Configuration.useSSL();
http = new HttpClient(userId, password);
}
/**
* Returns authenticating userid
*
* @return userid
*/
public String getUserId() {
return http.getUserId();
}
/**
* Returns authenticating password
*
* @return password
*/
public String getPassword() {
return http.getPassword();
}
//Low-level interface
public HttpClient getHttpClient(){
return http;
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.Arrays;
import org.json.JSONArray;
import org.json.JSONException;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing array of numeric IDs.
*
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class IDs extends WeiboResponse {
private String[] ids;
private long previousCursor;
private long nextCursor;
private static final long serialVersionUID = -6585026560164704953L;
private static String[] ROOT_NODE_NAMES = {"id_list", "ids"};
/*package*/ IDs(Response res) throws HttpException {
super(res);
Element elem = res.asDocument().getDocumentElement();
ensureRootNodeNameIs(ROOT_NODE_NAMES, elem);
NodeList idlist = elem.getElementsByTagName("id");
ids = new String[idlist.getLength()];
for (int i = 0; i < idlist.getLength(); i++) {
try {
ids[i] = idlist.item(i).getFirstChild().getNodeValue();
} catch (NumberFormatException nfe) {
throw new HttpException("Weibo API returned malformed response(Invalid Number): " + elem, nfe);
} catch (NullPointerException npe) {
throw new HttpException("Weibo API returned malformed response(NULL): " + elem, npe);
}
}
previousCursor = getChildLong("previous_cursor", elem);
nextCursor = getChildLong("next_cursor", elem);
}
/* package */IDs(Response res, Weibo w) throws HttpException {
super(res);
// TODO: 饭否返回的为 JSONArray 类型,
// 例如["ifan","fanfouapi","\u62cd\u62cd","daoru"]
// JSONObject json= res.asJSONObject();
JSONArray jsona = res.asJSONArray();
try {
int size = jsona.length();
ids = new String[size];
for (int i = 0; i < size; i++) {
ids[i] = jsona.getString(i);
}
} catch (JSONException jsone) {
throw new HttpException(jsone);
}
}
public String[] getIDs() {
return ids;
}
/**
*
* @since Weibo4J 2.0.10
*/
public boolean hasPrevious(){
return 0 != previousCursor;
}
/**
*
* @since Weibo4J 2.0.10
*/
public long getPreviousCursor() {
return previousCursor;
}
/**
*
* @since Weibo4J 2.0.10
*/
public boolean hasNext(){
return 0 != nextCursor;
}
/**
*
* @since Weibo4J 2.0.10
*/
public long getNextCursor() {
return nextCursor;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof IDs)) return false;
IDs iDs = (IDs) o;
if (!Arrays.equals(ids, iDs.ids)) return false;
return true;
}
@Override
public int hashCode() {
return ids != null ? Arrays.hashCode(ids) : 0;
}
public int getCount(){
return ids.length;
}
@Override
public String toString() {
return "IDs{" +
"ids=" + ids +
", previousCursor=" + previousCursor +
", nextCursor=" + nextCursor +
'}';
}
} | Java |
/*
* UserObjectWapper.java created on 2010-7-28 上午08:48:35 by bwl (Liu Daoru)
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.io.Serializable;
import java.util.List;
/**
* 对User对象列表进行的包装,以支持cursor相关信息传递
* @author liudaoru - daoru at sina.com.cn
*/
public class UserWapper implements Serializable {
private static final long serialVersionUID = -3119107701303920284L;
/**
* 用户对象列表
*/
private List<User> users;
/**
* 向前翻页的cursor
*/
private long previousCursor;
/**
* 向后翻页的cursor
*/
private long nextCursor;
public UserWapper(List<User> users, long previousCursor, long nextCursor) {
this.users = users;
this.previousCursor = previousCursor;
this.nextCursor = nextCursor;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public long getPreviousCursor() {
return previousCursor;
}
public void setPreviousCursor(long previousCursor) {
this.previousCursor = previousCursor;
}
public long getNextCursor() {
return nextCursor;
}
public void setNextCursor(long nextCursor) {
this.nextCursor = nextCursor;
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
/**
* Controlls pagination
*
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class Paging implements java.io.Serializable {
private int page = -1;
private int count = -1;
private String sinceId = "";
private String maxId = "";
private static final long serialVersionUID = -3285857427993796670L;
public Paging() {
}
public Paging(int page) {
setPage(page);
}
public Paging(String sinceId) {
setSinceId(sinceId);
}
public Paging(int page, int count) {
this(page);
setCount(count);
}
public Paging(int page, String sinceId) {
this(page);
setSinceId(sinceId);
}
public Paging(int page, int count, String sinceId) {
this(page, count);
setSinceId(sinceId);
}
public Paging(int page, int count, String sinceId, String maxId) {
this(page, count, sinceId);
setMaxId(maxId);
}
public int getPage() {
return page;
}
public void setPage(int page) {
if (page < 1) {
throw new IllegalArgumentException("page should be positive integer. passed:" + page);
}
this.page = page;
}
public int getCount() {
return count;
}
public void setCount(int count) {
if (count < 1) {
throw new IllegalArgumentException("count should be positive integer. passed:" + count);
}
this.count = count;
}
public Paging count(int count) {
setCount(count);
return this;
}
public String getSinceId() {
return sinceId;
}
public void setSinceId(String sinceId) {
if (sinceId.length() > 0) {
this.sinceId = sinceId;
} else {
throw new IllegalArgumentException("since_id is null. passed:" + sinceId);
}
}
public Paging sinceId(String sinceId) {
setSinceId(sinceId);
return this;
}
public String getMaxId() {
return maxId;
}
public void setMaxId(String maxId) {
if (maxId.length() == 0) {
throw new IllegalArgumentException("max_id is null. passed:" + maxId);
}
this.maxId = maxId;
}
public Paging maxId(String maxId) {
setMaxId(maxId);
return this;
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import android.text.TextUtils;
import android.util.Log;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.http.HttpClient;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
public class Weibo extends WeiboSupport implements java.io.Serializable {
public static final String TAG = "Weibo_API";
public static final String CONSUMER_KEY = Configuration.getSource();
public static final String CONSUMER_SECRET = "";
private String baseURL = Configuration.getScheme() + "api.fanfou.com/";
private String searchBaseURL = Configuration.getScheme() + "api.fanfou.com/";
private static final long serialVersionUID = -1486360080128882436L;
public Weibo() {
super(); // In case that the user is not logged in
format.setTimeZone(TimeZone.getTimeZone("GMT"));
}
public Weibo(String userId, String password) {
super(userId, password);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
}
public Weibo(String userId, String password, String baseURL) {
this(userId, password);
this.baseURL = baseURL;
}
/**
* 设置HttpClient的Auth,为请求做准备
* @param username
* @param password
*/
public void setCredentials(String username, String password) {
http.setCredentials(username, password);
}
/**
* 仅判断是否为空
* @param username
* @param password
* @return
*/
public static boolean isValidCredentials(String username, String password) {
return !TextUtils.isEmpty(username) && !TextUtils.isEmpty(password);
}
/**
* 在服务器上验证用户名/密码是否正确,成功则返回该用户信息,失败则抛出异常。
* @param username
* @param password
* @return Verified User
* @throws HttpException 验证失败及其他非200响应均抛出异常
*/
public User login(String username, String password) throws HttpException {
Log.d(TAG, "Login attempt for " + username);
http.setCredentials(username, password);
// Verify userName and password on the server.
User user = verifyCredentials();
if (null != user && user.getId().length() > 0) {
}
return user;
}
/**
* Reset HttpClient's Credentials
*/
public void reset() {
http.reset();
}
/**
* Whether Logged-in
* @return
*/
public boolean isLoggedIn() {
// HttpClient的userName&password是由TwitterApplication#onCreate
// 从SharedPreferences中取出的,他们为空则表示尚未登录,因为他们只在验证
// 账户成功后才会被储存,且注销时被清空。
return isValidCredentials(http.getUserId(), http.getPassword());
}
/**
* Sets the base URL
*
* @param baseURL String the base URL
*/
public void setBaseURL(String baseURL) {
this.baseURL = baseURL;
}
/**
* Returns the base URL
*
* @return the base URL
*/
public String getBaseURL() {
return this.baseURL;
}
/**
* Sets the search base URL
*
* @param searchBaseURL the search base URL
* @since fanfoudroid 0.5.0
*/
public void setSearchBaseURL(String searchBaseURL) {
this.searchBaseURL = searchBaseURL;
}
/**
* Returns the search base url
* @return search base url
* @since fanfoudroid 0.5.0
*/
public String getSearchBaseURL(){
return this.searchBaseURL;
}
/**
* Returns authenticating userid
* 注意:此userId不一定等同与饭否用户的user_id参数
* 它可能是任意一种当前用户所使用的ID类型(如邮箱,用户名等),
*
* @return userid
*/
public String getUserId() {
return http.getUserId();
}
/**
* Returns authenticating password
*
* @return password
*/
public String getPassword() {
return http.getPassword();
}
/**
* Issues an HTTP GET request.
*
* @param url the request url
* @param authenticate if true, the request will be sent with BASIC authentication header
* @return the response
* @throws HttpException
*/
protected Response get(String url, boolean authenticate) throws HttpException {
return get(url, null, authenticate);
}
/**
* Issues an HTTP GET request.
*
* @param url the request url
* @param authenticate if true, the request will be sent with BASIC authentication header
* @param name1 the name of the first parameter
* @param value1 the value of the first parameter
* @return the response
* @throws HttpException
*/
protected Response get(String url, String name1, String value1, boolean authenticate) throws HttpException {
ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
params.add( new BasicNameValuePair(name1, HttpClient.encode(value1) ) );
return get(url, params, authenticate);
}
/**
* Issues an HTTP GET request.
*
* @param url the request url
* @param name1 the name of the first parameter
* @param value1 the value of the first parameter
* @param name2 the name of the second parameter
* @param value2 the value of the second parameter
* @param authenticate if true, the request will be sent with BASIC authentication header
* @return the response
* @throws HttpException
*/
protected Response get(String url, String name1, String value1, String name2, String value2, boolean authenticate) throws HttpException {
ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
params.add(new BasicNameValuePair(name1, HttpClient.encode(value1)));
params.add(new BasicNameValuePair(name2, HttpClient.encode(value2)));
return get(url, params, authenticate);
}
/**
* Issues an HTTP GET request.
*
* @param url the request url
* @param params the request parameters
* @param authenticate if true, the request will be sent with BASIC authentication header
* @return the response
* @throws HttpException
*/
protected Response get(String url, ArrayList<BasicNameValuePair> params, boolean authenticated) throws HttpException {
if (url.indexOf("?") == -1) {
url += "?source=" + CONSUMER_KEY;
} else if (url.indexOf("source") == -1) {
url += "&source=" + CONSUMER_KEY;
}
//以HTML格式获得数据,以便进一步处理
url += "&format=html";
if (null != params && params.size() > 0) {
url += "&" + HttpClient.encodeParameters(params);
}
return http.get(url, authenticated);
}
/**
* Issues an HTTP GET request.
*
* @param url the request url
* @param params the request parameters
* @param paging controls pagination
* @param authenticate if true, the request will be sent with BASIC authentication header
* @return the response
* @throws HttpException
*/
protected Response get(String url, ArrayList<BasicNameValuePair> params, Paging paging, boolean authenticate) throws HttpException {
if (null == params) {
params = new ArrayList<BasicNameValuePair>();
}
if (null != paging) {
if ("" != paging.getMaxId()) {
params.add(new BasicNameValuePair("max_id", String.valueOf(paging.getMaxId())));
}
if ("" != paging.getSinceId()) {
params.add(new BasicNameValuePair("since_id", String.valueOf(paging.getSinceId())));
}
if (-1 != paging.getPage()) {
params.add(new BasicNameValuePair("page", String.valueOf(paging.getPage())));
}
if (-1 != paging.getCount()) {
params.add(new BasicNameValuePair("count", String.valueOf(paging.getCount())));
}
return get(url, params, authenticate);
} else {
return get(url, params, authenticate);
}
}
/**
* 生成POST Parameters助手
* @param nameValuePair 参数(一个或多个)
* @return post parameters
*/
public ArrayList<BasicNameValuePair> createParams(BasicNameValuePair... nameValuePair ) {
ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
for (BasicNameValuePair param : nameValuePair) {
params.add(param);
}
return params;
}
/***************** API METHOD START *********************/
/* 搜索相关的方法 */
/**
* Returns tweets that match a specified query.
* <br>This method calls http://api.fanfou.com/users/search.format
* @param query - the search condition
* @return the result
* @throws HttpException
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public QueryResult search(Query query) throws HttpException {
try{
return new QueryResult(get(searchBaseURL + "search/public_timeline.json", query.asPostParameters(), false), this);
}catch(HttpException te){
if(404 == te.getStatusCode()){
return new QueryResult(query);
}else{
throw te;
}
}
}
/**
* Returns the top ten topics that are currently trending on Weibo. The response includes the time of the request, the name of each trend.
* @return the result
* @throws HttpException
* @since fanfoudroid 0.5.0
*/
public Trends getTrends() throws HttpException {
return Trends.constructTrends(get(searchBaseURL + "trends.json", false));
}
private String toDateStr(Date date){
if(null == date){
date = new Date();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(date);
}
/* 消息相关的方法 */
/**
* Returns the 20 most recent statuses from non-protected users who have set a custom user icon.
* <br>This method calls http://api.fanfou.com/statuses/public_timeline.format
*
* @return list of statuses of the Public Timeline
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getPublicTimeline() throws
HttpException {
return Status.constructStatuses(get(getBaseURL() +
"statuses/public_timeline.json", true));
}
public RateLimitStatus getRateLimitStatus()throws
HttpException {
return new RateLimitStatus(get(getBaseURL() +
"account/rate_limit_status.json", true),this);
}
/**
* Returns the 20 most recent statuses, including retweets, posted by the authenticating user and that user's friends. This is the equivalent of /timeline/home on the Web.
* <br>This method calls http://api.fanfou.com/statuses/home_timeline.format
*
* @return list of the home Timeline
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<Status> getHomeTimeline() throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/home_timeline.json", true));
}
/**
* Returns the 20 most recent statuses, including retweets, posted by the authenticating user and that user's friends. This is the equivalent of /timeline/home on the Web.
* <br>This method calls http://api.fanfou.com/statuses/home_timeline.format
*
* @param paging controls pagination
* @return list of the home Timeline
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<Status> getHomeTimeline(Paging paging) throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/home_timeline.json", null, paging, true));
}
/**
* Returns the 20 most recent statuses posted in the last 24 hours from the authenticating1 user and that user's friends.
* It's also possible to request another user's friends_timeline via the id parameter below.
* <br>This method calls http://api.fanfou.com/statuses/friends_timeline.format
*
* @return list of the Friends Timeline
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getFriendsTimeline() throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/friends_timeline.json", true));
}
/**
* Returns the 20 most recent statuses posted in the last 24 hours from the specified userid.
* <br>This method calls http://api.fanfou.com/statuses/friends_timeline.format
*
* @param paging controls pagination
* @return list of the Friends Timeline
* @throws HttpException
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getFriendsTimeline(Paging paging) throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/friends_timeline.json",null, paging, true));
}
/**
* Returns friend time line by page and count.
* <br>This method calls http://api.fanfou.com/statuses/friends_timeline.format
* @param page
* @param count
* @return
* @throws HttpException
*/
public List<Status> getFriendsTimeline(int page, int count) throws
HttpException {
Paging paging = new Paging(page, count);
return Status.constructStatuses(get(getBaseURL() + "statuses/friends_timeline.json",null, paging, true));
}
/**
* Returns the most recent statuses posted in the last 24 hours from the specified userid.
* <br>This method calls http://api.fanfou.com/statuses/user_timeline.format
*
* @param id specifies the ID or screen name of the user for whom to return the user_timeline
* @param paging controls pagenation
* @return list of the user Timeline
* @throws HttpException
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getUserTimeline(String id, Paging paging)
throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/user_timeline/" + id + ".json",
null, paging, http.isAuthenticationEnabled()));
}
/**
* Returns the most recent statuses posted in the last 24 hours from the specified userid.
* <br>This method calls http://api.fanfou.com/statuses/user_timeline.format
*
* @param id specifies the ID or screen name of the user for whom to return the user_timeline
* @return the 20 most recent statuses posted in the last 24 hours from the user
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getUserTimeline(String id) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/user_timeline/" + id + ".json", http.isAuthenticationEnabled()));
}
/**
* Returns the most recent statuses posted in the last 24 hours from the authenticating user.
* <br>This method calls http://api.fanfou.com/statuses/user_timeline.format
*
* @return the 20 most recent statuses posted in the last 24 hours from the user
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getUserTimeline() throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/user_timeline.json"
, true));
}
/**
* Returns the most recent statuses posted in the last 24 hours from the authenticating user.
* <br>This method calls http://api.fanfou.com/statuses/user_timeline.format
*
* @param paging controls pagination
* @return the 20 most recent statuses posted in the last 24 hours from the user
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<Status> getUserTimeline(Paging paging) throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/user_timeline.json"
, null, paging, true));
}
public List<Status> getUserTimeline(int page, int count) throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/user_timeline.json"
, null, new Paging(page, count), true));
}
/**
* Returns the 20 most recent mentions (status containing @username) for the authenticating user.
* <br>This method calls http://api.fanfou.com/statuses/mentions.format
*
* @return the 20 most recent replies
* @throws HttpException
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getMentions() throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/mentions.json",
null, true));
}
// by since_id
public List<Status> getMentions(String since_id) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/mentions.json",
"since_id", String.valueOf(since_id), true));
}
/**
* Returns the 20 most recent mentions (status containing @username) for the authenticating user.
* <br>This method calls http://api.fanfou.com/statuses/mentions.format
*
* @param paging controls pagination
* @return the 20 most recent replies
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getMentions(Paging paging) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/mentions.json",
null, paging, true));
}
/**
* Returns a single status, specified by the id parameter. The status's author will be returned inline.
* <br>This method calls http://api.fanfou.com/statuses/show/id.format
*
* @param id the numerical ID of the status you're trying to retrieve
* @return a single status
* @throws HttpException when Weibo service or network is unavailable. 可能因为“你没有通过这个用户的验证“,返回403
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public Status showStatus(String id) throws HttpException {
return new Status(get(getBaseURL() + "statuses/show/" + id + ".json", true));
}
/**
* Updates the user's status.
* The text will be trimed if the length of the text is exceeding 160 characters.
* <br>This method calls http://api.fanfou.com/statuses/update.format
*
* @param status the text of your status update
* @return the latest status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public Status updateStatus(String status) throws HttpException{
return new Status(http.post(getBaseURL() + "statuses/update.json",
createParams(new BasicNameValuePair("status", status),
new BasicNameValuePair("source", source))));
}
/**
* Updates the user's status.
* The text will be trimed if the length of the text is exceeding 160 characters.
* <br>发布消息 http://api.fanfou.com/statuses/update.[json|xml]
*
* @param status the text of your status update
* @param latitude The location's latitude that this tweet refers to.
* @param longitude The location's longitude that this tweet refers to.
* @return the latest status
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public Status updateStatus(String status, double latitude, double longitude) throws HttpException, JSONException {
return new Status(http.post(getBaseURL() + "statuses/update.json",
createParams(new BasicNameValuePair("status", status),
new BasicNameValuePair("source", source),
new BasicNameValuePair("location", latitude + "," + longitude))));
}
/**
* Updates the user's status.
* 如果要使用inreplyToStatusId参数, 那么该status就必须得是@别人的.
* The text will be trimed if the length of the text is exceeding 160 characters.
* <br>发布消息 http://api.fanfou.com/statuses/update.[json|xml]
*
* @param status the text of your status update
* @param inReplyToStatusId The ID of an existing status that the status to be posted is in reply to. This implicitly sets the in_reply_to_user_id attribute of the resulting status to the user ID of the message being replied to. Invalid/missing status IDs will be ignored.
* @return the latest status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public Status updateStatus(String status, String inReplyToStatusId) throws HttpException {
return new Status(http.post(getBaseURL() + "statuses/update.json",
createParams(new BasicNameValuePair("status", status),
new BasicNameValuePair("source", source),
new BasicNameValuePair("in_reply_to_status_id", inReplyToStatusId))));
}
/**
* Updates the user's status.
* The text will be trimed if the length of the text is exceeding 160 characters.
* <br>发布消息 http://api.fanfou.com/statuses/update.[json|xml]
*
* @param status the text of your status update
* @param inReplyToStatusId The ID of an existing status that the status to be posted is in reply to. This implicitly sets the in_reply_to_user_id attribute of the resulting status to the user ID of the message being replied to. Invalid/missing status IDs will be ignored.
* @param latitude The location's latitude that this tweet refers to.
* @param longitude The location's longitude that this tweet refers to.
* @return the latest status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public Status updateStatus(String status, String inReplyToStatusId
, double latitude, double longitude) throws HttpException {
return new Status(http.post(getBaseURL() + "statuses/update.json",
createParams(new BasicNameValuePair("status", status),
new BasicNameValuePair("source", source),
new BasicNameValuePair("location", latitude + "," + longitude),
new BasicNameValuePair("in_reply_to_status_id", inReplyToStatusId))));
}
/**
* upload the photo.
* The text will be trimed if the length of the text is exceeding 160 characters.
* The image suport.
* <br>上传照片 http://api.fanfou.com/photos/upload.[json|xml]
*
* @param status the text of your status update
* @return the latest status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public Status uploadPhoto(String status, File file) throws HttpException {
return new Status(http.httpRequest(getBaseURL() + "photos/upload.json",
createParams(new BasicNameValuePair("status", status),
new BasicNameValuePair("source", source)),
file, true, HttpPost.METHOD_NAME));
}
public Status updateStatus(String status, File file) throws HttpException {
return uploadPhoto(status, file);
}
/**
* Destroys the status specified by the required ID parameter. The authenticating user must be the author of the specified status.
* <br>删除消息 http://api.fanfou.com/statuses/destroy.[json|xml]
*
* @param statusId The ID of the status to destroy.
* @return the deleted status
* @throws HttpException when Weibo service or network is unavailable
* @since 1.0.5
*/
public Status destroyStatus(String statusId) throws HttpException {
return new Status(http.post(getBaseURL() + "statuses/destroy/" + statusId + ".json",
createParams(), true));
}
/**
* Returns extended information of a given user, specified by ID or screen name as per the required id parameter below. This information includes design settings, so third party developers can theme their widgets according to a given user's preferences.
* <br>This method calls http://api.fanfou.com/users/show.format
*
* @param id (cann't be screenName the ID of the user for whom to request the detail
* @return User
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public User showUser(String id) throws HttpException {
return new User(get(getBaseURL() + "users/show.json",
createParams(new BasicNameValuePair("id", id)), true));
}
/**
* Return a status of repost
* @param to_user_name repost status's user name
* @param repost_status_id repost status id
* @param repost_status_text repost status text
* @param new_status the new status text
* @return a single status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public Status repost(String to_user_name, String repost_status_id,
String repost_status_text, String new_status) throws HttpException {
StringBuilder sb = new StringBuilder();
sb.append(new_status);
sb.append(" ");
sb.append(R.string.pref_rt_prefix_default + ":@");
sb.append(to_user_name);
sb.append(" ");
sb.append(repost_status_text);
sb.append(" ");
String message = sb.toString();
return new Status(http.post(getBaseURL() + "statuses/update.json",
createParams(new BasicNameValuePair("status", message),
new BasicNameValuePair("repost_status_id", repost_status_id)), true));
}
/**
* Return a status of repost
* @param to_user_name repost status's user name
* @param repost_status_id repost status id
* @param repost_status_text repost status text
* @param new_status the new status text
* @return a single status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public Status repost(String new_status, String repost_status_id) throws HttpException
{
return new Status(http.post(getBaseURL() + "statuses/update.json",
createParams(new BasicNameValuePair("status", new_status),
new BasicNameValuePair("source", CONSUMER_KEY),
new BasicNameValuePair("repost_status_id", repost_status_id)), true));
}
/**
* Return a status of repost
* @param repost_status_id repost status id
* @param repost_status_text repost status text
* @return a single status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public Status repost(String repost_status_id, String new_status, boolean tmp) throws HttpException {
Status repost_to = showStatus(repost_status_id);
String to_user_name = repost_to.getUser().getName();
String repost_status_text = repost_to.getText();
return repost(to_user_name, repost_status_id, repost_status_text, new_status);
}
/* User Methods */
/**
* Returns the specified user's friends, each with current status inline.
* <br>This method calls http://api.fanfou.com/statuses/friends.format
*
* @return the list of friends
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<User> getFriendsStatuses() throws HttpException {
return User.constructResult(get(getBaseURL() + "users/friends.json", true));
}
/**
* Returns the specified user's friends, each with current status inline.
* <br>This method calls http://api.fanfou.com/statuses/friends.format
* <br>分页每页显示100条
*
* @param paging controls pagination
* @return the list of friends
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*
*/
public List<User> getFriendsStatuses(Paging paging) throws HttpException {
return User.constructUsers(get(getBaseURL() + "users/friends.json", null,
paging, true));
}
/**
* Returns the user's friends, each with current status inline.
* <br>This method calls http://api.fanfou.com/statuses/friends.format
*
* @param id the ID or screen name of the user for whom to request a list of friends
* @return the list of friends
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<User> getFriendsStatuses(String id) throws HttpException {
return User.constructUsers(get(getBaseURL() + "users/friends.json",
createParams(new BasicNameValuePair("id", id)), false));
}
/**
* Returns the user's friends, each with current status inline.
* <br>This method calls http://api.fanfou.com/statuses/friends.format
*
* @param id the ID or screen name of the user for whom to request a list of friends
* @param paging controls pagination (饭否API 默认返回 100 条/页)
* @return the list of friends
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<User> getFriendsStatuses(String id, Paging paging) throws HttpException {
return User.constructUsers(get(getBaseURL() + "users/friends.json",
createParams(new BasicNameValuePair("id", id)), paging, false));
}
/**
* Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Weibo (this is going to be changed).
* <br>This method calls http://api.fanfou.com/statuses/followers.format
*
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<User> getFollowersStatuses() throws HttpException {
return User.constructResult(get(getBaseURL() + "statuses/followers.json", true));
}
/**
* Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Weibo (this is going to be changed).
* <br>This method calls http://api.fanfou.com/statuses/followers.format
*
* @param paging controls pagination
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<User> getFollowersStatuses(Paging paging) throws HttpException {
return User.constructUsers(get(getBaseURL() + "statuses/followers.json", null
, paging, true));
}
/**
* Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Weibo (this is going to be changed).
* <br>This method calls http://api.fanfou.com/statuses/followers.format
*
* @param id The ID (not screen name) of the user for whom to request a list of followers.
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<User> getFollowersStatuses(String id) throws HttpException {
return User.constructUsers(get(getBaseURL() + "statuses/followers/" + id + ".json", true));
}
/**
* Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Weibo (this is going to be changed).
* <br>This method calls http://api.fanfou.com/statuses/followers.format
*
* @param id The ID or screen name of the user for whom to request a list of followers.
* @param paging controls pagination
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<User> getFollowersStatuses(String id, Paging paging) throws HttpException {
return User.constructUsers(get(getBaseURL() + "statuses/followers/" + id +
".json", null, paging, true));
}
/* 私信功能 */
/**
* Sends a new direct message to the specified user from the authenticating user. Requires both the user and text parameters below.
* The text will be trimed if the length of the text is exceeding 140 characters.
* <br>This method calls http://api.fanfou.com/direct_messages/new.format
* <br>通过客户端只能给互相关注的人发私信
*
* @param id the ID of the user to whom send the direct message
* @param text String
* @return DirectMessage
* @throws HttpException when Weibo service or network is unavailable
@see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public DirectMessage sendDirectMessage(String id, String text) throws HttpException {
return new DirectMessage(http.post(getBaseURL() + "direct_messages/new.json",
createParams(new BasicNameValuePair("user", id),
new BasicNameValuePair("text", text))).asJSONObject());
}
//TODO: need be unit tested by in_reply_to_id.
/**
* Sends a new direct message to the specified user from the authenticating user. Requires both the user and text parameters below.
* The text will be trimed if the length of the text is exceeding 140 characters.
* <br>通过客户端只能给互相关注的人发私信
*
* @param id
* @param text
* @param in_reply_to_id
* @return
* @throws HttpException
*/
public DirectMessage sendDirectMessage(String id, String text, String in_reply_to_id)
throws HttpException {
return new DirectMessage(http.post(getBaseURL() + "direct_messages/new.json",
createParams(new BasicNameValuePair("user", id),
new BasicNameValuePair("text", text),
new BasicNameValuePair("is_reply_to_id", in_reply_to_id))).asJSONObject());
}
/**
* Destroys the direct message specified in the required ID parameter. The authenticating user must be the recipient of the specified direct message.
* <br>This method calls http://api.fanfou.com/direct_messages/destroy/id.format
*
* @param id the ID of the direct message to destroy
* @return the deleted direct message
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public DirectMessage destroyDirectMessage(String id) throws
HttpException {
return new DirectMessage(http.post(getBaseURL() +
"direct_messages/destroy/" + id + ".json", true).asJSONObject());
}
/**
* Returns a list of the direct messages sent to the authenticating user.
* <br>This method calls http://api.fanfou.com/direct_messages.format
*
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<DirectMessage> getDirectMessages() throws HttpException {
return DirectMessage.constructDirectMessages(get(getBaseURL() + "direct_messages.json", true));
}
/**
* Returns a list of the direct messages sent to the authenticating user.
* <br>This method calls http://api.fanfou.com/direct_messages.format
*
* @param paging controls pagination
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<DirectMessage> getDirectMessages(Paging paging) throws HttpException {
return DirectMessage.constructDirectMessages(get(getBaseURL()
+ "direct_messages.json", null, paging, true));
}
/**
* Returns a list of the direct messages sent by the authenticating user.
* <br>This method calls http://api.fanfou.com/direct_messages/sent.format
*
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<DirectMessage> getSentDirectMessages() throws
HttpException {
return DirectMessage.constructDirectMessages(get(getBaseURL() +
"direct_messages/sent.json", null, true));
}
/**
* Returns a list of the direct messages sent by the authenticating user.
* <br>This method calls http://api.fanfou.com/direct_messages/sent.format
*
* @param paging controls pagination
* @return List 默认返回20条, 一次最多返回60条
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<DirectMessage> getSentDirectMessages(Paging paging) throws
HttpException {
return DirectMessage.constructDirectMessages(get(getBaseURL() +
"direct_messages/sent.json", null, paging, true));
}
/* 收藏功能 */
/**
* Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format.
* @return List<Status>
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<Status> getFavorites() throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "favorites.json", createParams(), true));
}
public List<Status> getFavorites(Paging paging) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "favorites.json", createParams(), paging, true));
}
/**
* Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format.
*
* @param page the number of page
* @return List<Status>
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<Status> getFavorites(int page) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "favorites.json", "page", String.valueOf(page), true));
}
/**
* Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format.
*
* @param id the ID or screen name of the user for whom to request a list of favorite statuses
* @return List<Status>
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<Status> getFavorites(String id) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "favorites/" + id + ".json", createParams(), true));
}
/**
* Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format.
*
* @param id the ID or screen name of the user for whom to request a list of favorite statuses
* @param page the number of page
* @return List<Status>
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getFavorites(String id, int page) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "favorites/" + id + ".json", "page", String.valueOf(page), true));
}
public List<Status> getFavorites(String id, Paging paging) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "favorites/" + id + ".json", null, paging, true));
}
/**
* Favorites the status specified in the ID parameter as the authenticating user. Returns the favorite status when successful.
*
* @param id the ID of the status to favorite
* @return Status
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public Status createFavorite(String id) throws HttpException {
return new Status(http.post(getBaseURL() + "favorites/create/" + id + ".json", true));
}
/**
* Un-favorites the status specified in the ID parameter as the authenticating user. Returns the un-favorited status in the requested format when successful.
*
* @param id the ID of the status to un-favorite
* @return Status
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public Status destroyFavorite(String id) throws HttpException {
return new Status(http.post(getBaseURL() + "favorites/destroy/" + id + ".json", true));
}
/**
* Enables notifications for updates from the specified user to the authenticating user. Returns the specified user when successful.
* @param id String
* @return User
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @deprecated 饭否该功能暂时关闭, 等待该功能开放.
*/
public User enableNotification(String id) throws HttpException {
return new User(http.post(getBaseURL() + "notifications/follow/" + id + ".json", true).asJSONObject());
}
/**
* Disables notifications for updates from the specified user to the authenticating user. Returns the specified user when successful.
* @param id String
* @return User
* @throws HttpException when Weibo service or network is unavailable
* @deprecated 饭否该功能暂时关闭, 等待该功能开放.
* @since fanfoudroid 0.5.0
*/
public User disableNotification(String id) throws HttpException {
return new User(http.post(getBaseURL() + "notifications/leave/" + id + ".json", true).asJSONObject());
}
/* 黑名单 */
/**
* Blocks the user specified in the ID parameter as the authenticating user. Returns the blocked user in the requested format when successful.
* @param id the ID or screen_name of the user to block
* @return the blocked user
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public User createBlock(String id) throws HttpException {
return new User(http.post(getBaseURL() + "blocks/create/" + id + ".json", true).asJSONObject());
}
/**
* Un-blocks the user specified in the ID parameter as the authenticating user. Returns the un-blocked user in the requested format when successful.
* @param id the ID or screen_name of the user to block
* @return the unblocked user
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public User destroyBlock(String id) throws HttpException {
return new User(http.post(getBaseURL() + "blocks/destroy/" + id + ".json", true).asJSONObject());
}
/**
* Tests if a friendship exists between two users.
* @param id The ID or screen_name of the potentially blocked user.
* @return if the authenticating user is blocking a target user
* @throws HttpException when Weibo service or network is unavailable
* @deprecated 饭否暂无此功能, 期待此功能
* @since fanfoudroid 0.5.0
*/
public boolean existsBlock(String id) throws HttpException {
try{
return -1 == get(getBaseURL() + "blocks/exists/" + id + ".json", true).
asString().indexOf("<error>You are not blocking this user.</error>");
}catch(HttpException te){
if(te.getStatusCode() == 404){
return false;
}
throw te;
}
}
/**
* Returns a list of user objects that the authenticating user is blocking.
* @return a list of user objects that the authenticating user
* @throws HttpException when Weibo service or network is unavailable
* @deprecated 饭否暂无此功能, 期待此功能
* @since fanfoudroid 0.5.0
*/
public List<User> getBlockingUsers() throws
HttpException {
return User.constructUsers(get(getBaseURL() +
"blocks/blocking.json", true));
}
/**
* Returns a list of user objects that the authenticating user is blocking.
* @param page the number of page
* @return a list of user objects that the authenticating user
* @throws HttpException when Weibo service or network is unavailable
* @deprecated 饭否暂无此功能, 期待此功能
* @since fanfoudroid 0.5.0
*/
public List<User> getBlockingUsers(int page) throws
HttpException {
return User.constructUsers(get(getBaseURL() +
"blocks/blocking.json?page=" + page, true));
}
/**
* Returns an array of numeric user ids the authenticating user is blocking.
* @return Returns an array of numeric user ids the authenticating user is blocking.
* @throws HttpException when Weibo service or network is unavailable
* @deprecated 饭否暂无此功能, 期待此功能
* @since fanfoudroid 0.5.0
*/
public IDs getBlockingUsersIDs() throws HttpException {
return new IDs(get(getBaseURL() + "blocks/blocking/ids.json", true),this);
}
/* 好友关系方法 */
/**
* Tests if a friendship exists between two users.
*
* @param userA The ID or screen_name of the first user to test friendship for.
* @param userB The ID or screen_name of the second user to test friendship for.
* @return if a friendship exists between two users.
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public boolean existsFriendship(String userA, String userB) throws HttpException {
return -1 != get(getBaseURL() + "friendships/exists.json", "user_a", userA, "user_b", userB, true).
asString().indexOf("true");
}
/**
* Discontinues friendship with the user specified in the ID parameter as the authenticating user. Returns the un-friended user in the requested format when successful. Returns a string describing the failure condition when unsuccessful.
*
* @param id the ID or screen name of the user for whom to request a list of friends
* @return User
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public User destroyFriendship(String id) throws HttpException {
return new User(http.post(getBaseURL() + "friendships/destroy/" + id + ".json", createParams(), true).asJSONObject());
}
/**
* Befriends the user specified in the ID parameter as the authenticating user. Returns the befriended user in the requested format when successful. Returns a string describing the failure condition when unsuccessful.
*
* @param id the ID or screen name of the user to be befriended
* @return the befriended user
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public User createFriendship(String id) throws HttpException {
return new User(http.post(getBaseURL() + "friendships/create/" + id + ".json", createParams(), true).asJSONObject());
}
/**
* Returns an array of numeric IDs for every user the specified user is followed by.
* @param userId Specifies the ID of the user for whom to return the followers list.
* @param cursor Specifies the page number of the results beginning at 1. A single page contains 5000 ids. This is recommended for users with large ID lists. If not provided all ids are returned.
* @return The ID or screen_name of the user to retrieve the friends ID list for.
* @throws HttpException when Weibo service or network is unavailable
* @since Weibo4J 2.0.10
* @see <a href="http://open.t.sina.com.cn/wiki/index.php/Followers/ids">followers/ids </a>
*/
public IDs getFollowersIDs(String userId) throws HttpException {
return new IDs(get(getBaseURL() + "followers/ids.json?user_id=" + userId, true), this);
}
/**
* Returns an array of numeric IDs for every user the specified user is followed by.
* @param cursor Specifies the page number of the results beginning at 1. A single page contains 5000 ids. This is recommended for users with large ID lists. If not provided all ids are returned.
* @return The ID or screen_name of the user to retrieve the friends ID list for.
* @throws HttpException when Weibo service or network is unavailable
* @since Weibo4J 2.0.10
* @see <a href="http://open.t.sina.com.cn/wiki/index.php/Followers/ids">followers/ids </a>
*/
public IDs getFollowersIDs() throws HttpException {
return new IDs(get(getBaseURL() + "followers/ids.json", true), this);
}
public List<com.ch_linghu.fanfoudroid.fanfou.User> getFollowersList(String userId,Paging paging) throws HttpException{
return User.constructUsers(get(getBaseURL() + "users/followers.json",
createParams(new BasicNameValuePair("id", userId)),paging, false));
}
public List<com.ch_linghu.fanfoudroid.fanfou.User> getFollowersList(String userId) throws HttpException{
return User.constructUsers(get(getBaseURL() + "users/followers.json",
createParams(new BasicNameValuePair("id", userId)), false));
}
/**
* Returns an array of numeric IDs for every user the authenticating user is following.
* @return an array of numeric IDs for every user the authenticating user is following
* @throws HttpException when Weibo service or network is unavailable
* @since androidroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public IDs getFriendsIDs() throws HttpException {
return getFriendsIDs(-1l);
}
/**
* Returns an array of numeric IDs for every user the authenticating user is following.
* <br/>饭否无cursor参数
*
* @param cursor Specifies the page number of the results beginning at 1. A single page contains 5000 ids. This is recommended for users with large ID lists. If not provided all ids are returned.
* @return an array of numeric IDs for every user the authenticating user is following
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public IDs getFriendsIDs(long cursor) throws HttpException {
return new IDs(get(getBaseURL() + "friends/ids.json?cursor=" + cursor, true), this);
}
/**
* 获取关注者id列表
* @param userId
* @return
* @throws HttpException
*/
public IDs getFriendsIDs(String userId) throws HttpException{
return new IDs(get(getBaseURL() + "friends/ids.json?id=" +userId , true), this);
}
/* 账户方法 */
/**
* Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful; returns a 401 status code and an error message if not. Use this method to test if supplied user credentials are valid.
* 注意: 如果使用 错误的用户名/密码 多次登录后,饭否会锁IP
* 返回提示为“尝试次数过多,请去 http://fandou.com 登录“,且需输入验证码
*
* 登录成功返回 200 code
* 登录失败返回 401 code
* 使用HttpException的getStatusCode取得code
*
* @return user
* @since androidroid 0.5.0
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public User verifyCredentials() throws HttpException {
return new User(get(getBaseURL() + "account/verify_credentials.json"
, true).asJSONObject());
}
/* Saved Searches Methods */
/**
* Returns the authenticated user's saved search queries.
* @return Returns an array of numeric user ids the authenticating user is blocking.
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public List<SavedSearch> getSavedSearches() throws HttpException {
return SavedSearch.constructSavedSearches(get(getBaseURL() + "saved_searches.json", true));
}
/**
* Retrieve the data for a saved search owned by the authenticating user specified by the given id.
* @param id The id of the saved search to be retrieved.
* @return the data for a saved search
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public SavedSearch showSavedSearch(int id) throws HttpException {
return new SavedSearch(get(getBaseURL() + "saved_searches/show/" + id
+ ".json", true));
}
/**
* Retrieve the data for a saved search owned by the authenticating user specified by the given id.
* @return the data for a created saved search
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public SavedSearch createSavedSearch(String query) throws HttpException {
return new SavedSearch(http.post(getBaseURL() + "saved_searches/create.json",
createParams(new BasicNameValuePair("query", query)), true));
}
/**
* Destroys a saved search for the authenticated user. The search specified by id must be owned by the authenticating user.
* @param id The id of the saved search to be deleted.
* @return the data for a destroyed saved search
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public SavedSearch destroySavedSearch(int id) throws HttpException {
return new SavedSearch(http.post(getBaseURL() + "saved_searches/destroy/" + id
+ ".json", true));
}
/* Help Methods */
/**
* Returns the string "ok" in the requested format with a 200 OK HTTP status code.
* @return true if the API is working
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public boolean test() throws HttpException {
return -1 != get(getBaseURL() + "help/test.json", false).
asString().indexOf("ok");
}
/***************** API METHOD END *********************/
private SimpleDateFormat format = new SimpleDateFormat(
"EEE, d MMM yyyy HH:mm:ss z", Locale.US);
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Weibo weibo = (Weibo) o;
if (!baseURL.equals(weibo.baseURL)) return false;
if (!format.equals(weibo.format)) return false;
if (!http.equals(weibo.http)) return false;
if (!searchBaseURL.equals(weibo.searchBaseURL)) return false;
if (!source.equals(weibo.source)) return false;
return true;
}
@Override
public int hashCode() {
int result = http.hashCode();
result = 31 * result + baseURL.hashCode();
result = 31 * result + searchBaseURL.hashCode();
result = 31 * result + source.hashCode();
result = 31 * result + format.hashCode();
return result;
}
@Override
public String toString() {
return "Weibo{" +
"http=" + http +
", baseURL='" + baseURL + '\'' +
", searchBaseURL='" + searchBaseURL + '\'' +
", source='" + source + '\'' +
", format=" + format +
'}';
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing one single status of a user.
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class Status extends WeiboResponse implements java.io.Serializable {
private static final long serialVersionUID = 1608000492860584608L;
private Date createdAt;
private String id;
private String text;
private String source;
private boolean isTruncated;
private String inReplyToStatusId;
private String inReplyToUserId;
private boolean isFavorited;
private String inReplyToScreenName;
private double latitude = -1;
private double longitude = -1;
private String thumbnail_pic;
private String bmiddle_pic;
private String original_pic;
private String photo_url;
private RetweetDetails retweetDetails;
private User user = null;
/*package*/Status(Response res, Weibo weibo) throws HttpException {
super(res);
Element elem = res.asDocument().getDocumentElement();
init(res, elem, weibo);
}
/*package*/Status(Response res, Element elem, Weibo weibo) throws
HttpException {
super(res);
init(res, elem, weibo);
}
Status(Response res)throws HttpException{
super(res);
JSONObject json=res.asJSONObject();
try {
id = json.getString("id");
text = json.getString("text");
source = json.getString("source");
createdAt = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
inReplyToStatusId = getString("in_reply_to_status_id", json);
inReplyToUserId = getString("in_reply_to_user_id", json);
isFavorited = getBoolean("favorited", json);
// System.out.println("json photo" + json.getJSONObject("photo"));
if(!json.isNull("photo")) {
// System.out.println("not null" + json.getJSONObject("photo"));
Photo photo = new Photo(json.getJSONObject("photo"));
thumbnail_pic = photo.getThumbnail_pic();
bmiddle_pic = photo.getBmiddle_pic();
original_pic = photo.getOriginal_pic();
} else {
// System.out.println("Null");
thumbnail_pic = "";
bmiddle_pic = "";
original_pic = "";
}
if(!json.isNull("user"))
user = new User(json.getJSONObject("user"));
inReplyToScreenName=json.getString("in_reply_to_screen_name");
if(!json.isNull("retweetDetails")){
retweetDetails = new RetweetDetails(json.getJSONObject("retweetDetails"));
}
} catch (JSONException je) {
throw new HttpException(je.getMessage() + ":" + json.toString(), je);
}
}
/* modify by sycheng add some field*/
public Status(JSONObject json)throws HttpException, JSONException{
id = json.getString("id");
text = json.getString("text");
source = json.getString("source");
createdAt = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
isFavorited = getBoolean("favorited", json);
isTruncated=getBoolean("truncated", json);
inReplyToStatusId = getString("in_reply_to_status_id", json);
inReplyToUserId = getString("in_reply_to_user_id", json);
inReplyToScreenName=json.getString("in_reply_to_screen_name");
if(!json.isNull("photo")) {
Photo photo = new Photo(json.getJSONObject("photo"));
thumbnail_pic = photo.getThumbnail_pic();
bmiddle_pic = photo.getBmiddle_pic();
original_pic = photo.getOriginal_pic();
} else {
thumbnail_pic = "";
bmiddle_pic = "";
original_pic = "";
}
user = new User(json.getJSONObject("user"));
}
public Status(String str) throws HttpException, JSONException {
// StatusStream uses this constructor
super();
JSONObject json = new JSONObject(str);
id = json.getString("id");
text = json.getString("text");
source = json.getString("source");
createdAt = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
inReplyToStatusId = getString("in_reply_to_status_id", json);
inReplyToUserId = getString("in_reply_to_user_id", json);
isFavorited = getBoolean("favorited", json);
if(!json.isNull("photo")) {
Photo photo = new Photo(json.getJSONObject("photo"));
thumbnail_pic = photo.getThumbnail_pic();
bmiddle_pic = photo.getBmiddle_pic();
original_pic = photo.getOriginal_pic();
} else {
thumbnail_pic = "";
bmiddle_pic = "";
original_pic = "";
}
user = new User(json.getJSONObject("user"));
}
private void init(Response res, Element elem, Weibo weibo) throws
HttpException {
ensureRootNodeNameIs("status", elem);
user = new User(res, (Element) elem.getElementsByTagName("user").item(0)
, weibo);
id = getChildString("id", elem);
text = getChildText("text", elem);
source = getChildText("source", elem);
createdAt = getChildDate("created_at", elem);
isTruncated = getChildBoolean("truncated", elem);
inReplyToStatusId = getChildString("in_reply_to_status_id", elem);
inReplyToUserId = getChildString("in_reply_to_user_id", elem);
isFavorited = getChildBoolean("favorited", elem);
inReplyToScreenName = getChildText("in_reply_to_screen_name", elem);
NodeList georssPoint = elem.getElementsByTagName("georss:point");
if(1 == georssPoint.getLength()){
String[] point = georssPoint.item(0).getFirstChild().getNodeValue().split(" ");
if(!"null".equals(point[0]))
latitude = Double.parseDouble(point[0]);
if(!"null".equals(point[1]))
longitude = Double.parseDouble(point[1]);
}
NodeList retweetDetailsNode = elem.getElementsByTagName("retweet_details");
if(1 == retweetDetailsNode.getLength()){
retweetDetails = new RetweetDetails(res,(Element)retweetDetailsNode.item(0),weibo);
}
}
/**
* Return the created_at
*
* @return created_at
* @since Weibo4J 1.1.0
*/
public Date getCreatedAt() {
return this.createdAt;
}
/**
* Returns the id of the status
*
* @return the id
*/
public String getId() {
return this.id;
}
/**
* Returns the text of the status
*
* @return the text
*/
public String getText() {
return this.text;
}
/**
* Returns the source
*
* @return the source
* @since Weibo4J 1.0.4
*/
public String getSource() {
return this.source;
}
/**
* Test if the status is truncated
*
* @return true if truncated
* @since Weibo4J 1.0.4
*/
public boolean isTruncated() {
return isTruncated;
}
/**
* Returns the in_reply_tostatus_id
*
* @return the in_reply_tostatus_id
* @since Weibo4J 1.0.4
*/
public String getInReplyToStatusId() {
return inReplyToStatusId;
}
/**
* Returns the in_reply_user_id
*
* @return the in_reply_tostatus_id
* @since Weibo4J 1.0.4
*/
public String getInReplyToUserId() {
return inReplyToUserId;
}
/**
* Returns the in_reply_to_screen_name
*
* @return the in_in_reply_to_screen_name
* @since Weibo4J 2.0.4
*/
public String getInReplyToScreenName() {
return inReplyToScreenName;
}
/**
* returns The location's latitude that this tweet refers to.
*
* @since Weibo4J 2.0.10
*/
public double getLatitude() {
return latitude;
}
/**
* returns The location's longitude that this tweet refers to.
*
* @since Weibo4J 2.0.10
*/
public double getLongitude() {
return longitude;
}
/**
* Test if the status is favorited
*
* @return true if favorited
* @since Weibo4J 1.0.4
*/
public boolean isFavorited() {
return isFavorited;
}
public String getThumbnail_pic() {
return thumbnail_pic;
}
public String getBmiddle_pic() {
return bmiddle_pic;
}
public String getOriginal_pic() {
return original_pic;
}
/**
* Return the user
*
* @return the user
*/
public User getUser() {
return user;
}
// TODO: 等合并Tweet, Status
public int getType() {
return -1111111;
}
/**
*
* @since Weibo4J 2.0.10
*/
public boolean isRetweet(){
return null != retweetDetails;
}
/**
*
* @since Weibo4J 2.0.10
*/
public RetweetDetails getRetweetDetails() {
return retweetDetails;
}
/*package*/
static List<Status> constructStatuses(Response res,
Weibo weibo) throws HttpException {
Document doc = res.asDocument();
if (isRootNodeNilClasses(doc)) {
return new ArrayList<Status>(0);
} else {
try {
ensureRootNodeNameIs("statuses", doc);
NodeList list = doc.getDocumentElement().getElementsByTagName(
"status");
int size = list.getLength();
List<Status> statuses = new ArrayList<Status>(size);
for (int i = 0; i < size; i++) {
Element status = (Element) list.item(i);
statuses.add(new Status(res, status, weibo));
}
return statuses;
} catch (HttpException te) {
ensureRootNodeNameIs("nil-classes", doc);
return new ArrayList<Status>(0);
}
}
}
/* modify by sycheng add json call method */
/* package */
static List<Status> constructStatuses(Response res) throws HttpException {
try {
JSONArray list = res.asJSONArray();
int size = list.length();
List<Status> statuses = new ArrayList<Status>(size);
for (int i = 0; i < size; i++) {
statuses.add(new Status(list.getJSONObject(i)));
}
return statuses;
} catch (JSONException jsone) {
throw new HttpException(jsone);
} catch (HttpException te) {
throw te;
}
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public boolean equals(Object obj) {
if (null == obj) {
return false;
}
if (this == obj) {
return true;
}
// return obj instanceof Status && ((Status) obj).id == this.id;
return obj instanceof Status && this.id.equals(((Status) obj).id);
}
@Override
public String toString() {
return "Status{" +
"createdAt=" + createdAt +
", id=" + id +
", text='" + text + '\'' +
", source='" + source + '\'' +
", isTruncated=" + isTruncated +
", inReplyToStatusId=" + inReplyToStatusId +
", inReplyToUserId=" + inReplyToUserId +
", isFavorited=" + isFavorited +
", thumbnail_pic=" + thumbnail_pic +
", bmiddle_pic=" + bmiddle_pic +
", original_pic=" + original_pic +
", inReplyToScreenName='" + inReplyToScreenName + '\'' +
", latitude=" + latitude +
", longitude=" + longitude +
", retweetDetails=" + retweetDetails +
", user=" + user +
'}';
}
public boolean isEmpty() {
return (null == id);
}
}
| Java |
package com.ch_linghu.fanfoudroid.fanfou;
/**
* An exception class that will be thrown when WeiboAPI calls are failed.<br>
* In case the Fanfou server returned HTTP error code, you can get the HTTP status code using getStatusCode() method.
*/
public class WeiboException extends Exception {
private int statusCode = -1;
private static final long serialVersionUID = -2623309261327598087L;
public WeiboException(String msg) {
super(msg);
}
public WeiboException(Exception cause) {
super(cause);
}
public WeiboException(String msg, int statusCode) {
super(msg);
this.statusCode = statusCode;
}
public WeiboException(String msg, Exception cause) {
super(msg, cause);
}
public WeiboException(String msg, Exception cause, int statusCode) {
super(msg, cause);
this.statusCode = statusCode;
}
public int getStatusCode() {
return this.statusCode;
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing a Saved Search
*
* @author Yusuke Yamamoto - yusuke at mac.com
* @since Weibo4J 2.0.8
*/
public class SavedSearch extends WeiboResponse {
private Date createdAt;
private String query;
private int position;
private String name;
private int id;
private static final long serialVersionUID = 3083819860391598212L;
/*package*/ SavedSearch(Response res) throws HttpException {
super(res);
init(res.asJSONObject());
}
/*package*/ SavedSearch(Response res, JSONObject json) throws HttpException {
super(res);
init(json);
}
/*package*/ SavedSearch(JSONObject savedSearch) throws HttpException {
init(savedSearch);
}
/*package*/ static List<SavedSearch> constructSavedSearches(Response res) throws HttpException {
JSONArray json = res.asJSONArray();
List<SavedSearch> savedSearches;
try {
savedSearches = new ArrayList<SavedSearch>(json.length());
for(int i=0;i<json.length();i++){
savedSearches.add(new SavedSearch(res,json.getJSONObject(i)));
}
return savedSearches;
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + res.asString(), jsone);
}
}
private void init(JSONObject savedSearch) throws HttpException {
try {
createdAt = parseDate(savedSearch.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
query = getString("query", savedSearch, true);
name = getString("name", savedSearch, true);
id = getInt("id", savedSearch);
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + savedSearch.toString(), jsone);
}
}
public Date getCreatedAt() {
return createdAt;
}
public String getQuery() {
return query;
}
public int getPosition() {
return position;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof SavedSearch)) return false;
SavedSearch that = (SavedSearch) o;
if (id != that.id) return false;
if (position != that.position) return false;
if (!createdAt.equals(that.createdAt)) return false;
if (!name.equals(that.name)) return false;
if (!query.equals(that.query)) return false;
return true;
}
@Override
public int hashCode() {
int result = createdAt.hashCode();
result = 31 * result + query.hashCode();
result = 31 * result + position;
result = 31 * result + name.hashCode();
result = 31 * result + id;
return result;
}
@Override
public String toString() {
return "SavedSearch{" +
"createdAt=" + createdAt +
", query='" + query + '\'' +
", position=" + position +
", name='" + name + '\'' +
", id=" + id +
'}';
}
}
| Java |
/*
Copyright (c) 2007-2009
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import org.apache.http.message.BasicNameValuePair;
/**
* A data class represents search query.
*/
public class Query {
private String query = null;
private String lang = null;
private int rpp = -1;
private int page = -1;
private long sinceId = -1;
private String maxId = null;
private String geocode = null;
public Query(){
}
public Query(String query){
this.query = query;
}
public String getQuery() {
return query;
}
/**
* Sets the query string
* @param query - the query string
*/
public void setQuery(String query) {
this.query = query;
}
public String getLang() {
return lang;
}
/**
* restricts tweets to the given language, given by an <a href="http://en.wikipedia.org/wiki/ISO_639-1">ISO 639-1 code</a>
* @param lang an <a href="http://en.wikipedia.org/wiki/ISO_639-1">ISO 639-1 code</a>
*/
public void setLang(String lang) {
this.lang = lang;
}
public int getRpp() {
return rpp;
}
/**
* sets the number of tweets to return per page, up to a max of 100
* @param rpp the number of tweets to return per page
*/
public void setRpp(int rpp) {
this.rpp = rpp;
}
public int getPage() {
return page;
}
/**
* sets the page number (starting at 1) to return, up to a max of roughly 1500 results
* @param page - the page number (starting at 1) to return
*/
public void setPage(int page) {
this.page = page;
}
public long getSinceId() {
return sinceId;
}
/**
* returns tweets with status ids greater than the given id.
* @param sinceId - returns tweets with status ids greater than the given id
*/
public void setSinceId(long sinceId) {
this.sinceId = sinceId;
}
public String getMaxId() {
return maxId;
}
/**
* returns tweets with status ids less than the given id.
* @param maxId - returns tweets with status ids less than the given id
*/
public void setMaxId(String maxId) {
this.maxId = maxId;
}
public String getGeocode() {
return geocode;
}
public static final String MILES = "mi";
public static final String KILOMETERS = "km";
/**
* returns tweets by users located within a given radius of the given latitude/longitude, where the user's location is taken from their Weibo profile
* @param latitude latitude
* @param longtitude longtitude
* @param radius radius
* @param unit Query.MILES or Query.KILOMETERS
*/
public void setGeoCode(double latitude, double longtitude, double radius
, String unit) {
this.geocode = latitude + "," + longtitude + "," + radius + unit;
}
public ArrayList<BasicNameValuePair> asPostParameters(){
ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
appendParameter("q", query, params);
appendParameter("lang", lang, params);
appendParameter("page", page, params);
appendParameter("since_id",sinceId , params);
appendParameter("max_id", maxId, params);
appendParameter("geocode", geocode, params);
return params;
}
private void appendParameter(String name, String value, ArrayList<BasicNameValuePair> params) {
if (null != value) {
params.add(new BasicNameValuePair(name, value));
}
}
private void appendParameter(String name, long value, ArrayList<BasicNameValuePair> params) {
if (0 <= value) {
params.add(new BasicNameValuePair(name, value + ""));
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Query query1 = (Query) o;
if (page != query1.page) return false;
if (rpp != query1.rpp) return false;
if (sinceId != query1.sinceId) return false;
if (geocode != null ? !geocode.equals(query1.geocode) : query1.geocode != null)
return false;
if (lang != null ? !lang.equals(query1.lang) : query1.lang != null)
return false;
if (query != null ? !query.equals(query1.query) : query1.query != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = query != null ? query.hashCode() : 0;
result = 31 * result + (lang != null ? lang.hashCode() : 0);
result = 31 * result + rpp;
result = 31 * result + page;
result = 31 * result + (int) (sinceId ^ (sinceId >>> 32));
result = 31 * result + (geocode != null ? geocode.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Query{" +
"query='" + query + '\'' +
", lang='" + lang + '\'' +
", rpp=" + rpp +
", page=" + page +
", sinceId=" + sinceId +
", geocode='" + geocode + '\'' +
'}';
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.ch_linghu.fanfoudroid.http.HTMLEntity;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* Super class of Weibo Response objects.
*
* @see weibo4j.DirectMessage
* @see weibo4j.Status
* @see weibo4j.User
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class WeiboResponse implements java.io.Serializable {
private static Map<String,SimpleDateFormat> formatMap = new HashMap<String,SimpleDateFormat>();
private static final long serialVersionUID = 3519962197957449562L;
private transient int rateLimitLimit = -1;
private transient int rateLimitRemaining = -1;
private transient long rateLimitReset = -1;
public WeiboResponse() {
}
public WeiboResponse(Response res) {
}
protected static void ensureRootNodeNameIs(String rootName, Element elem) throws HttpException {
if (!rootName.equals(elem.getNodeName())) {
throw new HttpException("Unexpected root node name:" + elem.getNodeName() + ". Expected:" + rootName + ". Check the availability of the Weibo API at http://open.t.sina.com.cn/.");
}
}
protected static void ensureRootNodeNameIs(String[] rootNames, Element elem) throws HttpException {
String actualRootName = elem.getNodeName();
for (String rootName : rootNames) {
if (rootName.equals(actualRootName)) {
return;
}
}
String expected = "";
for (int i = 0; i < rootNames.length; i++) {
if (i != 0) {
expected += " or ";
}
expected += rootNames[i];
}
throw new HttpException("Unexpected root node name:" + elem.getNodeName() + ". Expected:" + expected + ". Check the availability of the Weibo API at http://open.t.sina.com.cn/.");
}
protected static void ensureRootNodeNameIs(String rootName, Document doc) throws HttpException {
Element elem = doc.getDocumentElement();
if (!rootName.equals(elem.getNodeName())) {
throw new HttpException("Unexpected root node name:" + elem.getNodeName() + ". Expected:" + rootName + ". Check the availability of the Weibo API at http://open.t.sina.com.cn/");
}
}
protected static boolean isRootNodeNilClasses(Document doc) {
String root = doc.getDocumentElement().getNodeName();
return "nil-classes".equals(root) || "nilclasses".equals(root);
}
protected static String getChildText( String str, Element elem ) {
return HTMLEntity.unescape(getTextContent(str,elem));
}
protected static String getTextContent(String str, Element elem){
NodeList nodelist = elem.getElementsByTagName(str);
if (nodelist.getLength() > 0) {
Node node = nodelist.item(0).getFirstChild();
if (null != node) {
String nodeValue = node.getNodeValue();
return null != nodeValue ? nodeValue : "";
}
}
return "";
}
/*modify by sycheng add "".equals(str) */
protected static int getChildInt(String str, Element elem) {
String str2 = getTextContent(str, elem);
if (null == str2 || "".equals(str2)||"null".equals(str)) {
return -1;
} else {
return Integer.valueOf(str2);
}
}
/*modify by sycheng add "".equals(str) */
protected static String getChildString(String str, Element elem) {
String str2 = getTextContent(str, elem);
if (null == str2 || "".equals(str2)||"null".equals(str)) {
return "";
} else {
return String.valueOf(str2);
}
}
protected static long getChildLong(String str, Element elem) {
String str2 = getTextContent(str, elem);
if (null == str2 || "".equals(str2)||"null".equals(str)) {
return -1;
} else {
return Long.valueOf(str2);
}
}
protected static String getString(String name, JSONObject json, boolean decode) {
String returnValue = null;
try {
returnValue = json.getString(name);
if (decode) {
try {
returnValue = URLDecoder.decode(returnValue, "UTF-8");
} catch (UnsupportedEncodingException ignore) {
}
}
} catch (JSONException ignore) {
// refresh_url could be missing
}
return returnValue;
}
protected static boolean getChildBoolean(String str, Element elem) {
String value = getTextContent(str, elem);
return Boolean.valueOf(value);
}
protected static Date getChildDate(String str, Element elem) throws HttpException {
return getChildDate(str, elem, "EEE MMM d HH:mm:ss z yyyy");
}
protected static Date getChildDate(String str, Element elem, String format) throws HttpException {
return parseDate(getChildText(str, elem),format);
}
protected static Date parseDate(String str, String format) throws HttpException{
if(str==null||"".equals(str)){
return null;
}
SimpleDateFormat sdf = formatMap.get(format);
if (null == sdf) {
sdf = new SimpleDateFormat(format, Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
formatMap.put(format, sdf);
}
try {
synchronized(sdf){
// SimpleDateFormat is not thread safe
return sdf.parse(str);
}
} catch (ParseException pe) {
throw new HttpException("Unexpected format(" + str + ") returned from sina.com.cn");
}
}
protected static int getInt(String key, JSONObject json) throws JSONException {
String str = json.getString(key);
if(null == str || "".equals(str)||"null".equals(str)){
return -1;
}
return Integer.parseInt(str);
}
protected static String getString(String key, JSONObject json) throws JSONException {
String str = json.getString(key);
if(null == str || "".equals(str)||"null".equals(str)){
return "";
}
return String.valueOf(str);
}
protected static long getLong(String key, JSONObject json) throws JSONException {
String str = json.getString(key);
if(null == str || "".equals(str)||"null".equals(str)){
return -1;
}
return Long.parseLong(str);
}
protected static boolean getBoolean(String key, JSONObject json) throws JSONException {
String str = json.getString(key);
if(null == str || "".equals(str)||"null".equals(str)){
return false;
}
return Boolean.valueOf(str);
}
public int getRateLimitLimit() {
return rateLimitLimit;
}
public int getRateLimitRemaining() {
return rateLimitRemaining;
}
public long getRateLimitReset() {
return rateLimitReset;
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.database.Cursor;
import android.util.Log;
import com.ch_linghu.fanfoudroid.db.MessageTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.db.UserInfoTable;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing Basic user information element
*/
public class User extends WeiboResponse implements java.io.Serializable {
static final String[] POSSIBLE_ROOT_NAMES = new String[]{"user", "sender", "recipient", "retweeting_user"};
private Weibo weibo;
private String id;
private String name;
private String screenName;
private String location;
private String description;
private String birthday;
private String gender;
private String profileImageUrl;
private String url;
private boolean isProtected;
private int followersCount;
private Date statusCreatedAt;
private String statusId = "";
private String statusText = null;
private String statusSource = null;
private boolean statusTruncated = false;
private String statusInReplyToStatusId = "";
private String statusInReplyToUserId = "";
private boolean statusFavorited = false;
private String statusInReplyToScreenName = null;
private String profileBackgroundColor;
private String profileTextColor;
private String profileLinkColor;
private String profileSidebarFillColor;
private String profileSidebarBorderColor;
private int friendsCount;
private Date createdAt;
private int favouritesCount;
private int utcOffset;
private String timeZone;
private String profileBackgroundImageUrl;
private String profileBackgroundTile;
private boolean following;
private boolean notificationEnabled;
private int statusesCount;
private boolean geoEnabled;
private boolean verified;
private static final long serialVersionUID = -6345893237975349030L;
/*package*/User(Response res, Weibo weibo) throws HttpException {
super(res);
Element elem = res.asDocument().getDocumentElement();
init(elem, weibo);
}
/*package*/public User(Response res, Element elem, Weibo weibo) throws HttpException {
super(res);
init(elem, weibo);
}
/*package*/public User(JSONObject json) throws HttpException {
super();
init(json);
}
/*package*/User(Response res) throws HttpException {
super();
init(res.asJSONObject());
}
User(){
}
private void init(JSONObject json) throws HttpException {
try {
id = json.getString("id");
name = json.getString("name");
screenName = json.getString("screen_name");
location = json.getString("location");
gender = json.getString("gender");
birthday = json.getString("birthday");
description = json.getString("description");
profileImageUrl = json.getString("profile_image_url");
url = json.getString("url");
isProtected = json.getBoolean("protected");
followersCount = json.getInt("followers_count");
profileBackgroundColor = json.getString("profile_background_color");
profileTextColor = json.getString("profile_text_color");
profileLinkColor = json.getString("profile_link_color");
profileSidebarFillColor = json.getString("profile_sidebar_fill_color");
profileSidebarBorderColor = json.getString("profile_sidebar_border_color");
friendsCount = json.getInt("friends_count");
createdAt = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
favouritesCount = json.getInt("favourites_count");
utcOffset = getInt("utc_offset", json);
// timeZone = json.getString("time_zone");
profileBackgroundImageUrl = json.getString("profile_background_image_url");
profileBackgroundTile = json.getString("profile_background_tile");
following = getBoolean("following", json);
notificationEnabled = getBoolean("notifications", json);
statusesCount = json.getInt("statuses_count");
if (!json.isNull("status")) {
JSONObject status = json.getJSONObject("status");
statusCreatedAt = parseDate(status.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
statusId = status.getString("id");
statusText = status.getString("text");
statusSource = status.getString("source");
statusTruncated = status.getBoolean("truncated");
// statusInReplyToStatusId = status.getString("in_reply_to_status_id");
statusInReplyToStatusId = status.getString("in_reply_to_lastmsg_id"); // 饭否不知为什么把这个参数的名称改了
statusInReplyToUserId = status.getString("in_reply_to_user_id");
statusFavorited = status.getBoolean("favorited");
statusInReplyToScreenName = status.getString("in_reply_to_screen_name");
}
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + json.toString(), jsone);
}
}
private void init(Element elem, Weibo weibo) throws HttpException {
this.weibo = weibo;
ensureRootNodeNameIs(POSSIBLE_ROOT_NAMES, elem);
id = getChildString("id", elem);
name = getChildText("name", elem);
screenName = getChildText("screen_name", elem);
location = getChildText("location", elem);
description = getChildText("description", elem);
profileImageUrl = getChildText("profile_image_url", elem);
url = getChildText("url", elem);
isProtected = getChildBoolean("protected", elem);
followersCount = getChildInt("followers_count", elem);
profileBackgroundColor = getChildText("profile_background_color", elem);
profileTextColor = getChildText("profile_text_color", elem);
profileLinkColor = getChildText("profile_link_color", elem);
profileSidebarFillColor = getChildText("profile_sidebar_fill_color", elem);
profileSidebarBorderColor = getChildText("profile_sidebar_border_color", elem);
friendsCount = getChildInt("friends_count", elem);
createdAt = getChildDate("created_at", elem);
favouritesCount = getChildInt("favourites_count", elem);
utcOffset = getChildInt("utc_offset", elem);
// timeZone = getChildText("time_zone", elem);
profileBackgroundImageUrl = getChildText("profile_background_image_url", elem);
profileBackgroundTile = getChildText("profile_background_tile", elem);
following = getChildBoolean("following", elem);
notificationEnabled = getChildBoolean("notifications", elem);
statusesCount = getChildInt("statuses_count", elem);
geoEnabled = getChildBoolean("geo_enabled", elem);
verified = getChildBoolean("verified", elem);
NodeList statuses = elem.getElementsByTagName("status");
if (statuses.getLength() != 0) {
Element status = (Element) statuses.item(0);
statusCreatedAt = getChildDate("created_at", status);
statusId = getChildString("id", status);
statusText = getChildText("text", status);
statusSource = getChildText("source", status);
statusTruncated = getChildBoolean("truncated", status);
statusInReplyToStatusId = getChildString("in_reply_to_status_id", status);
statusInReplyToUserId = getChildString("in_reply_to_user_id", status);
statusFavorited = getChildBoolean("favorited", status);
statusInReplyToScreenName = getChildText("in_reply_to_screen_name", status);
}
}
/**
* Returns the id of the user
*
* @return the id of the user
*/
public String getId() {
return id;
}
/**
* Returns the name of the user
*
* @return the name of the user
*/
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public String getBirthday() {
return birthday;
}
/**
* Returns the screen name of the user
*
* @return the screen name of the user
*/
public String getScreenName() {
return screenName;
}
/**
* Returns the location of the user
*
* @return the location of the user
*/
public String getLocation() {
return location;
}
/**
* Returns the description of the user
*
* @return the description of the user
*/
public String getDescription() {
return description;
}
/**
* Returns the profile image url of the user
*
* @return the profile image url of the user
*/
public URL getProfileImageURL() {
try {
return new URL(profileImageUrl);
} catch (MalformedURLException ex) {
return null;
}
}
/**
* Returns the url of the user
*
* @return the url of the user
*/
public URL getURL() {
try {
return new URL(url);
} catch (MalformedURLException ex) {
return null;
}
}
/**
* Test if the user status is protected
*
* @return true if the user status is protected
*/
public boolean isProtected() {
return isProtected;
}
/**
* Returns the number of followers
*
* @return the number of followers
* @since Weibo4J 1.0.4
*/
public int getFollowersCount() {
return followersCount;
}
//TODO: uncomment
// public DirectMessage sendDirectMessage(String text) throws WeiboException {
// return weibo.sendDirectMessage(this.getName(), text);
// }
public static List<User> constructUsers(Response res, Weibo weibo) throws HttpException {
Document doc = res.asDocument();
if (isRootNodeNilClasses(doc)) {
return new ArrayList<User>(0);
} else {
try {
ensureRootNodeNameIs("users", doc);
// NodeList list = doc.getDocumentElement().getElementsByTagName(
// "user");
// int size = list.getLength();
// List<User> users = new ArrayList<User>(size);
// for (int i = 0; i < size; i++) {
// users.add(new User(res, (Element) list.item(i), weibo));
// }
//去除掉嵌套的bug
NodeList list=doc.getDocumentElement().getChildNodes();
List<User> users = new ArrayList<User>(list.getLength());
Node node;
for(int i=0;i<list.getLength();i++){
node=list.item(i);
if(node.getNodeName().equals("user")){
users.add(new User(res, (Element) node, weibo));
}
}
return users;
} catch (HttpException te) {
if (isRootNodeNilClasses(doc)) {
return new ArrayList<User>(0);
} else {
throw te;
}
}
}
}
public static UserWapper constructWapperUsers(Response res, Weibo weibo) throws HttpException {
Document doc = res.asDocument();
if (isRootNodeNilClasses(doc)) {
return new UserWapper(new ArrayList<User>(0), 0, 0);
} else {
try {
ensureRootNodeNameIs("users_list", doc);
Element root = doc.getDocumentElement();
NodeList user = root.getElementsByTagName("users");
int length = user.getLength();
if (length == 0) {
return new UserWapper(new ArrayList<User>(0), 0, 0);
}
//
Element listsRoot = (Element) user.item(0);
NodeList list=listsRoot.getChildNodes();
List<User> users = new ArrayList<User>(list.getLength());
Node node;
for(int i=0;i<list.getLength();i++){
node=list.item(i);
if(node.getNodeName().equals("user")){
users.add(new User(res, (Element) node, weibo));
}
}
//
long previousCursor = getChildLong("previous_curosr", root);
long nextCursor = getChildLong("next_curosr", root);
if (nextCursor == -1) { // 兼容不同标签名称
nextCursor = getChildLong("nextCurosr", root);
}
return new UserWapper(users, previousCursor, nextCursor);
} catch (HttpException te) {
if (isRootNodeNilClasses(doc)) {
return new UserWapper(new ArrayList<User>(0), 0, 0);
} else {
throw te;
}
}
}
}
public static List<User> constructUsers(Response res) throws HttpException {
try {
JSONArray list = res.asJSONArray();
int size = list.length();
List<User> users = new ArrayList<User>(size);
for (int i = 0; i < size; i++) {
users.add(new User(list.getJSONObject(i)));
}
return users;
} catch (JSONException jsone) {
throw new HttpException(jsone);
} catch (HttpException te) {
throw te;
}
}
/**
*
* @param res
* @return
* @throws HttpException
*/
public static UserWapper constructWapperUsers(Response res) throws HttpException {
JSONObject jsonUsers = res.asJSONObject(); //asJSONArray();
try {
JSONArray user = jsonUsers.getJSONArray("users");
int size = user.length();
List<User> users = new ArrayList<User>(size);
for (int i = 0; i < size; i++) {
users.add(new User(user.getJSONObject(i)));
}
long previousCursor = jsonUsers.getLong("previous_curosr");
long nextCursor = jsonUsers.getLong("next_cursor");
if (nextCursor == -1) { // 兼容不同标签名称
nextCursor = jsonUsers.getLong("nextCursor");
}
return new UserWapper(users, previousCursor, nextCursor);
} catch (JSONException jsone) {
throw new HttpException(jsone);
}
}
/**
* @param res
* @return
* @throws HttpException
*/
static List<User> constructResult(Response res) throws HttpException {
JSONArray list = res.asJSONArray();
try {
int size = list.length();
List<User> users = new ArrayList<User>(size);
for (int i = 0; i < size; i++) {
users.add(new User(list.getJSONObject(i)));
}
return users;
} catch (JSONException e) {
}
return null;
}
/**
* @return created_at or null if the user is protected
* @since Weibo4J 1.1.0
*/
public Date getStatusCreatedAt() {
return statusCreatedAt;
}
/**
*
* @return status id or -1 if the user is protected
*/
public String getStatusId() {
return statusId;
}
/**
*
* @return status text or null if the user is protected
*/
public String getStatusText() {
return statusText;
}
/**
*
* @return source or null if the user is protected
* @since 1.1.4
*/
public String getStatusSource() {
return statusSource;
}
/**
*
* @return truncated or false if the user is protected
* @since 1.1.4
*/
public boolean isStatusTruncated() {
return statusTruncated;
}
/**
*
* @return in_reply_to_status_id or -1 if the user is protected
* @since 1.1.4
*/
public String getStatusInReplyToStatusId() {
return statusInReplyToStatusId;
}
/**
*
* @return in_reply_to_user_id or -1 if the user is protected
* @since 1.1.4
*/
public String getStatusInReplyToUserId() {
return statusInReplyToUserId;
}
/**
*
* @return favorited or false if the user is protected
* @since 1.1.4
*/
public boolean isStatusFavorited() {
return statusFavorited;
}
/**
*
* @return in_reply_to_screen_name or null if the user is protected
* @since 1.1.4
*/
public String getStatusInReplyToScreenName() {
return "" != statusInReplyToUserId ? statusInReplyToScreenName : null;
}
public String getProfileBackgroundColor() {
return profileBackgroundColor;
}
public String getProfileTextColor() {
return profileTextColor;
}
public String getProfileLinkColor() {
return profileLinkColor;
}
public String getProfileSidebarFillColor() {
return profileSidebarFillColor;
}
public String getProfileSidebarBorderColor() {
return profileSidebarBorderColor;
}
public int getFriendsCount() {
return friendsCount;
}
public Date getCreatedAt() {
return createdAt;
}
public int getFavouritesCount() {
return favouritesCount;
}
public int getUtcOffset() {
return utcOffset;
}
public String getTimeZone() {
return timeZone;
}
public String getProfileBackgroundImageUrl() {
return profileBackgroundImageUrl;
}
public String getProfileBackgroundTile() {
return profileBackgroundTile;
}
/**
*
*/
public boolean isFollowing() {
return following;
}
/**
* @deprecated use isNotificationsEnabled() instead
*/
public boolean isNotifications() {
return notificationEnabled;
}
/**
*
* @since Weibo4J 2.0.1
*/
public boolean isNotificationEnabled() {
return notificationEnabled;
}
public int getStatusesCount() {
return statusesCount;
}
/**
* @return the user is enabling geo location
* @since Weibo4J 2.0.10
*/
public boolean isGeoEnabled() {
return geoEnabled;
}
/**
* @return returns true if the user is a verified celebrity
* @since Weibo4J 2.0.10
*/
public boolean isVerified() {
return verified;
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public boolean equals(Object obj) {
if (null == obj) {
return false;
}
if (this == obj) {
return true;
}
return obj instanceof User && ((User) obj).id.equals(this.id);
}
@Override
public String toString() {
return "User{" +
"weibo=" + weibo +
", id=" + id +
", name='" + name + '\'' +
", screenName='" + screenName + '\'' +
", location='" + location + '\'' +
", description='" + description + '\'' +
", profileImageUrl='" + profileImageUrl + '\'' +
", url='" + url + '\'' +
", isProtected=" + isProtected +
", followersCount=" + followersCount +
", statusCreatedAt=" + statusCreatedAt +
", statusId=" + statusId +
", statusText='" + statusText + '\'' +
", statusSource='" + statusSource + '\'' +
", statusTruncated=" + statusTruncated +
", statusInReplyToStatusId=" + statusInReplyToStatusId +
", statusInReplyToUserId=" + statusInReplyToUserId +
", statusFavorited=" + statusFavorited +
", statusInReplyToScreenName='" + statusInReplyToScreenName + '\'' +
", profileBackgroundColor='" + profileBackgroundColor + '\'' +
", profileTextColor='" + profileTextColor + '\'' +
", profileLinkColor='" + profileLinkColor + '\'' +
", profileSidebarFillColor='" + profileSidebarFillColor + '\'' +
", profileSidebarBorderColor='" + profileSidebarBorderColor + '\'' +
", friendsCount=" + friendsCount +
", createdAt=" + createdAt +
", favouritesCount=" + favouritesCount +
", utcOffset=" + utcOffset +
// ", timeZone='" + timeZone + '\'' +
", profileBackgroundImageUrl='" + profileBackgroundImageUrl + '\'' +
", profileBackgroundTile='" + profileBackgroundTile + '\'' +
", following=" + following +
", notificationEnabled=" + notificationEnabled +
", statusesCount=" + statusesCount +
", geoEnabled=" + geoEnabled +
", verified=" + verified +
'}';
}
//TODO:增加从游标解析User的方法,用于和data里User转换一条数据
public static User parseUser(Cursor cursor){
if (null == cursor || 0 == cursor.getCount()||cursor.getCount()>1) {
Log.w("User.ParseUser", "Cann't parse Cursor, bacause cursor is null or empty.");
}
cursor.moveToFirst();
User u=new User();
u.id = cursor.getString(cursor.getColumnIndex(UserInfoTable._ID));
u.name = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_USER_NAME));
u.screenName = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_USER_SCREEN_NAME));
u.location = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_LOCALTION));
u.description = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_DESCRIPTION));
u.profileImageUrl = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_PROFILE_IMAGE_URL));
u.url = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_URL));
u.isProtected = (0 == cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_PROTECTED))) ? false : true;
u.followersCount = cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_FOLLOWERS_COUNT));
u.friendsCount = cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_FRIENDS_COUNT));
u.favouritesCount = cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_FAVORITES_COUNT));
u.statusesCount = cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_STATUSES_COUNT));
u.following = (0 == cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_FOLLOWING))) ? false : true;
try {
String createAtStr=cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_CREATED_AT));
if(createAtStr!=null){
u.createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(createAtStr);
}
} catch (ParseException e) {
Log.w("User", "Invalid created at data.");
}
return u;
}
public com.ch_linghu.fanfoudroid.data.User parseUser(){
com.ch_linghu.fanfoudroid.data.User user=new com.ch_linghu.fanfoudroid.data.User();
user.id=this.id;
user.name=this.name;
user.screenName=this.screenName;
user.location=this.location;
user.description=this.description;
user.profileImageUrl=this.profileImageUrl;
user.url=this.url;
user.isProtected=this.isProtected;
user.followersCount=this.followersCount;
user.friendsCount=this.friendsCount;
user.favoritesCount=this.favouritesCount;
user.statusesCount=this.statusesCount;
user.isFollowing=this.following;
user.createdAt = this.createdAt;
return user;
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import org.json.JSONException;
import org.json.JSONObject;
/**
* A data class representing Treand.
*
* @author Yusuke Yamamoto - yusuke at mac.com
* @since Weibo4J 2.0.2
*/
public class Trend implements java.io.Serializable{
private String name;
private String url = null;
private String query = null;
private static final long serialVersionUID = 1925956704460743946L;
public Trend(JSONObject json) throws JSONException {
this.name = json.getString("name");
if (!json.isNull("url")) {
this.url = json.getString("url");
}
if (!json.isNull("query")) {
this.query = json.getString("query");
}
}
public String getName() {
return name;
}
public String getUrl() {
return url;
}
public String getQuery() {
return query;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Trend)) return false;
Trend trend = (Trend) o;
if (!name.equals(trend.name)) return false;
if (query != null ? !query.equals(trend.query) : trend.query != null)
return false;
if (url != null ? !url.equals(trend.url) : trend.url != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + (url != null ? url.hashCode() : 0);
result = 31 * result + (query != null ? query.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Trend{" +
"name='" + name + '\'' +
", url='" + url + '\'' +
", query='" + query + '\'' +
'}';
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing one single retweet details.
*
* @author Yusuke Yamamoto - yusuke at mac.com
* @since Weibo4J 2.0.10
*/
public class RetweetDetails extends WeiboResponse implements
java.io.Serializable {
private long retweetId;
private Date retweetedAt;
private User retweetingUser;
static final long serialVersionUID = 1957982268696560598L;
public RetweetDetails(Response res, Weibo weibo) throws HttpException {
super(res);
Element elem = res.asDocument().getDocumentElement();
init(res, elem, weibo);
}
public RetweetDetails(JSONObject json) throws HttpException {
super();
init(json);
}
private void init(JSONObject json) throws HttpException{
try {
retweetId = json.getInt("retweetId");
retweetedAt = parseDate(json.getString("retweetedAt"), "EEE MMM dd HH:mm:ss z yyyy");
retweetingUser=new User(json.getJSONObject("retweetingUser"));
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + json.toString(), jsone);
}
}
/*package*/public RetweetDetails(Response res, Element elem, Weibo weibo) throws
HttpException {
super(res);
init(res, elem, weibo);
}
private void init(Response res, Element elem, Weibo weibo) throws
HttpException {
ensureRootNodeNameIs("retweet_details", elem);
retweetId = getChildLong("retweet_id", elem);
retweetedAt = getChildDate("retweeted_at", elem);
retweetingUser = new User(res, (Element) elem.getElementsByTagName("retweeting_user").item(0)
, weibo);
}
public long getRetweetId() {
return retweetId;
}
public Date getRetweetedAt() {
return retweetedAt;
}
public User getRetweetingUser() {
return retweetingUser;
}
/*modify by sycheng add json*/
/*package*/
static List<RetweetDetails> createRetweetDetails(Response res) throws HttpException {
try {
JSONArray list = res.asJSONArray();
int size = list.length();
List<RetweetDetails> retweets = new ArrayList<RetweetDetails>(size);
for (int i = 0; i < size; i++) {
retweets.add(new RetweetDetails(list.getJSONObject(i)));
}
return retweets;
} catch (JSONException jsone) {
throw new HttpException(jsone);
} catch (HttpException te) {
throw te;
}
}
/*package*/
static List<RetweetDetails> createRetweetDetails(Response res,
Weibo weibo) throws HttpException {
Document doc = res.asDocument();
if (isRootNodeNilClasses(doc)) {
return new ArrayList<RetweetDetails>(0);
} else {
try {
ensureRootNodeNameIs("retweets", doc);
NodeList list = doc.getDocumentElement().getElementsByTagName(
"retweet_details");
int size = list.getLength();
List<RetweetDetails> statuses = new ArrayList<RetweetDetails>(size);
for (int i = 0; i < size; i++) {
Element status = (Element) list.item(i);
statuses.add(new RetweetDetails(res, status, weibo));
}
return statuses;
} catch (HttpException te) {
ensureRootNodeNameIs("nil-classes", doc);
return new ArrayList<RetweetDetails>(0);
}
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof RetweetDetails)) return false;
RetweetDetails that = (RetweetDetails) o;
return retweetId == that.retweetId;
}
@Override
public int hashCode() {
int result = (int) (retweetId ^ (retweetId >>> 32));
result = 31 * result + retweetedAt.hashCode();
result = 31 * result + retweetingUser.hashCode();
return result;
}
@Override
public String toString() {
return "RetweetDetails{" +
"retweetId=" + retweetId +
", retweetedAt=" + retweetedAt +
", retweetingUser=" + retweetingUser +
'}';
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing sent/received direct message.
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class DirectMessage extends WeiboResponse implements java.io.Serializable {
private String id;
private String text;
private String sender_id;
private String recipient_id;
private Date created_at;
private String sender_screen_name;
private String recipient_screen_name;
private static final long serialVersionUID = -3253021825891789737L;
/*package*/DirectMessage(Response res, Weibo weibo) throws HttpException {
super(res);
init(res, res.asDocument().getDocumentElement(), weibo);
}
/*package*/DirectMessage(Response res, Element elem, Weibo weibo) throws HttpException {
super(res);
init(res, elem, weibo);
}
/*modify by sycheng add json call*/
/*package*/DirectMessage(JSONObject json) throws HttpException {
try {
id = json.getString("id");
text = json.getString("text");
sender_id = json.getString("sender_id");
recipient_id = json.getString("recipient_id");
created_at = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
sender_screen_name = json.getString("sender_screen_name");
recipient_screen_name = json.getString("recipient_screen_name");
if(!json.isNull("sender"))
sender = new User(json.getJSONObject("sender"));
if(!json.isNull("recipient"))
recipient = new User(json.getJSONObject("recipient"));
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + json.toString(), jsone);
}
}
private void init(Response res, Element elem, Weibo weibo) throws HttpException{
ensureRootNodeNameIs("direct_message", elem);
sender = new User(res, (Element) elem.getElementsByTagName("sender").item(0),
weibo);
recipient = new User(res, (Element) elem.getElementsByTagName("recipient").item(0),
weibo);
id = getChildString("id", elem);
text = getChildText("text", elem);
sender_id = getChildString("sender_id", elem);
recipient_id = getChildString("recipient_id", elem);
created_at = getChildDate("created_at", elem);
sender_screen_name = getChildText("sender_screen_name", elem);
recipient_screen_name = getChildText("recipient_screen_name", elem);
}
public String getId() {
return id;
}
public String getText() {
return text;
}
public String getSenderId() {
return sender_id;
}
public String getRecipientId() {
return recipient_id;
}
/**
* @return created_at
* @since Weibo4J 1.1.0
*/
public Date getCreatedAt() {
return created_at;
}
public String getSenderScreenName() {
return sender_screen_name;
}
public String getRecipientScreenName() {
return recipient_screen_name;
}
private User sender;
public User getSender() {
return sender;
}
private User recipient;
public User getRecipient() {
return recipient;
}
/*package*/
static List<DirectMessage> constructDirectMessages(Response res,
Weibo weibo) throws HttpException {
Document doc = res.asDocument();
if (isRootNodeNilClasses(doc)) {
return new ArrayList<DirectMessage>(0);
} else {
try {
ensureRootNodeNameIs("direct-messages", doc);
NodeList list = doc.getDocumentElement().getElementsByTagName(
"direct_message");
int size = list.getLength();
List<DirectMessage> messages = new ArrayList<DirectMessage>(size);
for (int i = 0; i < size; i++) {
Element status = (Element) list.item(i);
messages.add(new DirectMessage(res, status, weibo));
}
return messages;
} catch (HttpException te) {
if (isRootNodeNilClasses(doc)) {
return new ArrayList<DirectMessage>(0);
} else {
throw te;
}
}
}
}
/*package*/
static List<DirectMessage> constructDirectMessages(Response res
) throws HttpException {
JSONArray list= res.asJSONArray();
try {
int size = list.length();
List<DirectMessage> messages = new ArrayList<DirectMessage>(size);
for (int i = 0; i < size; i++) {
messages.add(new DirectMessage(list.getJSONObject(i)));
}
return messages;
} catch (JSONException jsone) {
throw new HttpException(jsone);
}
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public boolean equals(Object obj) {
if (null == obj) {
return false;
}
if (this == obj) {
return true;
}
return obj instanceof DirectMessage && ((DirectMessage) obj).id.equals(this.id);
}
@Override
public String toString() {
return "DirectMessage{" +
"id=" + id +
", text='" + text + '\'' +
", sender_id=" + sender_id +
", recipient_id=" + recipient_id +
", created_at=" + created_at +
", sender_screen_name='" + sender_screen_name + '\'' +
", recipient_screen_name='" + recipient_screen_name + '\'' +
", sender=" + sender +
", recipient=" + recipient +
'}';
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import org.json.JSONException;
import org.json.JSONObject;
import com.ch_linghu.fanfoudroid.http.HttpException;
/**
* A data class representing Basic user information element
*/
public class Photo extends WeiboResponse implements java.io.Serializable {
private Weibo weibo;
private String thumbnail_pic;
private String bmiddle_pic;
private String original_pic;
private boolean verified;
private static final long serialVersionUID = -6345893237975349030L;
public Photo(JSONObject json) throws HttpException {
super();
init(json);
}
private void init(JSONObject json) throws HttpException {
try {
//System.out.println(json);
thumbnail_pic = json.getString("thumburl");
bmiddle_pic = json.getString("imageurl");
original_pic = json.getString("largeurl");
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + json.toString(), jsone);
}
}
public String getThumbnail_pic() {
return thumbnail_pic;
}
public void setThumbnail_pic(String thumbnail_pic) {
this.thumbnail_pic = thumbnail_pic;
}
public String getBmiddle_pic() {
return bmiddle_pic;
}
public void setBmiddle_pic(String bmiddle_pic) {
this.bmiddle_pic = bmiddle_pic;
}
public String getOriginal_pic() {
return original_pic;
}
public void setOriginal_pic(String original_pic) {
this.original_pic = original_pic;
}
@Override
public String toString() {
return "Photo [thumbnail_pic=" + thumbnail_pic + ", bmiddle_pic="
+ bmiddle_pic + ", original_pic=" + original_pic + "]";
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Element;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing Weibo rate limit status
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class RateLimitStatus extends WeiboResponse {
private int remainingHits;
private int hourlyLimit;
private int resetTimeInSeconds;
private Date resetTime;
private static final long serialVersionUID = 933996804168952707L;
/* package */ RateLimitStatus(Response res) throws HttpException {
super(res);
Element elem = res.asDocument().getDocumentElement();
remainingHits = getChildInt("remaining-hits", elem);
hourlyLimit = getChildInt("hourly-limit", elem);
resetTimeInSeconds = getChildInt("reset-time-in-seconds", elem);
resetTime = getChildDate("reset-time", elem, "EEE MMM d HH:mm:ss z yyyy");
}
/*modify by sycheng add json call*/
/* package */ RateLimitStatus(Response res,Weibo w) throws HttpException {
super(res);
JSONObject json= res.asJSONObject();
try {
remainingHits = json.getInt("remaining_hits");
hourlyLimit = json.getInt("hourly_limit");
resetTimeInSeconds = json.getInt("reset_time_in_seconds");
resetTime = parseDate(json.getString("reset_time"), "EEE MMM dd HH:mm:ss z yyyy");
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + json.toString(), jsone);
}
}
public int getRemainingHits() {
return remainingHits;
}
public int getHourlyLimit() {
return hourlyLimit;
}
public int getResetTimeInSeconds() {
return resetTimeInSeconds;
}
/**
*
* @deprecated use getResetTime() instead
*/
@Deprecated
public Date getDateTime() {
return resetTime;
}
/**
* @since Weibo4J 2.0.9
*/
public Date getResetTime() {
return resetTime;
}
@Override
public String toString() {
StringBuilder sb=new StringBuilder();
sb.append("RateLimitStatus{remainingHits:");
sb.append(remainingHits);
sb.append(";hourlyLimit:");
sb.append(hourlyLimit);
sb.append(";resetTimeInSeconds:");
sb.append(resetTimeInSeconds);
sb.append(";resetTime:");
sb.append(resetTime);
sb.append("}");
return sb.toString();
}
}
| Java |
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.List;
import android.database.Cursor;
import android.os.Bundle;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity;
/**
* 随便看看
*
* @author jmx
*
*/
public class BrowseActivity extends TwitterCursorBaseActivity {
private static final String TAG = "BrowseActivity";
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState)) {
mNavbar.setHeaderTitle(getActivityTitle());
getTweetList().removeFooterView(mListFooter); // 随便看看没有获取更多功能
return true;
} else {
return false;
}
}
@Override
protected String getActivityTitle() {
return getResources().getString(R.string.page_title_browse);
}
@Override
public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) {
return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_BROWSE,
isUnread);
}
@Override
public String fetchMaxId() {
return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_BROWSE);
}
@Override
protected Cursor fetchMessages() {
return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_BROWSE);
}
@Override
public List<Status> getMessageSinceId(String maxId) throws HttpException {
return getApi().getPublicTimeline();
}
@Override
protected void markAllRead() {
getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_BROWSE);
}
@Override
public String fetchMinId() {
// 随便看看没有获取更多的功能
return null;
}
@Override
public List<Status> getMoreMessageFromId(String minId) throws HttpException {
// 随便看看没有获取更多的功能
return null;
}
@Override
public int getDatabaseType() {
return StatusTable.TYPE_BROWSE;
}
@Override
public String getUserId() {
return TwitterApplication.getMyselfId();
}
}
| Java |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.app.ImageManager;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.http.HttpClient;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.ui.module.TweetEdit;
import com.ch_linghu.fanfoudroid.util.FileHelper;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class WriteActivity extends BaseActivity {
// FIXME: for debug, delete me
private long startTime = -1;
private long endTime = -1;
public static final String NEW_TWEET_ACTION = "com.ch_linghu.fanfoudroid.NEW";
public static final String REPLY_TWEET_ACTION = "com.ch_linghu.fanfoudroid.REPLY";
public static final String REPOST_TWEET_ACTION = "com.ch_linghu.fanfoudroid.REPOST";
public static final String EXTRA_REPLY_TO_NAME = "reply_to_name";
public static final String EXTRA_REPLY_ID = "reply_id";
public static final String EXTRA_REPOST_ID = "repost_status_id";
private static final String TAG = "WriteActivity";
private static final String SIS_RUNNING_KEY = "running";
private static final String PREFS_NAME = "com.ch_linghu.fanfoudroid";
private static final int REQUEST_IMAGE_CAPTURE = 2;
private static final int REQUEST_PHOTO_LIBRARY = 3;
// View
private TweetEdit mTweetEdit;
private EditText mTweetEditText;
private TextView mProgressText;
private ImageButton mLocationButton;
private ImageButton chooseImagesButton;
private ImageButton mCameraButton;
private ProgressDialog dialog;
private NavBar mNavbar;
// Picture
private boolean withPic=false ;
private File mFile;
private ImageView mPreview;
private ImageView imageDelete;
private static final int MAX_BITMAP_SIZE = 400;
private File mImageFile;
private Uri mImageUri;
// Task
private GenericTask mSendTask;
private TaskListener mSendTaskListener = new TaskAdapter() {
@Override
public void onPreExecute(GenericTask task) {
onSendBegin();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
endTime = System.currentTimeMillis();
Log.d("LDS", "Sended a status in " + (endTime - startTime));
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
onSendSuccess();
} else if (result == TaskResult.IO_ERROR) {
onSendFailure();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return "SendTask";
}
};
private String _reply_id;
private String _repost_id;
private String _reply_to_name;
// sub menu
protected void openImageCaptureMenu() {
try {
// TODO: API < 1.6, images size too small
mImageFile = new File(FileHelper.getBasePath(), "upload.jpg");
mImageUri = Uri.fromFile(mImageFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
protected void openPhotoLibraryMenu() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_PHOTO_LIBRARY);
}
/**
* @deprecated 已废弃, 分解成两个按钮
*/
protected void createInsertPhotoDialog() {
final CharSequence[] items = {
getString(R.string.write_label_take_a_picture),
getString(R.string.write_label_choose_a_picture) };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.write_label_insert_picture));
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch (item) {
case 0:
openImageCaptureMenu();
break;
case 1:
openPhotoLibraryMenu();
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaColumns.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void getPic(Intent intent, Uri uri) {
// layout for picture mode
changeStyleWithPic();
withPic = true;
mFile = null;
mImageUri = uri;
if (uri.getScheme().equals("content")) {
mFile = new File(getRealPathFromURI(mImageUri));
} else {
mFile = new File(mImageUri.getPath());
}
// TODO:想将图片放在EditText左边
mPreview.setImageBitmap(createThumbnailBitmap(mImageUri,
MAX_BITMAP_SIZE));
if (mFile == null) {
updateProgress("Could not locate picture file. Sorry!");
disableEntry();
}
}
private File bitmapToFile(Bitmap bitmap) {
try {
File file = new File(FileHelper.getBasePath(), "upload.jpg");
FileOutputStream out = new FileOutputStream(file);
if (bitmap.compress(Bitmap.CompressFormat.JPEG,
ImageManager.DEFAULT_COMPRESS_QUALITY, out)) {
out.flush();
out.close();
}
return file;
} catch (FileNotFoundException e) {
Log.e(TAG, "Sorry, the file can not be created. " + e.getMessage());
return null;
} catch (IOException e) {
Log.e(TAG,
"IOException occurred when save upload file. "
+ e.getMessage());
return null;
}
}
private void changeStyleWithPic() {
// 修改布局 ,以前 图片居中,现在在左边
// mPreview.setLayoutParams(
// new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,
// LayoutParams.FILL_PARENT)
// );
mPreview.setVisibility(View.VISIBLE);
imageDelete.setVisibility(View.VISIBLE);
mTweetEditText.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 2f));
}
/**
* 制作微缩图
*
* @param uri
* @param size
* @return
*/
private Bitmap createThumbnailBitmap(Uri uri, int size) {
InputStream input = null;
try {
input = getContentResolver().openInputStream(uri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(input, null, options);
input.close();
// Compute the scale.
int scale = 1;
while ((options.outWidth / scale > size)
|| (options.outHeight / scale > size)) {
scale *= 2;
}
options.inJustDecodeBounds = false;
options.inSampleSize = scale;
input = getContentResolver().openInputStream(uri);
return BitmapFactory.decodeStream(input, null, options);
} catch (IOException e) {
Log.w(TAG, e);
return null;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
Log.w(TAG, e);
}
}
}
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)) {
// init View
setContentView(R.layout.write);
mNavbar = new NavBar(NavBar.HEADER_STYLE_WRITE, this);
// Intent & Action & Extras
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
Bundle extras = intent.getExtras();
String text = null;
Uri uri = null;
if (extras != null) {
String subject = extras.getString(Intent.EXTRA_SUBJECT);
text = extras.getString(Intent.EXTRA_TEXT);
uri = (Uri) (extras.get(Intent.EXTRA_STREAM));
if (!TextUtils.isEmpty(subject)) {
text = subject + " " + text;
}
if ((type != null && type.startsWith("text")) && uri != null) {
text = text + " " + uri.toString();
uri = null;
}
}
_reply_id = null;
_repost_id = null;
_reply_to_name = null;
// View
mProgressText = (TextView) findViewById(R.id.progress_text);
mTweetEditText = (EditText) findViewById(R.id.tweet_edit);
// TODO: @某人-- 类似饭否自动补全
ImageButton mAddUserButton = (ImageButton) findViewById(R.id.add_user);
mAddUserButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int start = mTweetEditText.getSelectionStart();
int end = mTweetEditText.getSelectionEnd();
mTweetEditText.getText().replace(Math.min(start, end),
Math.max(start, end), "@");
}
});
// 插入图片
chooseImagesButton = (ImageButton) findViewById(R.id.choose_images_button);
chooseImagesButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "chooseImagesButton onClick");
openPhotoLibraryMenu();
}
});
// 打开相机
mCameraButton = (ImageButton) findViewById(R.id.camera_button);
mCameraButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "mCameraButton onClick");
openImageCaptureMenu();
}
});
// With picture
imageDelete = (ImageView) findViewById(R.id.image_delete);
imageDelete.setOnClickListener(deleteListener);
mPreview = (ImageView) findViewById(R.id.preview);
if (Intent.ACTION_SEND.equals(intent.getAction()) && uri != null) {
getPic(intent, uri);
}
// Update status
mTweetEdit = new TweetEdit(mTweetEditText,
(TextView) findViewById(R.id.chars_text));
if (TwitterApplication.mPref.getBoolean(Preferences.USE_ENTER_SEND, false)){
mTweetEdit.setOnKeyListener(tweetEnterHandler);
}
mTweetEdit.addTextChangedListener(new MyTextWatcher(
WriteActivity.this));
if (NEW_TWEET_ACTION.equals(action) || Intent.ACTION_SEND.equals(action)){
if (!TextUtils.isEmpty(text)){
//始终将光标置于最末尾,以方便回复消息时保持@用户在最前面
EditText inputField = mTweetEdit.getEditText();
inputField.setTextKeepState(text);
Editable etext = inputField.getText();
int position = etext.length();
Selection.setSelection(etext, position);
}
}else if (REPLY_TWEET_ACTION.equals(action)) {
_reply_id = intent.getStringExtra(EXTRA_REPLY_ID);
_reply_to_name = intent.getStringExtra(EXTRA_REPLY_TO_NAME);
if (!TextUtils.isEmpty(text)){
String reply_to_name = "@"+_reply_to_name + " ";
String other_replies = "";
for (String mention : TextHelper.getMentions(text)){
//获取名字时不包括自己和回复对象
if (!mention.equals(TwitterApplication.getMyselfName()) &&
!mention.equals(_reply_to_name)){
other_replies += "@"+mention+" ";
}
}
EditText inputField = mTweetEdit.getEditText();
inputField.setTextKeepState(reply_to_name + other_replies);
//将除了reply_to_name的其他名字默认选中
Editable etext = inputField.getText();
int start = reply_to_name.length();
int stop = etext.length();
Selection.setSelection(etext, start, stop);
}
}else if (REPOST_TWEET_ACTION.equals(action)) {
if (!TextUtils.isEmpty(text)){
// 如果是转发消息,则根据用户习惯,将光标放置在转发消息的头部或尾部
SharedPreferences prefereces = getPreferences();
boolean isAppendToTheBeginning = prefereces.getBoolean(
Preferences.RT_INSERT_APPEND, true);
EditText inputField = mTweetEdit.getEditText();
inputField.setTextKeepState(text);
Editable etext = inputField.getText();
int position = (isAppendToTheBeginning) ? 0 : etext.length();
Selection.setSelection(etext, position);
}
}
mLocationButton = (ImageButton) findViewById(R.id.location_button);
mLocationButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(WriteActivity.this, "LBS地理定位功能开发中, 敬请期待",
Toast.LENGTH_SHORT).show();
}
});
Button mTopSendButton = (Button) findViewById(R.id.top_send_btn);
mTopSendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
doSend();
}
});
return true;
} else {
return false;
}
}
private View.OnClickListener deleteListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = getIntent();
intent.setAction(null);
withPic = false;
mPreview.setVisibility(View.INVISIBLE);
imageDelete.setVisibility(View.INVISIBLE);
}
};
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause.");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart.");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume.");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart.");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop.");
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mSendTask != null
&& mSendTask.getStatus() == GenericTask.Status.RUNNING) {
// Doesn't really cancel execution (we let it continue running).
// See the SendTask code for more details.
mSendTask.cancel(true);
}
// Don't need to cancel FollowersTask (assuming it ends properly).
if (dialog != null) {
dialog.dismiss();
}
super.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mSendTask != null
&& mSendTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
public static Intent createNewTweetIntent(String text) {
Intent intent = new Intent(NEW_TWEET_ACTION);
intent.putExtra(Intent.EXTRA_TEXT, text);
intent.putExtra(Intent.EXTRA_SUBJECT, "");
return intent;
}
public static Intent createNewReplyIntent(String tweetText, String screenName, String replyId) {
Intent intent = new Intent(WriteActivity.REPLY_TWEET_ACTION);
intent.putExtra(Intent.EXTRA_SUBJECT, "");
intent.putExtra(Intent.EXTRA_TEXT, TextHelper.getSimpleTweetText(tweetText));
intent.putExtra(WriteActivity.EXTRA_REPLY_TO_NAME, screenName);
intent.putExtra(WriteActivity.EXTRA_REPLY_ID, replyId);
return intent;
}
public static Intent createNewRepostIntent(Context content,
String tweetText, String screenName, String repostId) {
SharedPreferences mPreferences = PreferenceManager
.getDefaultSharedPreferences(content);
String prefix = mPreferences.getString(Preferences.RT_PREFIX_KEY,
content.getString(R.string.pref_rt_prefix_default));
String retweet = " " + prefix + " @" + screenName + " "
+ TextHelper.getSimpleTweetText(tweetText);
Intent intent = new Intent(WriteActivity.REPOST_TWEET_ACTION);
intent.putExtra(Intent.EXTRA_SUBJECT, "");
intent.putExtra(Intent.EXTRA_TEXT, retweet);
intent.putExtra(WriteActivity.EXTRA_REPOST_ID, repostId);
return intent;
}
public static Intent createImageIntent(Activity activity, Uri uri) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, uri);
try {
WriteActivity writeActivity = (WriteActivity) activity;
intent.putExtra(Intent.EXTRA_TEXT,
writeActivity.mTweetEdit.getText());
intent.putExtra(WriteActivity.EXTRA_REPLY_TO_NAME,
writeActivity._reply_to_name);
intent.putExtra(WriteActivity.EXTRA_REPLY_ID,
writeActivity._reply_id);
intent.putExtra(WriteActivity.EXTRA_REPOST_ID,
writeActivity._repost_id);
} catch (ClassCastException e) {
// do nothing
}
return intent;
}
private class MyTextWatcher implements TextWatcher {
private WriteActivity _activity;
public MyTextWatcher(WriteActivity activity) {
_activity = activity;
}
@Override
public void afterTextChanged(Editable s) {
if (s.length() == 0) {
_activity._reply_id = null;
_activity._reply_to_name = null;
_activity._repost_id = null;
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
}
private View.OnKeyListener tweetEnterHandler = new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER
|| keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
if (event.getAction() == KeyEvent.ACTION_UP) {
WriteActivity t = (WriteActivity) (v.getContext());
doSend();
}
return true;
}
return false;
}
};
private void doSend() {
Log.d(TAG, "dosend "+withPic);
startTime = System.currentTimeMillis();
Log.d(TAG, String.format("doSend, reply_id=%s", _reply_id));
if (mSendTask != null
&& mSendTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
String status = mTweetEdit.getText().toString();
if (!TextUtils.isEmpty(status) || withPic) {
int mode = SendTask.TYPE_NORMAL;
if (withPic) {
mode = SendTask.TYPE_PHOTO;
} else if (null != _reply_id) {
mode = SendTask.TYPE_REPLY;
} else if (null != _repost_id) {
mode = SendTask.TYPE_REPOST;
}
mSendTask = new SendTask();
mSendTask.setListener(mSendTaskListener);
TaskParams params = new TaskParams();
params.put("mode", mode);
mSendTask.execute(params);
} else {
updateProgress(getString(R.string.page_text_is_null));
}
}
}
private class SendTask extends GenericTask {
public static final int TYPE_NORMAL = 0;
public static final int TYPE_REPLY = 1;
public static final int TYPE_REPOST = 2;
public static final int TYPE_PHOTO = 3;
@Override
protected TaskResult _doInBackground(TaskParams... params) {
TaskParams param = params[0];
try {
String status = mTweetEdit.getText().toString();
int mode = param.getInt("mode");
Log.d(TAG, "Send Status. Mode : " + mode);
// Send status in different way
switch (mode) {
case TYPE_REPLY:
// 增加容错性,即使reply_id为空依然允许发送
if (null == WriteActivity.this._reply_id) {
Log.e(TAG,
"Cann't send status in REPLY mode, reply_id is null");
}
getApi().updateStatus(status, WriteActivity.this._reply_id);
break;
case TYPE_REPOST:
// 增加容错性,即使repost_id为空依然允许发送
if (null == WriteActivity.this._repost_id) {
Log.e(TAG,
"Cann't send status in REPOST mode, repost_id is null");
}
getApi().repost(status, WriteActivity.this._repost_id);
break;
case TYPE_PHOTO:
if (null != mFile) {
// Compress image
try {
mFile = getImageManager().compressImage(mFile, 100);
//ImageManager.DEFAULT_COMPRESS_QUALITY);
} catch (IOException ioe) {
Log.e(TAG, "Cann't compress images.");
}
getApi().updateStatus(status, mFile);
} else {
Log.e(TAG,
"Cann't send status in PICTURE mode, photo is null");
}
break;
case TYPE_NORMAL:
default:
getApi().updateStatus(status); // just send a status
break;
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
if (e.getStatusCode() == HttpClient.NOT_AUTHORIZED) {
return TaskResult.AUTH_ERROR;
}
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
private ImageManager getImageManager() {
return TwitterApplication.mImageLoader.getImageManager();
}
}
private void onSendBegin() {
disableEntry();
dialog = ProgressDialog.show(WriteActivity.this, "",
getString(R.string.page_status_updating), true);
if (dialog != null) {
dialog.setCancelable(false);
}
updateProgress(getString(R.string.page_status_updating));
}
private void onSendSuccess() {
if (dialog != null) {
dialog.setMessage(getString(R.string.page_status_update_success));
dialog.dismiss();
}
_reply_id = null;
_repost_id = null;
updateProgress(getString(R.string.page_status_update_success));
enableEntry();
// FIXME: 不理解这段代码的含义,暂时注释掉
// try {
// Thread.currentThread();
// Thread.sleep(500);
// updateProgress("");
// } catch (InterruptedException e) {
// Log.d(TAG, e.getMessage());
// }
updateProgress("");
// 发送成功就自动关闭界面
finish();
// 关闭软键盘
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mTweetEdit.getEditText().getWindowToken(),
0);
}
private void onSendFailure() {
dialog.setMessage(getString(R.string.page_status_unable_to_update));
dialog.dismiss();
updateProgress(getString(R.string.page_status_unable_to_update));
enableEntry();
}
private void enableEntry() {
mTweetEdit.setEnabled(true);
mLocationButton.setEnabled(true);
chooseImagesButton.setEnabled(true);
}
private void disableEntry() {
mTweetEdit.setEnabled(false);
mLocationButton.setEnabled(false);
chooseImagesButton.setEnabled(false);
}
// UI helpers.
private void updateProgress(String progress) {
mProgressText.setText(progress);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Intent intent = WriteActivity.createImageIntent(this, mImageUri);
//照相完后不重新起一个WriteActivity
getPic(intent, mImageUri);
/*intent.setClass(this, WriteActivity.class);
startActivity(intent);
// 打开发送图片界面后将自身关闭
finish();*/
} else if (requestCode == REQUEST_PHOTO_LIBRARY
&& resultCode == RESULT_OK) {
mImageUri = data.getData();
Intent intent = WriteActivity.createImageIntent(this, mImageUri);
//选图片后不重新起一个WriteActivity
getPic(intent, mImageUri);
/*intent.setClass(this, WriteActivity.class);
startActivity(intent);
// 打开发送图片界面后将自身关闭
finish();*/
}
}
} | Java |
package com.ch_linghu.fanfoudroid;
import com.ch_linghu.fanfoudroid.app.Preferences;
import android.app.Activity;
import android.content.ComponentName;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AboutActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
if (TwitterApplication.mPref.getBoolean(
Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
//set real version
ComponentName comp = new ComponentName(this, getClass());
PackageInfo pinfo = null;
try {
pinfo = getPackageManager().getPackageInfo(comp.getPackageName(), 0);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TextView version = (TextView)findViewById(R.id.version);
version.setText(String.format("v %s", pinfo.versionName));
//bind button click event
Button okBtn = (Button)findViewById(R.id.ok_btn);
okBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
| Java |
package com.ch_linghu.fanfoudroid;
import java.util.HashSet;
//import org.acra.ReportingInteractionMode;
//import org.acra.annotation.ReportsCrashes;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.preference.PreferenceManager;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.fanfou.Configuration;
import com.ch_linghu.fanfoudroid.fanfou.User;
import com.ch_linghu.fanfoudroid.fanfou.Weibo;
import com.ch_linghu.fanfoudroid.http.HttpException;
//@ReportsCrashes(formKey="dHowMk5LMXQweVJkWGthb1E1T1NUUHc6MQ",
// mode = ReportingInteractionMode.NOTIFICATION,
// resNotifTickerText = R.string.crash_notif_ticker_text,
// resNotifTitle = R.string.crash_notif_title,
// resNotifText = R.string.crash_notif_text,
// resNotifIcon = android.R.drawable.stat_notify_error, // optional. default is a warning sign
// resDialogText = R.string.crash_dialog_text,
// resDialogIcon = android.R.drawable.ic_dialog_info, //optional. default is a warning sign
// resDialogTitle = R.string.crash_dialog_title, // optional. default is your application name
// resDialogCommentPrompt = R.string.crash_dialog_comment_prompt, // optional. when defined, adds a user text field input with this text resource as a label
// resDialogOkToast = R.string.crash_dialog_ok_toast // optional. displays a Toast message when the user accepts to send a report.
//)
public class TwitterApplication extends Application {
public static final String TAG = "TwitterApplication";
// public static ImageManager mImageManager;
public static LazyImageLoader mImageLoader;
public static TwitterDatabase mDb;
public static Weibo mApi; // new API
public static Context mContext;
public static SharedPreferences mPref;
public static int networkType = 0;
public final static boolean DEBUG = Configuration.getDebug();
// FIXME:获取登录用户id, 据肉眼观察,刚注册的用户系统分配id都是~开头的,因为不知道
// 用户何时去修改这个ID,目前只有把所有以~开头的ID在每次需要UserId时都去服务器
// 取一次数据,看看新的ID是否已经设定,判断依据是是否以~开头。这么判断会把有些用户
// 就是把自己ID设置的以~开头的造成,每次都需要去服务器取数。
// 只是简单处理了mPref没有CURRENT_USER_ID的情况,因为用户在登陆时,肯定会记一个CURRENT_USER_ID
// 到mPref.
private static void fetchMyselfInfo() {
User myself;
try {
myself = TwitterApplication.mApi.showUser(TwitterApplication.mApi.getUserId());
TwitterApplication.mPref.edit().putString(
Preferences.CURRENT_USER_ID, myself.getId()).commit();
TwitterApplication.mPref.edit().putString(
Preferences.CURRENT_USER_SCREEN_NAME, myself.getScreenName()).commit();
} catch (HttpException e) {
e.printStackTrace();
}
}
public static String getMyselfId() {
if (!mPref.contains(Preferences.CURRENT_USER_ID)
|| mPref.getString(Preferences.CURRENT_USER_ID, "~")
.startsWith("~")) {
fetchMyselfInfo();
}
return mPref.getString(Preferences.CURRENT_USER_ID, "~");
}
public static String getMyselfName() {
if (!mPref.contains(Preferences.CURRENT_USER_ID)
|| !mPref.contains(Preferences.CURRENT_USER_SCREEN_NAME)
|| mPref.getString(Preferences.CURRENT_USER_ID, "~")
.startsWith("~")) {
fetchMyselfInfo();
}
return mPref.getString(Preferences.CURRENT_USER_SCREEN_NAME, "");
}
@Override
public void onCreate() {
// FIXME: StrictMode类在1.6以下的版本中没有,会导致类加载失败。
// 因此将这些代码设成关闭状态,仅在做性能调试时才打开。
// //NOTE: StrictMode模式需要2.3+ API支持。
// if (DEBUG){
// StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
// .detectAll()
// .penaltyLog()
// .build());
// StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
// .detectAll()
// .penaltyLog()
// .build());
// }
super.onCreate();
mContext = this.getApplicationContext();
// mImageManager = new ImageManager(this);
mImageLoader = new LazyImageLoader();
mApi = new Weibo();
mDb = TwitterDatabase.getInstance(this);
mPref = PreferenceManager.getDefaultSharedPreferences(this);
String username = mPref.getString(Preferences.USERNAME_KEY, "");
String password = mPref.getString(Preferences.PASSWORD_KEY, "");
password = LoginActivity.decryptPassword(password);
if (Weibo.isValidCredentials(username, password)) {
mApi.setCredentials(username, password); // Setup API and HttpClient
}
// 为cmwap用户设置代理上网
String type = getNetworkType();
if (null != type && type.equalsIgnoreCase("cmwap")) {
Toast.makeText(this, "您当前正在使用cmwap网络上网.", Toast.LENGTH_SHORT);
mApi.getHttpClient().setProxy("10.0.0.172", 80, "http");
}
}
public String getNetworkType() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
//NetworkInfo mobNetInfo = connectivityManager
// .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (activeNetInfo != null){
return activeNetInfo.getExtraInfo(); // 接入点名称: 此名称可被用户任意更改 如: cmwap, cmnet,
// internet ...
}else{
return null;
}
}
@Override
public void onTerminate() {
//FIXME: 根据android文档,onTerminate不会在真实机器上被执行到
//因此这些清理动作需要再找合适的地方放置,以确保执行。
cleanupImages();
mDb.close();
Toast.makeText(this, "exit app", Toast.LENGTH_LONG);
super.onTerminate();
}
private void cleanupImages() {
HashSet<String> keepers = new HashSet<String>();
Cursor cursor = mDb.fetchAllTweets(StatusTable.TYPE_HOME);
if (cursor.moveToFirst()) {
int imageIndex = cursor
.getColumnIndexOrThrow(StatusTable.PROFILE_IMAGE_URL);
do {
keepers.add(cursor.getString(imageIndex));
} while (cursor.moveToNext());
}
cursor.close();
cursor = mDb.fetchAllDms(-1);
if (cursor.moveToFirst()) {
int imageIndex = cursor
.getColumnIndexOrThrow(StatusTable.PROFILE_IMAGE_URL);
do {
keepers.add(cursor.getString(imageIndex));
} while (cursor.moveToNext());
}
cursor.close();
mImageLoader.getImageManager().cleanup(keepers);
}
}
| Java |
package com.ch_linghu.fanfoudroid.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.text.Html;
import android.text.util.Linkify;
import android.util.Log;
import android.widget.TextView;
import android.widget.TextView.BufferType;
public class TextHelper {
private static final String TAG = "TextHelper";
public static String stringifyStream(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
return sb.toString();
}
private static HashMap<String, String> _userLinkMapping = new HashMap<String, String>();
private static final Pattern NAME_MATCHER = Pattern.compile("@.+?\\s");
private static final Linkify.MatchFilter NAME_MATCHER_MATCH_FILTER = new Linkify.MatchFilter() {
@Override
public final boolean acceptMatch(final CharSequence s, final int start,
final int end) {
String name = s.subSequence(start + 1, end).toString().trim();
boolean result = _userLinkMapping.containsKey(name);
return result;
}
};
private static final Linkify.TransformFilter NAME_MATCHER_TRANSFORM_FILTER = new Linkify.TransformFilter() {
@Override
public String transformUrl(Matcher match, String url) {
// TODO Auto-generated method stub
String name = url.subSequence(1, url.length()).toString().trim();
return _userLinkMapping.get(name);
}
};
private static final String TWITTA_USER_URL = "twitta://users/";
public static void linkifyUsers(TextView view) {
Linkify.addLinks(view, NAME_MATCHER, TWITTA_USER_URL,
NAME_MATCHER_MATCH_FILTER, NAME_MATCHER_TRANSFORM_FILTER);
}
private static final Pattern TAG_MATCHER = Pattern.compile("#\\w+#");
private static final Linkify.TransformFilter TAG_MATCHER_TRANSFORM_FILTER = new Linkify.TransformFilter() {
@Override
public final String transformUrl(Matcher match, String url) {
String result = url.substring(1, url.length() - 1);
return "%23" + result + "%23";
}
};
private static final String TWITTA_SEARCH_URL = "twitta://search/";
public static void linkifyTags(TextView view) {
Linkify.addLinks(view, TAG_MATCHER, TWITTA_SEARCH_URL, null,
TAG_MATCHER_TRANSFORM_FILTER);
}
private static Pattern USER_LINK = Pattern
.compile("@<a href=\"http:\\/\\/fanfou\\.com\\/(.*?)\" class=\"former\">(.*?)<\\/a>");
private static String preprocessText(String text) {
// 处理HTML格式返回的用户链接
Matcher m = USER_LINK.matcher(text);
while (m.find()) {
_userLinkMapping.put(m.group(2), m.group(1));
Log.d(TAG,
String.format("Found mapping! %s=%s", m.group(2),
m.group(1)));
}
// 将User Link的连接去掉
StringBuffer sb = new StringBuffer();
m = USER_LINK.matcher(text);
while (m.find()) {
m.appendReplacement(sb, "@$2");
}
m.appendTail(sb);
return sb.toString();
}
public static String getSimpleTweetText(String text) {
return Html.fromHtml(text).toString();
}
public static void setSimpleTweetText(TextView textView, String text) {
String processedText = getSimpleTweetText(text);
textView.setText(processedText);
}
public static void setTweetText(TextView textView, String text) {
String processedText = preprocessText(text);
textView.setText(Html.fromHtml(processedText), BufferType.SPANNABLE);
Linkify.addLinks(textView, Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES);
linkifyUsers(textView);
linkifyTags(textView);
_userLinkMapping.clear();
}
/**
* 从消息中获取全部提到的人,将它们按先后顺序放入一个列表
* @param msg 消息文本
* @return 消息中@的人的列表,按顺序存放
*/
public static List<String> getMentions(String msg){
ArrayList<String> mentionList = new ArrayList<String>();
final Pattern p = Pattern.compile("@(.*?)\\s");
final int MAX_NAME_LENGTH = 12; //简化判断,无论中英文最长12个字
Matcher m = p.matcher(msg);
while(m.find()){
String mention = m.group(1);
//过长的名字就忽略(不是合法名字) +1是为了补上“@”所占的长度
if (mention.length() <= MAX_NAME_LENGTH+1){
//避免重复名字
if (!mentionList.contains(mention)){
mentionList.add(m.group(1));
}
}
}
return mentionList;
}
}
| Java |
package com.ch_linghu.fanfoudroid.util;
import java.io.InputStream;
import java.io.OutputStream;
public class StreamUtils {
public static void CopyStream(InputStream is, OutputStream os)
{
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}
} | Java |
package com.ch_linghu.fanfoudroid.util;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.HashMap;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
/**
* Debug Timer
*
* Usage:
* --------------------------------
* DebugTimer.start();
* DebugTimer.mark("my_mark1"); // optional
* DebugTimer.stop();
*
* System.out.println(DebugTimer.__toString()); // get report
* --------------------------------
*
* @author LDS
*/
public class DebugTimer {
public static final int START = 0;
public static final int END = 1;
private static HashMap<String, Long> mTime = new HashMap<String, Long>();
private static long mStartTime = 0;
private static long mLastTime = 0;
/**
* Start a timer
*/
public static void start() {
reset();
mStartTime = touch();
}
/**
* Mark current time
*
* @param tag mark tag
* @return
*/
public static long mark(String tag) {
long time = System.currentTimeMillis() - mStartTime;
mTime.put(tag, time);
return time;
}
/**
* Mark current time
*
* @param tag mark tag
* @return
*/
public static long between(String tag, int startOrEnd) {
if(TwitterApplication.DEBUG){
Log.v("DEBUG", tag + " " + startOrEnd);
}
switch (startOrEnd) {
case START:
return mark(tag);
case END:
long time = System.currentTimeMillis() - mStartTime - get(tag, mStartTime);
mTime.put(tag, time);
//touch();
return time;
default:
return -1;
}
}
public static long betweenStart(String tag) {
return between(tag, START);
}
public static long betweenEnd(String tag) {
return between(tag, END);
}
/**
* Stop timer
*
* @return result
*/
public static String stop() {
mTime.put("_TOTLE", touch() - mStartTime);
return __toString();
}
public static String stop(String tag) {
mark(tag);
return stop();
}
/**
* Get a mark time
*
* @param tag mark tag
* @return time(milliseconds) or NULL
*/
public static long get(String tag) {
return get(tag, 0);
}
public static long get(String tag, long defaultValue) {
if (mTime.containsKey(tag)) {
return mTime.get(tag);
}
return defaultValue;
}
/**
* Reset timer
*/
public static void reset() {
mTime = new HashMap<String, Long>();
mStartTime = 0;
mLastTime = 0;
}
/**
* static toString()
*
* @return
*/
public static String __toString() {
return "Debuger [time =" + mTime.toString() + "]";
}
private static long touch() {
return mLastTime = System.currentTimeMillis();
}
public static DebugProfile[] getProfile() {
DebugProfile[] profile = new DebugProfile[mTime.size()];
long totel = mTime.get("_TOTLE");
int i = 0;
for (String key : mTime.keySet()) {
long time = mTime.get(key);
profile[i] = new DebugProfile(key, time, time/(totel*1.0) );
i++;
}
try {
Arrays.sort(profile);
} catch (NullPointerException e) {
// in case item is null, do nothing
}
return profile;
}
public static String getProfileAsString() {
StringBuilder sb = new StringBuilder();
for (DebugProfile p : getProfile()) {
sb.append("TAG: ");
sb.append(p.tag);
sb.append("\t INC: ");
sb.append(p.inc);
sb.append("\t INCP: ");
sb.append(p.incPercent);
sb.append("\n");
}
return sb.toString();
}
@Override
public String toString() {
return __toString();
}
}
class DebugProfile implements Comparable<DebugProfile> {
private static NumberFormat percent = NumberFormat.getPercentInstance();
public String tag;
public long inc;
public String incPercent;
public DebugProfile(String tag, long inc, double incPercent) {
this.tag = tag;
this.inc = inc;
percent = new DecimalFormat("0.00#%");
this.incPercent = percent.format(incPercent);
}
@Override
public int compareTo(DebugProfile o) {
// TODO Auto-generated method stub
return (int) (o.inc - this.inc);
}
}
| Java |
package com.ch_linghu.fanfoudroid.util;
import java.io.File;
import java.io.IOException;
import android.os.Environment;
/**
* 对SD卡文件的管理
* @author ch.linghu
*
*/
public class FileHelper {
private static final String TAG = "FileHelper";
private static final String BASE_PATH="fanfoudroid";
public static File getBasePath() throws IOException{
File basePath = new File(Environment.getExternalStorageDirectory(),
BASE_PATH);
if (!basePath.exists()){
if (!basePath.mkdirs()){
throw new IOException(String.format("%s cannot be created!", basePath.toString()));
}
}
if (!basePath.isDirectory()){
throw new IOException(String.format("%s is not a directory!", basePath.toString()));
}
return basePath;
}
}
| Java |
package com.ch_linghu.fanfoudroid.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import android.util.Log;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
public class DateTimeHelper {
private static final String TAG = "DateTimeHelper";
// Wed Dec 15 02:53:36 +0000 2010
public static final DateFormat TWITTER_DATE_FORMATTER = new SimpleDateFormat(
"E MMM d HH:mm:ss Z yyyy", Locale.US);
public static final DateFormat TWITTER_SEARCH_API_DATE_FORMATTER = new SimpleDateFormat(
"E, d MMM yyyy HH:mm:ss Z", Locale.US); // TODO: Z -> z ?
public static final Date parseDateTime(String dateString) {
try {
Log.v(TAG, String.format("in parseDateTime, dateString=%s", dateString));
return TWITTER_DATE_FORMATTER.parse(dateString);
} catch (ParseException e) {
Log.w(TAG, "Could not parse Twitter date string: " + dateString);
return null;
}
}
// Handle "yyyy-MM-dd'T'HH:mm:ss.SSS" from sqlite
public static final Date parseDateTimeFromSqlite(String dateString) {
try {
Log.v(TAG, String.format("in parseDateTime, dateString=%s", dateString));
return TwitterDatabase.DB_DATE_FORMATTER.parse(dateString);
} catch (ParseException e) {
Log.w(TAG, "Could not parse Twitter date string: " + dateString);
return null;
}
}
public static final Date parseSearchApiDateTime(String dateString) {
try {
return TWITTER_SEARCH_API_DATE_FORMATTER.parse(dateString);
} catch (ParseException e) {
Log.w(TAG, "Could not parse Twitter search date string: "
+ dateString);
return null;
}
}
public static final DateFormat AGO_FULL_DATE_FORMATTER = new SimpleDateFormat(
"yyyy-MM-dd HH:mm");
public static String getRelativeDate(Date date) {
Date now = new Date();
String prefix = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_prefix);
String sec = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_sec);
String min = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_min);
String hour = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_hour);
String day = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_day);
String suffix = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_suffix);
// Seconds.
long diff = (now.getTime() - date.getTime()) / 1000;
if (diff < 0) {
diff = 0;
}
if (diff < 60) {
return diff + sec + suffix;
}
// Minutes.
diff /= 60;
if (diff < 60) {
return prefix + diff + min + suffix;
}
// Hours.
diff /= 60;
if (diff < 24) {
return prefix + diff + hour + suffix;
}
return AGO_FULL_DATE_FORMATTER.format(date);
}
public static long getNowTime() {
return Calendar.getInstance().getTime().getTime();
}
}
| Java |
/***
Copyright (c) 2008-2009 CommonsWare, LLC
Portions (c) 2009 Google, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.commonsware.cwac.sacklist;
import java.util.ArrayList;
import java.util.List;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
/**
* Adapter that simply returns row views from a list.
*
* If you supply a size, you must implement newView(), to
* create a required view. The adapter will then cache these
* views.
*
* If you supply a list of views in the constructor, that
* list will be used directly. If any elements in the list
* are null, then newView() will be called just for those
* slots.
*
* Subclasses may also wish to override areAllItemsEnabled()
* (default: false) and isEnabled() (default: false), if some
* of their rows should be selectable.
*
* It is assumed each view is unique, and therefore will not
* get recycled.
*
* Note that this adapter is not designed for long lists. It
* is more for screens that should behave like a list. This
* is particularly useful if you combine this with other
* adapters (e.g., SectionedAdapter) that might have an
* arbitrary number of rows, so it all appears seamless.
*/
public class SackOfViewsAdapter extends BaseAdapter {
private List<View> views=null;
/**
* Constructor creating an empty list of views, but with
* a specified count. Subclasses must override newView().
*/
public SackOfViewsAdapter(int count) {
super();
views=new ArrayList<View>(count);
for (int i=0;i<count;i++) {
views.add(null);
}
}
/**
* Constructor wrapping a supplied list of views.
* Subclasses must override newView() if any of the elements
* in the list are null.
*/
public SackOfViewsAdapter(List<View> views) {
super();
this.views=views;
}
/**
* Get the data item associated with the specified
* position in the data set.
* @param position Position of the item whose data we want
*/
@Override
public Object getItem(int position) {
return(views.get(position));
}
/**
* How many items are in the data set represented by this
* Adapter.
*/
@Override
public int getCount() {
return(views.size());
}
/**
* Returns the number of types of Views that will be
* created by getView().
*/
@Override
public int getViewTypeCount() {
return(getCount());
}
/**
* Get the type of View that will be created by getView()
* for the specified item.
* @param position Position of the item whose data we want
*/
@Override
public int getItemViewType(int position) {
return(position);
}
/**
* Are all items in this ListAdapter enabled? If yes it
* means all items are selectable and clickable.
*/
@Override
public boolean areAllItemsEnabled() {
return(false);
}
/**
* Returns true if the item at the specified position is
* not a separator.
* @param position Position of the item whose data we want
*/
@Override
public boolean isEnabled(int position) {
return(false);
}
/**
* Get a View that displays the data at the specified
* position in the data set.
* @param position Position of the item whose data we want
* @param convertView View to recycle, if not null
* @param parent ViewGroup containing the returned View
*/
@Override
public View getView(int position, View convertView,
ViewGroup parent) {
View result=views.get(position);
if (result==null) {
result=newView(position, parent);
views.set(position, result);
}
return(result);
}
/**
* Get the row id associated with the specified position
* in the list.
* @param position Position of the item whose data we want
*/
@Override
public long getItemId(int position) {
return(position);
}
/**
* Create a new View to go into the list at the specified
* position.
* @param position Position of the item whose data we want
* @param parent ViewGroup containing the returned View
*/
protected View newView(int position, ViewGroup parent) {
throw new RuntimeException("You must override newView()!");
}
} | Java |
/***
Copyright (c) 2008-2009 CommonsWare, LLC
Portions (c) 2009 Google, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.commonsware.cwac.merge;
import java.util.ArrayList;
import java.util.List;
import android.database.DataSetObserver;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.SectionIndexer;
import com.commonsware.cwac.sacklist.SackOfViewsAdapter;
/**
* Adapter that merges multiple child adapters and views
* into a single contiguous whole.
*
* Adapters used as pieces within MergeAdapter must
* have view type IDs monotonically increasing from 0. Ideally,
* adapters also have distinct ranges for their row ids, as
* returned by getItemId().
*
*/
public class MergeAdapter extends BaseAdapter implements SectionIndexer {
private ArrayList<ListAdapter> pieces=new ArrayList<ListAdapter>();
/**
* Stock constructor, simply chaining to the superclass.
*/
public MergeAdapter() {
super();
}
/**
* Adds a new adapter to the roster of things to appear
* in the aggregate list.
* @param adapter Source for row views for this section
*/
public void addAdapter(ListAdapter adapter) {
pieces.add(adapter);
adapter.registerDataSetObserver(new CascadeDataSetObserver());
}
/**
* Adds a new View to the roster of things to appear
* in the aggregate list.
* @param view Single view to add
*/
public void addView(View view) {
addView(view, false);
}
/**
* Adds a new View to the roster of things to appear
* in the aggregate list.
* @param view Single view to add
* @param enabled false if views are disabled, true if enabled
*/
public void addView(View view, boolean enabled) {
ArrayList<View> list=new ArrayList<View>(1);
list.add(view);
addViews(list, enabled);
}
/**
* Adds a list of views to the roster of things to appear
* in the aggregate list.
* @param views List of views to add
*/
public void addViews(List<View> views) {
addViews(views, false);
}
/**
* Adds a list of views to the roster of things to appear
* in the aggregate list.
* @param views List of views to add
* @param enabled false if views are disabled, true if enabled
*/
public void addViews(List<View> views, boolean enabled) {
if (enabled) {
addAdapter(new EnabledSackAdapter(views));
}
else {
addAdapter(new SackOfViewsAdapter(views));
}
}
/**
* Get the data item associated with the specified
* position in the data set.
* @param position Position of the item whose data we want
*/
@Override
public Object getItem(int position) {
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
return(piece.getItem(position));
}
position-=size;
}
return(null);
}
/**
* Get the adapter associated with the specified
* position in the data set.
* @param position Position of the item whose adapter we want
*/
public ListAdapter getAdapter(int position) {
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
return(piece);
}
position-=size;
}
return(null);
}
/**
* How many items are in the data set represented by this
* Adapter.
*/
@Override
public int getCount() {
int total=0;
for (ListAdapter piece : pieces) {
total+=piece.getCount();
}
return(total);
}
/**
* Returns the number of types of Views that will be
* created by getView().
*/
@Override
public int getViewTypeCount() {
int total=0;
for (ListAdapter piece : pieces) {
total+=piece.getViewTypeCount();
}
return(Math.max(total, 1)); // needed for setListAdapter() before content add'
}
/**
* Get the type of View that will be created by getView()
* for the specified item.
* @param position Position of the item whose data we want
*/
@Override
public int getItemViewType(int position) {
int typeOffset=0;
int result=-1;
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
result=typeOffset+piece.getItemViewType(position);
break;
}
position-=size;
typeOffset+=piece.getViewTypeCount();
}
return(result);
}
/**
* Are all items in this ListAdapter enabled? If yes it
* means all items are selectable and clickable.
*/
@Override
public boolean areAllItemsEnabled() {
return(false);
}
/**
* Returns true if the item at the specified position is
* not a separator.
* @param position Position of the item whose data we want
*/
@Override
public boolean isEnabled(int position) {
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
return(piece.isEnabled(position));
}
position-=size;
}
return(false);
}
/**
* Get a View that displays the data at the specified
* position in the data set.
* @param position Position of the item whose data we want
* @param convertView View to recycle, if not null
* @param parent ViewGroup containing the returned View
*/
@Override
public View getView(int position, View convertView,
ViewGroup parent) {
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
return(piece.getView(position, convertView, parent));
}
position-=size;
}
return(null);
}
/**
* Get the row id associated with the specified position
* in the list.
* @param position Position of the item whose data we want
*/
@Override
public long getItemId(int position) {
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
return(piece.getItemId(position));
}
position-=size;
}
return(-1);
}
@Override
public int getPositionForSection(int section) {
int position=0;
for (ListAdapter piece : pieces) {
if (piece instanceof SectionIndexer) {
Object[] sections=((SectionIndexer)piece).getSections();
int numSections=0;
if (sections!=null) {
numSections=sections.length;
}
if (section<numSections) {
return(position+((SectionIndexer)piece).getPositionForSection(section));
}
else if (sections!=null) {
section-=numSections;
}
}
position+=piece.getCount();
}
return(0);
}
@Override
public int getSectionForPosition(int position) {
int section=0;
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
if (piece instanceof SectionIndexer) {
return(section+((SectionIndexer)piece).getSectionForPosition(position));
}
return(0);
}
else {
if (piece instanceof SectionIndexer) {
Object[] sections=((SectionIndexer)piece).getSections();
if (sections!=null) {
section+=sections.length;
}
}
}
position-=size;
}
return(0);
}
@Override
public Object[] getSections() {
ArrayList<Object> sections=new ArrayList<Object>();
for (ListAdapter piece : pieces) {
if (piece instanceof SectionIndexer) {
Object[] curSections=((SectionIndexer)piece).getSections();
if (curSections!=null) {
for (Object section : curSections) {
sections.add(section);
}
}
}
}
if (sections.size()==0) {
return(null);
}
return(sections.toArray(new Object[0]));
}
private static class EnabledSackAdapter extends SackOfViewsAdapter {
public EnabledSackAdapter(List<View> views) {
super(views);
}
@Override
public boolean areAllItemsEnabled() {
return(true);
}
@Override
public boolean isEnabled(int position) {
return(true);
}
}
private class CascadeDataSetObserver extends DataSetObserver {
@Override
public void onChanged() {
notifyDataSetChanged();
}
@Override
public void onInvalidated() {
notifyDataSetInvalidated();
}
}
} | Java |
package com.hlidskialf.android.hardware;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
public class ShakeListener implements SensorEventListener {
private static final int FORCE_THRESHOLD = 350;
private static final int TIME_THRESHOLD = 100;
private static final int SHAKE_TIMEOUT = 500;
private static final int SHAKE_DURATION = 1000;
private static final int SHAKE_COUNT = 3;
private SensorManager mSensorMgr;
private Sensor mSensor;
private float mLastX = -1.0f, mLastY = -1.0f, mLastZ = -1.0f;
private long mLastTime;
private OnShakeListener mShakeListener;
private Context mContext;
private int mShakeCount = 0;
private long mLastShake;
private long mLastForce;
public interface OnShakeListener {
public void onShake();
}
public ShakeListener(Context context) {
mContext = context;
resume();
}
public void setOnShakeListener(OnShakeListener listener) {
mShakeListener = listener;
}
public void resume() {
mSensorMgr = (SensorManager) mContext
.getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorMgr
.getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER);
if (mSensorMgr == null) {
throw new UnsupportedOperationException("Sensors not supported");
}
boolean supported = mSensorMgr.registerListener(this,
mSensor,
SensorManager.SENSOR_DELAY_GAME);
if (!supported) {
mSensorMgr.unregisterListener(this, mSensor);
throw new UnsupportedOperationException(
"Accelerometer not supported");
}
}
public void pause() {
if (mSensorMgr != null) {
mSensorMgr.unregisterListener(this,
mSensor);
mSensorMgr = null;
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
float[] values = event.values;
if (sensor.getType() != SensorManager.SENSOR_ACCELEROMETER)
return;
long now = System.currentTimeMillis();
if ((now - mLastForce) > SHAKE_TIMEOUT) {
mShakeCount = 0;
}
if ((now - mLastTime) > TIME_THRESHOLD) {
long diff = now - mLastTime;
float speed = Math.abs(values[SensorManager.DATA_X]
+ values[SensorManager.DATA_Y]
+ values[SensorManager.DATA_Z] - mLastX - mLastY - mLastZ)
/ diff * 10000;
if (speed > FORCE_THRESHOLD) {
if ((++mShakeCount >= SHAKE_COUNT)
&& (now - mLastShake > SHAKE_DURATION)) {
mLastShake = now;
mShakeCount = 0;
if (mShakeListener != null) {
mShakeListener.onShake();
}
}
mLastForce = now;
}
mLastTime = now;
mLastX = values[SensorManager.DATA_X];
mLastY = values[SensorManager.DATA_Y];
mLastZ = values[SensorManager.DATA_Z];
}
}
}
| Java |
package com.besttone.app;
import android.content.ContentValues;
import android.content.SearchRecentSuggestionsProvider;
import android.database.Cursor;
import android.net.Uri;
public class SuggestionProvider extends SearchRecentSuggestionsProvider {
public static final String AUTHORITY = "com.besttone.app.114SuggestionProvider";
public static final String[] COLUMNS;
public static final int MODE = DATABASE_MODE_QUERIES;
private static String sDatabaseName = "suggestions.db";
private static int totalRecord;
private final int MAXCOUNT = 20;
static {
String[] arrayOfString = new String[4];
arrayOfString[0] = "_id";
arrayOfString[1] = "display1";
arrayOfString[2] = "query";
arrayOfString[3] = "date";
COLUMNS = arrayOfString;
}
public SuggestionProvider() {
//super(contex, AUTHORITY, MODE);
setupSuggestions(AUTHORITY, MODE);
}
private Object[] columnValuesOfWord(int paramInt, String paramString1,
String paramString2) {
Object[] arrayOfObject = new Object[4];
arrayOfObject[0] = Integer.valueOf(paramInt);
arrayOfObject[1] = paramString1;
arrayOfObject[2] = paramString2;
arrayOfObject[3] = paramString1;
return arrayOfObject;
}
public Uri insert(Uri uri, ContentValues values) {
String selection = "query=?";
String[] selectionArgs = new String[1];
selectionArgs[0] = "没有搜索记录";
super.delete(uri, selection, selectionArgs);
Cursor localCursor = super.query(uri, COLUMNS, null, null, null);
if (localCursor!=null && localCursor.getCount() == 0) {
ContentValues localContentValues = new ContentValues();
localContentValues.put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[0],
Integer.valueOf(2));
localContentValues.put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[1],
Long.valueOf(System.currentTimeMillis()));
localContentValues.put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[2],
"清空搜索记录");
localContentValues.put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[3],
"清空搜索记录");
super.insert(uri, localContentValues);
}
values.put("date", Long.valueOf(System.currentTimeMillis()));
Uri localUri = super.insert(uri, values);
return localUri;
}
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Cursor localCursor = super.query(uri, projection, selection, selectionArgs, sortOrder);
Object localObject;
if (selectionArgs == null || selectionArgs.length == 0)
if (localCursor.getCount() == 0) {
ContentValues localContentValues = new ContentValues();
localContentValues
.put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[0],
Integer.valueOf(1));
localContentValues
.put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[1],
Long.valueOf(System.currentTimeMillis()));
localContentValues
.put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[2],
"没有搜索记录");
localContentValues
.put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[3],
"没有搜索记录");
super.insert(uri, localContentValues);
}
localCursor = super.query(uri, projection, selection, selectionArgs, sortOrder);
totalRecord = localCursor.getCount();
if (totalRecord > 20)
truncateHistory(uri, -20 + totalRecord);
return localCursor;
}
protected void truncateHistory(Uri paramUri, int paramInt) {
if (paramInt < 0)
throw new IllegalArgumentException();
String str = null;
if (paramInt > 0)
try {
str = "_id IN (SELECT _id FROM suggestions ORDER BY date ASC LIMIT "
+ String.valueOf(paramInt) + " OFFSET 1)";
delete(paramUri, str, null);
return;
} catch (RuntimeException localRuntimeException) {
}
}
} | Java |
package com.besttone.http;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.MarshalBase64;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParser;
import com.besttone.search.Client;
import com.besttone.search.ServerListener;
import com.besttone.search.model.ChResultInfo;
import com.besttone.search.model.OrgInfo;
import com.besttone.search.model.RequestInfo;
import com.besttone.search.util.Constants;
import com.besttone.search.util.XmlHelper;
import android.util.Log;
import android.util.Xml;
public class WebServiceHelper {
private static final String TAG = "WebServiceHelper";
//命名空间
private static final String serviceNameSpace="http://ws.besttone.com/";
//调用方法(获得支持的城市)
//private static final String methodName="SearchChInfo";
private static final String methodName="searchChNewInfo";
private ChResultInfo resultInfo;
private int i = 0;
private List<Map<String, Object>> list;
public static interface WebServiceListener {
public void onWebServiceSuccess();
public void onWebServiceFailed();
}
public void setmListener(WebServiceListener mListener) {
this.mListener = mListener;
}
private WebServiceListener mListener;
public List<Map<String, Object>> searchChInfo(RequestInfo rqInfo){
Long t1 = System.currentTimeMillis();
list = new LinkedList<Map<String, Object>>();
//返回的查询结果
String result =null;
//实例化SoapObject对象
SoapObject request=new SoapObject(serviceNameSpace, methodName);
//假设方法有参数的话,设置调用方法参数
String rqXml = XmlHelper.getRequestXml(rqInfo);
request.addProperty("xml", rqXml);
request.addProperty("name",Constants.chName);
request.addProperty("key",Constants.chKey);
//设置SOAP请求信息(参数部分为SOAP协议版本号,与你要调用的webService中版本号一致)
//获得序列化的Envelope
SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER10);
//设置是否调用的是dotNet开发的
envelope.dotNet = false;
envelope.bodyOut=request;
envelope.setOutputSoapObject(request);
//注册Envelope
(new MarshalBase64()).register(envelope);
//构建传输对象,并指明WSDL文档URL
//Android传输对象
HttpTransportSE transport=new HttpTransportSE(Constants.serviceURL);
transport.debug=true;
//调用WebService(其中参数为1:命名空间+方法名称,2:Envelope对象):
String soapAction = serviceNameSpace+methodName;
try {
transport.call(soapAction, envelope);
//解析返回数据
Object resultObj = envelope.getResponse();
result = resultObj.toString();
parseChInfo(result);
} catch (Exception e) {
e.printStackTrace();
Log.v(TAG, "获取XML出错");
}
Long t2 = System.currentTimeMillis();
Log.v(TAG, "获取查号信息耗时"+(t2-t1)+"毫秒");
return list;
}
public void parseChInfo(String xmlString) {
Map<String, Object> map = new HashMap<String, Object>();
InputStream inputStream=null;
//获得XmlPullParser解析器
XmlPullParser xmlParser = Xml.newPullParser();
try {
//得到文件流,并设置编码方式
xmlParser.setInput(new StringReader(xmlString));
//获得解析到的事件类别,这里有开始文档,结束文档,开始标签,结束标签,文本等等事件。
int evtType=xmlParser.getEventType();
List<OrgInfo> orgList = null;
OrgInfo info = null;
String propertyName = null;
String propertyValue = null;
//一直循环,直到文档结束
while(evtType!=XmlPullParser.END_DOCUMENT){
String tag = xmlParser.getName();
switch(evtType){
case XmlPullParser.START_TAG:
//如果是river标签开始,则说明需要实例化对象了
if (tag.equalsIgnoreCase("SearchResult")) {
resultInfo = new ChResultInfo();
break;
}
if (tag.equalsIgnoreCase("BDCDataSource")) {
resultInfo.setSource(xmlParser.nextText());
break;
}
if (tag.equalsIgnoreCase("BDCSearchflag")) {
resultInfo.setSearchFlag(xmlParser.nextText());
break;
}
if (tag.equalsIgnoreCase("ResultCount")) {
String cnt = xmlParser.nextText();
break;
}
if (tag.equalsIgnoreCase("ResultTime")) {
String time = xmlParser.nextText();
break;
}
if (tag.equalsIgnoreCase("SingleResult")) {
map = new HashMap<String, Object>();
break;
}
if (tag.equalsIgnoreCase("propertyName")) {
propertyName = xmlParser.nextText();
break;
}
if (tag.equalsIgnoreCase("propertyValue")) {
propertyValue = xmlParser.nextText();
if(propertyName!=null && "产品序列号".equals(propertyName)) {
// if(propertyValue!=null && !Constants.SPACE.equals(propertyValue)){
// info.setChId(Integer.valueOf(propertyValue));
// }
if(propertyValue==null || Constants.SPACE.equals(propertyValue)) {
propertyValue = Constants.SPACE;
}
map.put("chId", propertyValue);
}
if(propertyName!=null && "公司名称".equals(propertyName)) {
if(propertyValue==null || Constants.SPACE.equals(propertyValue)) {
propertyValue = Constants.SPACE;
}
map.put("name", propertyValue);
}
if(propertyName!=null && "首查电话".equals(propertyName)) {
if(propertyValue==null || Constants.SPACE.equals(propertyValue)) {
propertyValue = Constants.SPACE;
}
map.put("tel", propertyValue);
}
if(propertyName!=null && "地址".equals(propertyName)) {
if(propertyValue==null || Constants.SPACE.equals(propertyValue)) {
propertyValue = Constants.SPACE;
}
map.put("addr", propertyValue);
}
if(propertyName!=null && "ORG_ID".equals(propertyName)) {
map.put("orgId", propertyValue);
}
if(propertyName!=null && "所属城市".equals(propertyName)) {
map.put("city", Constants.getCity(propertyValue));
}
if(propertyName!=null && "Region_Cede".equals(propertyName)) {
map.put("regionCode", propertyValue);
}
if(propertyName!=null && "IS_DC".equals(propertyName)) {
map.put("isDc", propertyValue);
}
if(propertyName!=null && "IS_DF".equals(propertyName)) {
map.put("isDf", propertyValue);
}
if(propertyName!=null && "QYMP".equals(propertyName)) {
map.put("isQymp", propertyValue);
}
propertyName = null;
propertyValue = null;
}
break;
case XmlPullParser.END_TAG:
//如果遇到river标签结束,则把river对象添加进集合中
if (tag.equalsIgnoreCase("SingleResult")) {
if(map.get("addr")==null) {
map.put("addr", Constants.SPACE);
}
if(map.get("tel")==null) {
map.put("tel", Constants.SPACE);
}
list.add(map);
}
break;
default:break;
}
//如果xml没有结束,则导航到下一个river节点
evtType=xmlParser.next();
}
} catch (Exception e) {
e.printStackTrace();
Log.v(TAG, "xml解析出错"+e.getMessage());
}
}
public void sendRequest(final ServerListener listener, final RequestInfo rqInfo) {
Client.getThreadPoolForRequest().execute(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(1000);
} catch (Exception e) {
}
list = searchChInfo(rqInfo);
listener.serverDataArrived(list, false);
}
});
}
public ArrayList<String> getAssociateList(String key) {
Long t1 = System.currentTimeMillis();
ArrayList<String> resultAssociateList = new ArrayList<String>();
// new ArrayList<String>();
//返回的查询结果
String result =null;
//实例化SoapObject对象
SoapObject request=new SoapObject(serviceNameSpace, Constants.associate_method);
//假设方法有参数的话,设置调用方法参数
StringBuilder sb = new StringBuilder("");
if (key != null) {
sb.append("<ChKeyInpara>");
sb.append("<content><![CDATA[" + key + "]]></content>");
sb.append("</ChKeyInpara>");
}
request.addProperty("xml", sb.toString());
request.addProperty("name",Constants.chName);
request.addProperty("key",Constants.chKey);
//设置SOAP请求信息(参数部分为SOAP协议版本号,与你要调用的webService中版本号一致)
//获得序列化的Envelope
SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER10);
//设置是否调用的是dotNet开发的
envelope.dotNet = false;
envelope.bodyOut=request;
envelope.setOutputSoapObject(request);
//注册Envelope
(new MarshalBase64()).register(envelope);
//构建传输对象,并指明WSDL文档URL
//Android传输对象
HttpTransportSE transport=new HttpTransportSE(Constants.serviceURL);
transport.debug=true;
//调用WebService(其中参数为1:命名空间+方法名称,2:Envelope对象):
String soapAction = serviceNameSpace+Constants.associate_method;
try {
transport.call(soapAction, envelope);
//解析返回数据
Object resultObj = envelope.getResponse();
result = resultObj.toString();
resultAssociateList = parseKeywordInfo(result);
} catch (Exception e) {
e.printStackTrace();
Log.v(TAG, "关键词联想获取出错");
}
Long t2 = System.currentTimeMillis();
Log.v(TAG, "关键词联想获取耗时"+(t2-t1)+"毫秒");
// if(mListener!=null)
// mListener.onWebServiceSuccess();
return resultAssociateList;
}
public ArrayList<String> parseKeywordInfo(String xmlString) {
Map<String, Object> map = new HashMap<String, Object>();
ArrayList<String> resultList = new ArrayList<String>();
InputStream inputStream=null;
//获得XmlPullParser解析器
XmlPullParser xmlParser = Xml.newPullParser();
try{
//得到文件流,并设置编码方式
xmlParser.setInput(new StringReader(xmlString));
//获得解析到的事件类别,这里有开始文档,结束文档,开始标签,结束标签,文本等等事件。
int evtType=xmlParser.getEventType();
// 一直循环,直到文档结束
while (evtType != XmlPullParser.END_DOCUMENT) {
String tag = xmlParser.getName();
switch (evtType) {
case XmlPullParser.START_TAG:
// 如果是river标签开始,则说明需要实例化对象了
if (tag.equalsIgnoreCase("ChKeyResult")) {
map = new HashMap<String, Object>();
break;
}
if (tag.equalsIgnoreCase("resultNum")) {
String resultNum = xmlParser.nextText();
map.put("resultNum", resultNum);
break;
}
if (tag.equalsIgnoreCase("result")) {
String result = xmlParser.nextText();
map.put("result", result);
break;
}
if (tag.equalsIgnoreCase("searchTime")) {
String searchTime = xmlParser.nextText();
map.put("searchTime", searchTime);
break;
}
if (tag.equalsIgnoreCase("ChKeyList")) {
break;
}
if (tag.equalsIgnoreCase("searchKey")) {
String searchKey = xmlParser.nextText();
resultList.add(searchKey);
break;
}
break;
case XmlPullParser.END_TAG:
// 如果遇到river标签结束,则把river对象添加进集合中
if (tag.equalsIgnoreCase("ChKeyResult")) {
map.put("resultList", resultList);
}
break;
default:
break;
}
// 如果xml没有结束,则导航到下一个river节点
evtType = xmlParser.next();
}
} catch (Exception e) {
e.printStackTrace();
Log.v(TAG, "xml解析出错"+e.getMessage());
}
return resultList;
}
}
| Java |
package com.besttone.http;
import com.besttone.search.Client;
public class UpdateRequest extends WebServiceHelper
{
public static interface UpdateListener
{
public void onUpdateAvaiable(String msg, String url);
public void onUpdateMust(String msg, String url);
public void onUpdateNoNeed(String msg);
public void onUpdateError(short code, Exception e);
}
private int latestVersionCode = 0;
private String url = "";
private UpdateListener mListener = null;
public void setListener(UpdateListener mListener)
{
this.mListener = mListener;
}
public void checkUpdate()
{
Client.getThreadPoolForRequest().execute(new Runnable()
{
@Override
public void run()
{
// TODO Auto-generated method stub
getUpdateInfo();
Client.postRunnable(new Runnable()
{
@Override
public void run()
{
// TODO Auto-generated method stub
if (Client.getVersion(Client.getContext()) != latestVersionCode)
{
mListener.onUpdateAvaiable("", url);
}
else
{
mListener.onUpdateNoNeed("");
}
}
});
}
});
}
private void getUpdateInfo()
{
this.latestVersionCode = 2;
this.url = "http://droidapps.googlecode.com/files/MiniFetion-2.8.4.apk";
}
}
| Java |
package com.besttone.search;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.besttone.adapter.AreaAdapter;
import com.besttone.adapter.CateAdapter;
import com.besttone.adapter.SortAdapter;
import com.besttone.http.WebServiceHelper;
import com.besttone.search.model.RequestInfo;
import com.besttone.search.util.Constants;
import com.besttone.search.util.SharedUtils;
import com.besttone.widget.PoiListItem;
import com.besttone.search.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;
public class SearchResultActivity extends Activity implements ServerListener,
OnClickListener {
private Context mContext;
private List<Map<String, Object>> filterData;
private View loadingView;
private View addShopView;
private ListView list;
private boolean isEnd = false;
PoiResultAdapter resultAdapter = null;
ListAdapter areaAdapter = null;
CateAdapter cateAdapter = null;
private ImageButton btn_back;
private Button mSearchBtn;
private Button mAreaBtn;
private String[] mAreaArray = null;
private String[] mChannelArray = null;
private int mAreaIndex = 0;
private Button mChannelBtn;
public PopupWindow mPopupWindow;
private ListView popListView;
private String keyword;
private RequestInfo rqInfo;
private WebServiceHelper serviceHelper;
private boolean isLoadingRemoved = false;
private boolean isLoadingEnd = false;
Handler handler = new Handler() {
public void handleMessage(Message paramMessage) {
if (paramMessage.what == 1) {
loadingView.setVisibility(View.GONE);
} else if (paramMessage.what == 2) {
list.removeFooterView(loadingView);
isLoadingRemoved = true;
} else if (paramMessage.what == 3) {
list.addFooterView(loadingView);
loadingView.setVisibility(View.VISIBLE);
isLoadingRemoved = false;
} else if (paramMessage.what == 4) {
loadingView.setVisibility(View.VISIBLE);
} else if (paramMessage.what == 5) {
list.removeFooterView(loadingView);
isLoadingRemoved = true;
if(!isLoadingEnd)
addShopView();
}
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.search_result);
mContext = this.getApplicationContext();
init();
}
private ImageButton.OnClickListener backListner = new ImageButton.OnClickListener() {
public void onClick(View v) {
finish();
}
};
private Button.OnClickListener searchHistroyListner = new Button.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(SearchResultActivity.this, SearchActivity.class);
finish();
startActivity(intent);
}
};
private AdapterView.OnItemClickListener mOnClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
// Intent intent = new Intent();
// ListView listView = (ListView)parent;
// HashMap<String, String> map = (HashMap<String, String>) listView.getItemAtPosition(position);
// intent.setClass(ResultActivity.this, DetailActivity.class);
// if(map.get("id")==null || "".equals(map.get("id"))) {
// intent.putExtra("id", "2029602847-421506714");
// } else {
// intent.putExtra("id", map.get("id"));
// }
// startActivity(intent);
// ResultActivity.this.finish();
//显示数据详情
//Toast.makeText(SearchResultActivity.this, "正在开发中,敬请期待...", Toast.LENGTH_SHORT).show();
}
};
public class PoiResultAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public PoiResultAdapter(Context context) {
this.mInflater = LayoutInflater.from(context);
}
public int getCount() {
return filterData.size();
}
public Object getItem(int position) {
return filterData.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
}
convertView = mInflater.inflate(R.layout.search_result_item, null);
// convertView.findViewById(R.id.name).setSelected(true);
// convertView.findViewById(R.id.addr).setSelected(true);
PoiListItem item = (PoiListItem) convertView;
Map map = filterData.get(position);
item.setPoiData(map.get("name").toString(), map.get("tel")
.toString(), map.get("addr").toString(),(map
.get("city")==null?null:(map
.get("city")).toString()) );
if (position == filterData.size() - 1 && !isEnd) {
loadingView.setVisibility(View.VISIBLE);
//下拉获取数据
int size = filterData.size();
int page = 1 + size/Constants.PAGE_SIZE;
int currentPage =Integer.valueOf(rqInfo.getPage());
if(size==currentPage*Constants.PAGE_SIZE) {
rqInfo.setPage(Constants.SPACE + page);
serviceHelper.sendRequest(SearchResultActivity.this, rqInfo);
} else {
//Toast.makeText(ResultActivity.this, "没有更多的数据", Toast.LENGTH_SHORT).show();
Message localMessage = new Message();
localMessage.what = 5;
handler.sendMessage(localMessage);
}
}
return convertView;
}
}
public void addShopView() {
isLoadingEnd = true;
addShopView = getLayoutInflater().inflate(R.layout.search_result_empty, null, false);
list.addFooterView(addShopView);
addShopView.setVisibility(View.VISIBLE);
}
public void serverDataArrived(List list, boolean isEnd) {
this.isEnd = isEnd;
Iterator iter = list.iterator();
while (iter.hasNext()) {
filterData.add((Map<String, Object>) iter.next());
}
Message localMessage = new Message();
if (!isEnd) {
localMessage.what = 1;
} else {
localMessage.what = 2;
}
if(list!=null && list.size()==0){
localMessage.what = 5;
}
this.handler.sendMessage(localMessage);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.area: {
showDialogPopup(R.id.area);
break;
}
case R.id.channel: {
showDialogPopup(R.id.channel);
// if (mPopupWindow != null && mPopupWindow.isShowing()) {
// mPopupWindow.dismiss();
// } else {
// createPopWindow(v);
// }
break;
}
}
}
protected void showDialogPopup(int viewId) {
AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
switch (viewId) {
case R.id.area: {
if (areaAdapter == null) {
areaAdapter = new AreaAdapter(this, mAreaArray);
}
localBuilder.setAdapter(areaAdapter, new areaPopupListener(
areaAdapter));
break;
}
case R.id.channel: {
if (cateAdapter == null) {
cateAdapter = new CateAdapter(this, mChannelArray);
}
localBuilder.setAdapter(cateAdapter, new channelPopupListener(
cateAdapter));
break;
}
}
AlertDialog localAlertDialog = localBuilder.create();
localAlertDialog.show();
}
class areaPopupListener implements DialogInterface.OnClickListener {
AreaAdapter mAdapter;
public areaPopupListener(ListAdapter adapter) {
mAdapter = (AreaAdapter) adapter;
}
public void onClick(DialogInterface dialog, int which) {
((AreaAdapter) mAdapter).setTypeIndex(which);
final String cityName = ((AreaAdapter) mAdapter).getSelect();
mAreaBtn.setText(cityName);
filterData.clear();
filterData = new ArrayList<Map<String, Object>>();
resultAdapter.notifyDataSetChanged();
if (isLoadingRemoved) {
list.addFooterView(loadingView);
loadingView.setVisibility(View.VISIBLE);
isLoadingRemoved = false;
} else {
loadingView.setVisibility(View.VISIBLE);
}
if(isLoadingEnd){
list.removeFooterView(addShopView);
isLoadingEnd = false;
}
//获取数据
String simplifyCode = null;
if("全部区域".equals(cityName)) {
simplifyCode = SharedUtils.getCurrentSimplifyCode(mContext);
} else {
simplifyCode = Constants.getSimplifyCodeByName(mContext, cityName);
}
rqInfo.setRegion(simplifyCode);
String tradeName = mChannelBtn.getText().toString();
if(!"全部行业".equals(tradeName)) {
rqInfo.setContent(keyword + "/n|" + tradeName + "/i");
} else {
rqInfo.setContent(keyword+"/n");
}
rqInfo.setPage("1");
rqInfo.setPageSize(Constants.SPACE + Constants.PAGE_SIZE);
serviceHelper = new WebServiceHelper();
serviceHelper.sendRequest(SearchResultActivity.this, rqInfo);
}
}
class channelPopupListener implements DialogInterface.OnClickListener {
CateAdapter cAdapter;
public channelPopupListener(CateAdapter adapter) {
cAdapter = (CateAdapter) adapter;
}
public void onClick(DialogInterface dialog, int which) {
((CateAdapter) cAdapter).setTypeIndex(which);
final String tradeName = ((CateAdapter) cAdapter).getSelect();
mChannelBtn.setText(tradeName);
filterData.clear();
filterData = new ArrayList<Map<String, Object>>();
resultAdapter.notifyDataSetChanged();
if (isLoadingRemoved) {
list.addFooterView(loadingView);
loadingView.setVisibility(View.VISIBLE);
isLoadingRemoved = false;
} else {
loadingView.setVisibility(View.VISIBLE);
}
if(isLoadingEnd){
list.removeFooterView(addShopView);
isLoadingEnd = false;
}
//获取数据
String simplifyCode = null;
String cityName = mAreaBtn.getText().toString();
if("全部区域".equals(cityName)) {
simplifyCode = SharedUtils.getCurrentSimplifyCode(mContext);
} else {
simplifyCode = Constants.getSimplifyCodeByName(mContext, cityName);
}
if(!"全部行业".equals(tradeName)) {
rqInfo.setContent(keyword + "/n|" + tradeName + "/i");
} else {
rqInfo.setContent(keyword+"/n");
}
rqInfo.setRegion(simplifyCode);
rqInfo.setPage("1");
rqInfo.setPageSize(Constants.SPACE + Constants.PAGE_SIZE);
serviceHelper = new WebServiceHelper();
serviceHelper.sendRequest(SearchResultActivity.this, rqInfo);
}
}
private void init()
{
filterData = PoiResultData.getData();
list = (ListView) findViewById(R.id.resultlist);
list.setFastScrollEnabled(true);
resultAdapter = new PoiResultAdapter(this);
btn_back = (ImageButton) findViewById(R.id.left_title_button);
btn_back.setOnClickListener(backListner);
rqInfo = new RequestInfo();
Bundle bundle = this.getIntent().getExtras();
rqInfo.setRegion(SharedUtils.getCurrentSimplifyCode(this));
rqInfo.setDeviceid(SharedUtils.getCurrentPhoneDeviceId(this));
rqInfo.setImsi(SharedUtils.getCurrentPhoneImsi(this));
rqInfo.setMobile(SharedUtils.getCurrentPhoneNo(this));
rqInfo.setPage("1");
rqInfo.setPageSize(Constants.SPACE + Constants.PAGE_SIZE);
keyword = bundle.getString("keyword");
rqInfo.setContent(keyword+"/n");
serviceHelper = new WebServiceHelper();
serviceHelper.sendRequest(this, rqInfo);
mSearchBtn = ((Button)findViewById(R.id.start_search));
mSearchBtn.setText(bundle.getString("keyword"));
mSearchBtn.setOnClickListener(searchHistroyListner);
loadingView = LayoutInflater.from(this).inflate(R.layout.listfooter,
null);
list.addFooterView(loadingView);
list.setAdapter(resultAdapter);
list.setOnItemClickListener(mOnClickListener);
list.setOnItemLongClickListener(mOnLongClickListener);
mAreaBtn = ((Button)findViewById(R.id.area));
mChannelBtn = ((Button)findViewById(R.id.channel));
mAreaBtn.setOnClickListener(this);
mChannelBtn.setOnClickListener(this);
initHomeView();
}
private void initHomeView() {
mAreaArray = Constants.getDistrictArray(this, SharedUtils.getCurrentCityCode(this));
if ((mAreaArray == null) || (this.mAreaArray.length == 0)) {
mAreaBtn.setText("全部区域");
mAreaBtn.setEnabled(false);
}
while (true) {
mChannelArray = getResources().getStringArray(R.array.trade_name_items);
mAreaBtn.setText(this.mAreaArray[this.mAreaIndex]);
mAreaBtn.setEnabled(true);
return;
}
}
private void createPopWindow(View parent) {
// LayoutInflater lay = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// View view = lay.inflate(R.layout.popup_window, null );
//
// mPopupWindow = new PopupWindow(view, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
//
// //初始化listview,加载数据
// popListView = (ListView) findViewById(R.id.pop_list);
//// if (sortAdapter == null) {
//// sortAdapter = new SortAdapter(this, mSortArray);
//// }
//// popListView.setAdapter(sortAdapter);
//
//
// //设置整个popupwindow的样式
// mPopupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.right_filter_bg));
//
// mPopupWindow.setFocusable(true );
// mPopupWindow.setTouchable(true);
// mPopupWindow.setOutsideTouchable(true);
// mPopupWindow.update();
// mPopupWindow.showAsDropDown(parent, 10, 10);
View contentView = LayoutInflater.from(getApplicationContext())
.inflate(R.layout.popup_window, null);
mPopupWindow = new PopupWindow(contentView, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
mPopupWindow.setContentView(contentView);
//设置整个popupwindow的样式
mPopupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.right_filter_bg));
String[] name = openDir();
ListView listView = (ListView) contentView.findViewById(R.id.pop_list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, name);
listView.setAdapter(adapter);
mPopupWindow.setFocusable(true );
mPopupWindow.setTouchable(true);
mPopupWindow.setOutsideTouchable(true);
mPopupWindow.update();
mPopupWindow.showAsDropDown(parent, 10, 10);
}
private String[] openDir() {
String[] name;
String rootPath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
File file = new File(rootPath);
File[] files = file.listFiles();
name = new String[files.length];
for (int i = 0; i < files.length; i++) {
name[i] = files[i].getName();
System.out.println(name[i]);
}
return name;
}
private AdapterView.OnItemLongClickListener mOnLongClickListener = new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
ListView listView = (ListView)parent;
HashMap<String, String> map = (HashMap<String, String>) listView.getItemAtPosition(position);
final String name = map.get("name");
final String tel = map.get("tel");
final String addr = map.get("addr");
String[] array = new String[2];
array[0] = "呼叫 " + tel;
array[1] = "添加至联系人";
new AlertDialog.Builder(SearchResultActivity.this)
.setTitle(name)
.setItems(array,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
if(which == 0) {
Intent myIntentDial = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tel));
startActivity(myIntentDial);
}
if(which == 1){
String rwContactId = getContactId(name);
ContentResolver resolver = mContext.getContentResolver();
ContentValues values = new ContentValues();
//联系人中是否存在,若存在则更新
if(rwContactId!=null && !"".equals(rwContactId)){
Toast.makeText(SearchResultActivity.this, "商家已存在", Toast.LENGTH_SHORT).show();
// String whereClause = ContactsContract.RawContacts.Data.RAW_CONTACT_ID + "= ? AND " + ContactsContract.Data.MIMETYPE + "=?";
//
// values.clear();
// values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
// values.put(StructuredName.DISPLAY_NAME, name);
// resolver.update(Data.CONTENT_URI, values, whereClause, new String[]{rwContactId, StructuredName.CONTENT_ITEM_TYPE });
//
// values.clear();
// values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
// values.put(Phone.NUMBER, tel);
// if(isMobilePhone(tel)){
// values.put(Phone.TYPE, Phone.TYPE_MOBILE);
// values.put(Phone.LABEL, Phone.TYPE_WORK_MOBILE);
// } else {
// values.put(Phone.TYPE, Phone.TYPE_WORK);
// values.put(Phone.LABEL, Phone.TYPE_WORK);
// }
// resolver.update(Data.CONTENT_URI, values, whereClause, new String[]{rwContactId, Phone.CONTENT_ITEM_TYPE});
//
// values.clear();
// values.put(Data.MIMETYPE, StructuredPostal.CONTENT_ITEM_TYPE);
// values.put(StructuredPostal.TYPE, StructuredPostal.TYPE_WORK);
// values.put(StructuredPostal.LABEL, StructuredPostal.TYPE_WORK);
// values.put(StructuredPostal.STREET, addr);
// resolver.update(Data.CONTENT_URI, values, whereClause, new String[]{rwContactId, StructuredPostal.CONTENT_ITEM_TYPE});
//
// Toast.makeText(SearchResultActivity.this, "联系人更新成功", Toast.LENGTH_SHORT).show();
} else {
Uri rawContactUri = resolver.insert(
RawContacts.CONTENT_URI, values);
long rawContactId = ContentUris.parseId(rawContactUri);
values.clear();
values.put(Data.RAW_CONTACT_ID, rawContactId);
values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
values.put(StructuredName.DISPLAY_NAME, name);
resolver.insert(Data.CONTENT_URI, values);
values.clear();
values.put(Data.RAW_CONTACT_ID, rawContactId);
values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
values.put(Phone.NUMBER, tel);
if(isMobilePhone(tel)){
values.put(Phone.TYPE, Phone.TYPE_MOBILE);
values.put(Phone.LABEL, Phone.TYPE_WORK_MOBILE);
} else {
values.put(Phone.TYPE, Phone.TYPE_WORK);
values.put(Phone.LABEL, Phone.TYPE_WORK);
}
resolver.insert(Data.CONTENT_URI, values);
values.clear();
values.put(Data.RAW_CONTACT_ID, rawContactId);
values.put(Data.MIMETYPE, StructuredPostal.CONTENT_ITEM_TYPE);
values.put(StructuredPostal.TYPE, StructuredPostal.TYPE_WORK);
values.put(StructuredPostal.LABEL, StructuredPostal.TYPE_WORK);
values.put(StructuredPostal.STREET, addr);
resolver.insert(Data.CONTENT_URI, values);
Toast.makeText(SearchResultActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
}
}
}
})
.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
return true;
}
};
public boolean isMobilePhone(String tel){
boolean flag = false;
if(tel!=null && tel.length()==11){
String reg = "^(13[0-9]|15[012356789]|18[0236789]|14[57])[0-9]{8}$";
flag = tel.matches(reg);
}
return flag;
}
/*
* 根据电话号码取得联系人姓名
*/
public void getPeople() {
String[] projection = { ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER};
// 将自己添加到 msPeers 中
Cursor cursor = this.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, // Which columns to return.
ContactsContract.CommonDataKinds.Phone.NUMBER + " = '021-65291718'", // WHERE clause.
null, // WHERE clause value substitution
null); // Sort order.
if( cursor == null ) {
return;
}
System.out.println(cursor.getCount());
for( int i = 0; i < cursor.getCount(); i++ )
{
cursor.moveToPosition(i);
// 取得联系人名字
int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
String name = cursor.getString(nameFieldColumnIndex);
System.out.println("联系人姓名:" + name);
Toast.makeText(SearchResultActivity.this, "联系人姓名:" + name, Toast.LENGTH_SHORT).show();
}
}
/*
* 根据联系人姓名取得ID
*/
public String getContactId(String name) {
String rawContactId = null;
String[] projection = { ContactsContract.RawContacts.Data.RAW_CONTACT_ID };
// 将自己添加到 msPeers 中
Cursor cursor = this.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, // Which columns to return.
ContactsContract.PhoneLookup.DISPLAY_NAME + " = '"+ name +"'", // WHERE clause.
null, // WHERE clause value substitution
null); // Sort order.
if( cursor == null ) {
return null;
} else if(cursor.getCount()>0){
cursor.moveToFirst();
// 取得联系人ID
int idFieldColumnIndex = cursor.getColumnIndex(ContactsContract.RawContacts.Data.RAW_CONTACT_ID);
rawContactId = cursor.getString(idFieldColumnIndex);
return rawContactId;
}
return null;
}
} | Java |
package com.besttone.search;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;
public class Client {
// -------------------------------------------------------------------------
private static Client instance;
private static String screenSize = "";
private static String deviceId = "";
private static float dencyRate = 1.0f;
private static DisplayMetrics display;
private Handler mHd;
private ThreadPoolExecutor mThreadPoorForLocal;
private ThreadPoolExecutor mThreadPoorForDownload;
private ThreadPoolExecutor mThreadPoorForRequest;
private Context mContext;
private final static String Tag="Client";
// public static UserInfo userInfo;
// public static WordInfo wordInfo;
// public static int dataType;
// public static boolean turnType;
// public static DrawCommon drawComm;
// public static GuessCommon guessComm;
// public static boolean rightWrong;
// -------------------------------------------------------------------------
private Client() {
instance = this;
mHd = new Handler();
mThreadPoorForLocal = new ThreadPoolExecutor(3, 6, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100));
mThreadPoorForRequest = new ThreadPoolExecutor(4, 8, 15, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100));
mThreadPoorForDownload = new ThreadPoolExecutor(2, 5, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100));
}
// -------------------------------------------------------------------------
public static void release() {
try {
instance.mThreadPoorForLocal.shutdownNow();
instance.mThreadPoorForRequest.shutdownNow();
instance.mThreadPoorForDownload.shutdownNow();
} catch (Exception e) {
e.printStackTrace();
}
instance = null;
}
// -------------------------------------------------------------------------
public static Client getInstance() {
if (instance == null) {
instance = new Client();
}
return instance;
}
// -------------------------------------------------------------------------
public static Handler getHandler() {
return getInstance().mHd;
}
// -------------------------------------------------------------------------
public static void postRunnable(Runnable r) {
getInstance().mHd.post(r);
}
// -------------------------------------------------------------------------
public static ThreadPoolExecutor getThreadPoolForLocal() {
return getInstance().mThreadPoorForLocal;
}
// -------------------------------------------------------------------------
public static ThreadPoolExecutor getThreadPoolForRequest() {
Log.d(Tag,"request");
return getInstance().mThreadPoorForRequest;
}
// -------------------------------------------------------------------------
public static ThreadPoolExecutor getThreadPoolForDownload() {
return getInstance().mThreadPoorForDownload;
}
// -------------------------------------------------------------------------
public static void initWithContext(Context context) {
getInstance().mContext = context;
display = new DisplayMetrics();
WindowManager wm = (WindowManager) context.getSystemService( Context.WINDOW_SERVICE );
if (null != wm) {
wm.getDefaultDisplay().getMetrics( display );
screenSize = display.widthPixels < display.heightPixels ? display.widthPixels + "x" + display.heightPixels : display.heightPixels
+ "x" + display.widthPixels;
dencyRate = display.density / 1.5f;
}
TelephonyManager tm = (TelephonyManager) context.getSystemService( Context.TELEPHONY_SERVICE );
if (null != tm) {
deviceId = tm.getDeviceId();
if (null == deviceId)
deviceId = "";
}
}
// -------------------------------------------------------------------------
public static Context getContext() {
return getInstance().mContext;
}
// -------------------------------------------------------------------------
public static String getDeviceId() {
return deviceId;
}
// -------------------------------------------------------------------------
public static String getScreenSize() {
return screenSize;
}
// -------------------------------------------------------------------------
public static float getDencyParam() {
return dencyRate;
}
// -------------------------------------------------------------------------
public static DisplayMetrics getDisplayMetrics() {
return display;
}
// -------------------------------------------------------------------------
public static boolean decetNetworkOn() {
try {
ConnectivityManager cm = (ConnectivityManager) getInstance().mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
if (null != cm ) {
NetworkInfo wi = cm.getActiveNetworkInfo();
if (null != wi)
return wi.isConnected();
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static boolean decetNetworkOn(Context c) {
ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
if (null != cm ) {
NetworkInfo info = cm.getActiveNetworkInfo();
if (null != info)
return info.isConnected();
}
return false;
}
public static Bundle getAppInfoBundle(Context context) {
Bundle bundle = null;
try {
ApplicationInfo appInfo = ((Activity)context).getPackageManager().getApplicationInfo(((Activity)context).getPackageName(), PackageManager.GET_META_DATA);
if (appInfo != null) {
bundle = appInfo.metaData;
}
PackageInfo pinfo = ((Activity)context).getPackageManager().getPackageInfo(((Activity)context).getPackageName(), PackageManager.GET_CONFIGURATIONS);
if(pinfo!=null)
{
bundle.putString("versionName", pinfo.versionName);
bundle.putInt("versionCode", pinfo.versionCode);
}
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return bundle;
}
/**
* 应用程序版本
* @param context
* @return
*/
public static int getVersion(Context context) {
int uVersion = 0;
Bundle bundle = getAppInfoBundle(context);
if (bundle != null) {
uVersion = bundle.getInt("versionCode");
}
return uVersion;
}
}
| Java |
package com.besttone.search;
import android.app.Application;
public class Ch114NewApplication extends Application {
@Override
public void onCreate() {
//appContext = getApplicationContext();
super.onCreate();
Client.getInstance();
}
}
| Java |
package com.besttone.search.sql;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class NativeDBHelper extends SQLiteOpenHelper {
public static final String AREA_CODE = "AREA_CODE";
public static final int AREA_CODE_INDEX = 9;
public static final String BUSINESS_FLAG = "BUSINESS_FLAG";
public static final int BUSINESS_FLAG_INDEX = 12;
public static final int DATABASE_VERSION = 1;
public static final String ENG_NAME = "ENG_NAME";
public static final int ENG_NAME_INDEX = 7;
public static final String FIRST_PY = "FIRST_PY";
public static final int FIRST_PY_INDEX = 6;
public static final String ID = "ID";
public static final int ID_INDEX = 0;
public static final String IS_FREQUENT = "IS_FREQUENT";
public static final int IS_FREQUENT_INDEX = 10;
public static final String NAME = "NAME";
public static final int NAME_INDEX = 4;
public static final String PARENT_REGION = "PARENT_REGION";
public static final int PARENT_REGION_INDEX = 2;
public static final String REGION_CODE = "REGION_CODE";
public static final int REGION_CODE_INDEX = 1;
public static final String SHORT_NAME = "SHORT_NAME";
public static final int SHORT_NAME_INDEX = 5;
public static final String SORT_VALUE = "SORT_VALUE";
public static final int SORT_VALUE_INDEX = 11;
public static final String TEL_LENGTH = "TEL_LENGTH";
public static final int TEL_LENGTH_INDEX = 8;
public static final String TYPE = "TYPE";
public static final String TYPE_CITY = "2";
public static final String TYPE_DISTRICT = "3";
public static final int TYPE_INDEX = 3;
public static final String TYPE_PROVINCE = "1";
private static NativeDBHelper sInstance;
private final String[] mColumns;
private NativeDBHelper(Context paramContext) {
super(paramContext, "native_database.db", null, 1);
String[] arrayOfString = new String[8];
arrayOfString[0] = "ID";
arrayOfString[1] = "REGION_CODE";
arrayOfString[2] = "PARENT_REGION";
arrayOfString[3] = "TYPE";
arrayOfString[4] = "SHORT_NAME";
arrayOfString[5] = "FIRST_PY";
arrayOfString[6] = "AREA_CODE";
arrayOfString[7] = "BUSINESS_FLAG";
this.mColumns = arrayOfString;
}
public static NativeDBHelper getInstance(Context paramContext) {
if (sInstance == null)
sInstance = new NativeDBHelper(paramContext);
return sInstance;
}
public void onCreate(SQLiteDatabase paramSQLiteDatabase) {
}
public void onUpgrade(SQLiteDatabase paramSQLiteDatabase, int paramInt1,
int paramInt2) {
}
public Cursor select(String[] paramArrayOfString1, String paramString,
String[] paramArrayOfString2) {
return getReadableDatabase().query("PUB_LOCATION", paramArrayOfString1,
paramString, paramArrayOfString2, null, null, null);
}
public Cursor selectAllCity() {
String[] arrayOfString = new String[1];
arrayOfString[0] = "2";
return select(this.mColumns, "TYPE=?", arrayOfString);
}
public Cursor selectCodeByName(String paramString) {
String[] arrayOfString = new String[1];
arrayOfString[0] = paramString;
return select(this.mColumns, "SHORT_NAME=?", arrayOfString);
}
public Cursor selectDistrict(String paramString) {
String[] arrayOfString = new String[2];
arrayOfString[0] = "3";
arrayOfString[1] = paramString;
return select(this.mColumns, "TYPE=? AND PARENT_REGION like ?",
arrayOfString);
}
public Cursor selectNameByCode(String paramString) {
String[] arrayOfString = new String[1];
arrayOfString[0] = paramString;
return select(this.mColumns, "REGION_CODE=?", arrayOfString);
}
} | Java |
package com.besttone.search;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PoiResultData {
public static List<Map<String, Object>> getData() {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
return list;
}
}
| Java |
package com.besttone.search;
import java.util.ArrayList;
import com.besttone.adapter.LetterListAdapter;
import com.besttone.search.CityListBaseActivity.AutoCityAdapter;
import com.besttone.search.model.City;
import com.besttone.search.sql.NativeDBHelper;
import com.besttone.search.util.Constants;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
public abstract class CityListBaseActivity extends Activity implements
AbsListView.OnScrollListener {
private Context mContext;
protected ArrayList<City> citylist = new ArrayList();
private Handler handler;
protected ArrayAdapter<String> mAutoAdapter;
protected EditText mAutoTextView;
protected ArrayList<String> autoCitylist = new ArrayList<String>();
protected String[] autoArray;
protected String[] mCityFirstLetter;
private TextView mDialogText;
protected int mHotCount = 0;
protected Cursor mHotCursor;
private String mLetter = "";
protected LetterListAdapter mListAdapter;
protected ListView mListView;
private RemoveWindow mRemoveWindow;
private int mScroll;
private boolean mShowing = false;
private NativeDBHelper mDB;
private WindowManager windowManager;
protected AutoCityAdapter mAutoCityAdapter;
protected ListView mAutoListView;
private final TextWatcher textWatcher = new TextWatcher() {
private int selectionEnd;
private int selectionStart;
private CharSequence temp;
public void afterTextChanged(Editable paramEditable) {
this.selectionStart = CityListBaseActivity.this.mAutoTextView
.getSelectionStart();
this.selectionEnd = CityListBaseActivity.this.mAutoTextView
.getSelectionEnd();
if (this.temp.length() > 25) {
Toast.makeText(CityListBaseActivity.this, "temp 长度大于25", Toast.LENGTH_SHORT).show();
paramEditable.delete(this.selectionStart - (-25 + this.temp.length()),
this.selectionEnd);
int i = this.selectionStart;
CityListBaseActivity.this.mAutoTextView.setText(paramEditable);
CityListBaseActivity.this.mAutoTextView.setSelection(i);
}
//获取mAutoTextView结果
String str = temp.toString();
Cursor localCursor = null;
String[] arrayParm = new String[2];
arrayParm[0] = "2";
arrayParm[1] = (str + "%");
autoCitylist = new ArrayList<String>();
String[] mColumns = {"FIRST_PY", "SHORT_NAME"};
// Log.d("selectCity", "search");
// Log.i("arrayParm[0]", "search"+arrayParm[0]);
// Log.i("arrayParm[q]", "search"+arrayParm[1]);
if(Constants.isAlphabet(str)) {
localCursor =mDB.select(mColumns, "TYPE=? AND FIRST_PY like ?",arrayParm);
} else {
localCursor =mDB.select(mColumns, "TYPE=? AND SHORT_NAME like ?",arrayParm);
}
if (localCursor!=null && localCursor.getCount()>0) {
localCursor.moveToFirst();
while (true) {
if (localCursor.isAfterLast()) {
localCursor.close();
break;
}
autoCitylist.add(localCursor.getString(0) + "," + localCursor.getString(1));
// Log.i("result", localCursor.getString(0) + "," + localCursor.getString(1));
localCursor.moveToNext();
}
}
autoArray = autoCitylist.toArray(new String[autoCitylist.size()]);
// mAutoAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_dropdown_item_1line, autoArray);
// mAutoTextView.setAdapter(mAutoAdapter);
// for(int i=0;i<autoArray.length;i++)
// Log.i("autoArray[i]", "result"+autoArray[i]);
if(str.length()>0&&autoArray.length>0)
{
mAutoListView.setVisibility(View.VISIBLE);
}
else
{
mAutoListView.setVisibility(View.GONE);
}
mAutoCityAdapter.notifyDataSetChanged();
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
this.temp = s;
}
public void onTextChanged(CharSequence s, int start, int count,
int after) {
}
};
private void init() {
this.mDialogText = ((TextView) ((LayoutInflater) getSystemService("layout_inflater")).inflate(R.layout.select_city_position_dialog, null));
this.mDialogText.setVisibility(4);
this.mRemoveWindow = new RemoveWindow();
this.handler = new Handler();
this.windowManager = getWindowManager();
setAdapter();
this.mListView.setOnScrollListener(this);
this.mListView.setFastScrollEnabled(true);
initAutoData();
mAutoTextView = (EditText)this.findViewById(R.id.change_city_auto_text);
// this.mAutoTextView.setAdapter(this.mAutoAdapter);
// this.mAutoTextView.setThreshold(1);
this.mAutoTextView.addTextChangedListener(this.textWatcher);
mDB = NativeDBHelper.getInstance(this);
}
private void initFirstLetter() {
setFirstletter();
initDBHelper();
addHotCityFirstLetter();
this.mHotCount = this.citylist.size();
addCityFirstLetter();
}
private void removeWindow() {
if (!this.mShowing)
;
while (true) {
this.mShowing = false;
this.mDialogText.setVisibility(4);
return;
}
}
public abstract void addCityFirstLetter();
public abstract void addHotCityFirstLetter();
public abstract void initAutoData();
public abstract void initDBHelper();
protected void onCreate(Bundle paramBundle) {
super.onCreate(paramBundle);
requestWindowFeature(1);
setTheContentView();
mContext = this.getApplicationContext();
initFirstLetter();
init();
setListViewOnItemClickListener();
setAutoCompassTextViewOnItemClickListener();
// mAutoTextView.setAdapter(mAutoCityAdapter);
}
public void onScroll(AbsListView paramAbsListView, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
this.mScroll = (1 + this.mScroll);
if (this.mScroll >= 2) {
while (true) {
int i = firstVisibleItem - 1 + visibleItemCount / 2;
String str = ((City) this.mListView.getAdapter().getItem(i))
.getFirstLetter();
if (str == null)
continue;
this.mShowing = true;
this.mDialogText.setVisibility(0);
this.mDialogText.setText(str);
this.mLetter = str;
this.handler.removeCallbacks(this.mRemoveWindow);
this.handler.postDelayed(this.mRemoveWindow, 3000L);
return;
}
}
}
public void onScrollStateChanged(AbsListView paramAbsListView, int paramInt) {
}
protected void onStart() {
super.onStart();
WindowManager.LayoutParams localLayoutParams = new WindowManager.LayoutParams(
-1, -1, 2, 24, -3);
this.windowManager.addView(this.mDialogText, localLayoutParams);
this.mScroll = 0;
}
protected void onStop() {
super.onStop();
try {
this.mScroll = 0;
this.windowManager.removeView(this.mDialogText);
return;
} catch (Exception localException) {
while (true)
localException.printStackTrace();
}
}
public abstract void setAdapter();
public abstract void setAutoCompassTextViewOnItemClickListener();
public abstract void setFirstletter();
public abstract void setListViewOnItemClickListener();
public abstract void setTheContentView();
final class RemoveWindow implements Runnable {
private RemoveWindow() {
}
public void run() {
CityListBaseActivity.this.removeWindow();
}
}
public class AutoCityAdapter extends BaseAdapter
{
private LayoutInflater mInflater;
public AutoCityAdapter(Context context) {
this.mInflater = LayoutInflater.from(context);
autoArray = new String[1];
}
public int getCount()
{
return autoArray.length;
}
public Object getItem(int position)
{
return autoArray[position];
}
public long getItemId(int position)
{
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
convertView = mInflater.inflate(R.layout.auto_city_item, null);
Log.i("adapt", "getDropDownView");
String searchRecord = autoArray[position];
((TextView) convertView.findViewById(R.id.auto_city_info)).setText(searchRecord);
return convertView;
}
}
}
| Java |
package com.besttone.search.dialog;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import com.besttone.search.Client;
import com.besttone.search.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.StatFs;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class ProgressBarDialog extends Dialog
{
private ProgressBar mProgress;
private TextView mProgressNumber;
private TextView mProgressPercent;
public static final int M = 1024 * 1024;
public static final int K = 1024;
private double dMax;
private double dProgress;
private int middle = K;
private int prev = 0;
private Handler mViewUpdateHandler;
private int fileSize;
private int downLoadFileSize;
private static final NumberFormat nf = NumberFormat.getPercentInstance();
private static final DecimalFormat df = new DecimalFormat("###.##");
private static final int msg_init = 0;
private static final int msg_update = 1;
private static final int msg_complete = 2;
private static final int msg_error = -1;
private String mUrl;
private File fileOut;
private String downloadPath;
public ProgressBarDialog(Context context)
{
super(context);
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
LayoutInflater inflater = LayoutInflater.from(getContext());
mViewUpdateHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
super.handleMessage(msg);
if (!Thread.currentThread().isInterrupted())
{
// Log.i("msg what", String.valueOf(msg.what));
switch (msg.what)
{
case msg_init:
// pbr.setMax(fileSize);
mProgress.setMax(100);
break;
case msg_update:
setDProgress((double) downLoadFileSize);
break;
case msg_complete:
setTitle("文件下载完成");
break;
case msg_error:
String error = msg.getData().getString("更新失败");
setTitle(error);
break;
default:
break;
}
}
double precent = dProgress / dMax;
if (prev != (int) (precent * 100))
{
mProgress.setProgress((int) (precent * 100));
mProgressNumber.setText(df.format(dProgress) + "/" + df.format(dMax) + (middle == K ? "K" : "M"));
mProgressPercent.setText(nf.format(precent));
prev = (int) (precent * 100);
}
}
};
View view = inflater.inflate(R.layout.dialog_progress_bar, null);
mProgress = (ProgressBar) view.findViewById(R.id.progress);
mProgress.setMax(100);
mProgressNumber = (TextView) view.findViewById(R.id.progress_number);
mProgressPercent = (TextView) view.findViewById(R.id.progress_percent);
setContentView(view);
onProgressChanged();
super.onCreate(savedInstanceState);
}
private void onProgressChanged()
{
mViewUpdateHandler.sendEmptyMessage(0);
}
public double getDMax()
{
return dMax;
}
public void setDMax(double max)
{
if (max > M)
{
middle = M;
}
else
{
middle = K;
}
dMax = max / middle;
}
public double getDProgress()
{
return dProgress;
}
public void setDProgress(double progress)
{
dProgress = progress / middle;
onProgressChanged();
}
// String downloadPath = Environment.getExternalStorageDirectory().getPath()
// + "/download_cache";
public void downLoadFile(final String httpUrl)
{
this.mUrl = httpUrl;
File sdDir = null;
boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
// 判断sd卡是否存在
if (sdCardExist)
{
sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
if (getAvailableExternalMemorySize() < 50000000)
{
Toast.makeText(Client.getContext(), "存储空间不足", Toast.LENGTH_SHORT).show();
dismiss();
return;
}
}
else
{
Toast.makeText(Client.getContext(), "SD卡不存在", Toast.LENGTH_SHORT).show();
dismiss();
return;
}
downloadPath = sdDir + "/114update";
Client.getThreadPoolForDownload().execute(new Runnable()
{
@Override
public void run()
{
// TODO Auto-generated method stub
URL url = null;
try
{
url = new URL(mUrl);
String fileName = mUrl.substring(mUrl.lastIndexOf("/"));
// String downloadPath = sdDir+"/114update";
File tmpFile = new File(downloadPath);
if (!tmpFile.exists())
{
tmpFile.mkdir();
}
fileOut = new File(downloadPath + fileName);
// URL url = new URL(appurl);
// URL url = new URL(mUrl);
HttpURLConnection con;
con = (HttpURLConnection) url.openConnection();
InputStream in;
in = con.getInputStream();
fileSize = con.getContentLength();
setDMax((double) fileSize);
FileOutputStream out = new FileOutputStream(fileOut);
byte[] bytes = new byte[1024];
downLoadFileSize = 0;
setDProgress((double) downLoadFileSize);
sendMsg(msg_init);
int c;
while ((c = in.read(bytes)) != -1)
{
out.write(bytes, 0, c);
downLoadFileSize += c;
sendMsg(msg_update);// 更新进度条
}
in.close();
out.close();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
sendMsg(msg_error);// error
}
sendMsg(msg_complete);// 下载完成
Client.postRunnable(new Runnable()
{
@Override
public void run()
{
// TODO Auto-generated method stub
dismiss();
installApk(fileOut);
exitApp();
}
});
}
});
}
private void sendMsg(int flag)
{
Message msg = new Message();
msg.what = flag;
mViewUpdateHandler.sendMessage(msg);
}
private void installApk(File file)
{
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
String type = "application/vnd.android.package-archive";
intent.setDataAndType(Uri.fromFile(file), type);
Client.getContext().startActivity(intent);
Log.e("success", "the end");
}
// 彻底关闭程序
protected void exitApp()
{
Client.release();
System.exit(0);
// 或者下面这种方式
// android.os.Process.killProcess(android.os.Process.myPid());
}
public static long getAvailableExternalMemorySize()
{
if (externalMemoryAvailable())
{
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
return availableBlocks * blockSize;
}
else
{
return msg_error;
}
}
public static boolean externalMemoryAvailable()
{
return android.os.Environment.getExternalStorageState()
.equals(android.os.Environment.MEDIA_MOUNTED);
}
} | Java |
package com.besttone.search;
import java.io.File;
import com.besttone.http.UpdateRequest;
import com.besttone.http.UpdateRequest.UpdateListener;
import com.besttone.search.dialog.ProgressBarDialog;
import com.besttone.search.model.City;
import com.besttone.search.model.PhoneInfo;
import com.besttone.search.util.Constants;
import com.besttone.search.util.LogUtils;
import com.besttone.search.util.PhoneUtil;
import com.besttone.search.util.SharedUtils;
import com.besttone.search.util.StringUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
public class SplashActivity extends Activity {
private final int TIME_UP = 1;
protected Context mContext;
protected UpdateRequest r;
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == TIME_UP) {
Intent intent = new Intent();
intent.setClass(SplashActivity.this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.splash_screen_fade,
R.anim.splash_screen_hold);
SplashActivity.this.finish();
}
}
};
public void onCreate(Bundle paramBundle) {
super.onCreate(paramBundle);
setContentView(R.layout.splash_screen_view);
initApp();
initCity();
initPhoneInfo();
Client.initWithContext(this);
detectUpdate();
// new Thread() {
// public void run() {
// try {
// Thread.sleep(500);
// } catch (Exception e) {
//
// }
// Message msg = new Message();
// msg.what = TIME_UP;
// handler.sendMessage(msg);
// }
// }.start();
}
private void initApp() {
initNativeDB();
}
private void initNativeDB() {
SharedPreferences localSharedPreferences = getSharedPreferences(
"NativeDB", 0);
if (1 > localSharedPreferences.getInt("Version", 0)) {
Constants.copyNativeDB(this,
getResources().openRawResource(R.raw.native_database));
localSharedPreferences.edit().putInt("Version", 1).commit();
}
Constants.copyNativeDB(this,
getResources().openRawResource(R.raw.native_database));
localSharedPreferences.edit().putInt("Version", 1).commit();
}
private boolean isUnSelectedCity() {
if ((!SharedUtils.isFirstSelectedCityComplete(this.mContext))
|| (StringUtils.isEmpty(SharedUtils
.getCurrentCityName(this.mContext)))
|| (StringUtils.isEmpty(SharedUtils
.getCurrentCityCode(this.mContext)))
|| (StringUtils.isEmpty(SharedUtils
.getCurrentProvinceCode(this.mContext)))) {
return true;
}
return false;
}
private void initCity() {
City localCity = new City();
localCity.setCityName("上海");
localCity.setCityCode("310000");
localCity.setSimplifyCode("31");
localCity.setCityId("75");
localCity.setProvinceCode("310000");
SharedUtils.setCurrentCity(this, localCity);
}
public void initPhoneInfo() {
TelephonyManager tm = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
String imei = tm.getDeviceId(); //IMEI
String provider = tm.getNetworkOperatorName(); //运营商
String imsi = tm.getSubscriberId(); //IMSI
PhoneUtil util = new PhoneUtil();
PhoneInfo info = null;
try {
if(NetWorkStatus()) {
//info = util.getPhoneNoByIMSI(imsi);
}
} catch (Exception e) {
e.printStackTrace();
}
if(info==null)
info = new PhoneInfo();
info.setImei(imei);
info.setImsi(imsi);
info.setProvider(provider);
SharedUtils.setCurrentPhoneInfo(this, info);
}
private boolean NetWorkStatus() {
boolean netSataus = false;
ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
cwjManager.getActiveNetworkInfo();
if (cwjManager.getActiveNetworkInfo() != null) {
netSataus = cwjManager.getActiveNetworkInfo().isAvailable();
}
// if (netSataus) {
// Builder b = new AlertDialog.Builder(this).setTitle("没有可用的网络").setMessage("是否对网络进行设置?");
// b.setPositiveButton("是", new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int whichButton) {
// Intent mIntent = new Intent("/");
// ComponentName comp = new ComponentName("com.android.settings",
// "com.android.settings.WirelessSettings");
// mIntent.setComponent(comp);
// mIntent.setAction("android.intent.action.VIEW");
// startActivityForResult(mIntent,0); // 如果在设置完成后需要再次进行操作,可以重写操作代码,在这里不再重写
// }
// }).setNeutralButton("否", new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int whichButton) {
// dialog.cancel();
// }
// }).show();
// }
return netSataus;
}
private void detectUpdate() {
r = new UpdateRequest();
r.setListener(new UpdateListener() {
@Override
public void onUpdateNoNeed(String msg) {
gotoLogin();
}
public void onUpdateMust(String msg, final String url) {
AlertDialog.Builder b = new AlertDialog.Builder(Client.getContext());
b.setTitle("程序必须升级才能继续");
b.setMessage(msg+"\r\n"+url);
b.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
System.gc();
}
});
b.setPositiveButton("升级",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
gotoUpdate(url);
}
});
b.setCancelable(false);
b.show();
}
public void onUpdateError(short code, Exception e) {
AlertDialog.Builder b = new AlertDialog.Builder(Client.getContext());
b.setTitle("升级验证失败");
b.setMessage("请检查网络...");
b.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
System.gc();
}
});
b.setCancelable(false);
b.show();
}
public void onUpdateAvaiable(String msg, final String url) {
AlertDialog.Builder b = new AlertDialog.Builder(Client.getContext());
b.setTitle("程序可以升级,请选择");
b.setMessage(msg+"\r\n"+url);
b.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
gotoLogin();
}
});
b.setPositiveButton("升级",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
gotoUpdate(url);
}
});
b.setCancelable(false);
b.show();
}
});
if (Client.decetNetworkOn())
{
// Log.d("check","on");
r.checkUpdate();
}
else {
// Log.d("check","off");
gotoLogin();
Toast.makeText(Client.getContext(), "网络异常,没有可用网络",
Toast.LENGTH_SHORT).show();
}
}
private void gotoLogin() {
new Thread() {
public void run() {
try {
Thread.sleep(500);
} catch (Exception e) {
}
Message msg = new Message();
msg.what = TIME_UP;
handler.sendMessage(msg);
}
}.start();
}
private void gotoUpdate(String url) {
if (TextUtils.isEmpty(url)) {
Toast.makeText(this, "升级的地址有误", Toast.LENGTH_SHORT).show();
finish();
System.gc();
return;
}
// url = url.toLowerCase();
if (url.startsWith("www")) {
url = "http://" + url;
}
if (url.startsWith("http")) {
try {
// Uri u = Uri.parse(url);
ProgressBarDialog pbd=new ProgressBarDialog(Client.getContext());
pbd.setTitle("下载中");
pbd.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
gotoLogin();
}
});
pbd.show();
pbd.downLoadFile(url);
// Intent i = new Intent( Intent.ACTION_VIEW, u );
// startActivity( i );
// finish();
System.gc();
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
| Java |
package com.besttone.search;
import java.util.List;
public interface ServerListener
{
void serverDataArrived(List list, boolean isEnd);
}
| Java |
package com.besttone.search;
import com.besttone.app.SuggestionProvider;
import com.besttone.search.R.color;
import com.besttone.search.util.LogUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.SearchRecentSuggestions;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.TextView;
public class MainActivity extends Activity
{
private GridView grid;
private DisplayMetrics localDisplayMetrics;
private View view;
private Button btn_city_search;
private Button mSearchBtn;
private SearchRecentSuggestions suggestions;
public void onCreate(Bundle bundle)
{
super.onCreate(bundle);
requestWindowFeature(Window.FEATURE_NO_TITLE);
view = this.getLayoutInflater().inflate(R.layout.main, null);
setContentView(view);
btn_city_search = (Button) findViewById(R.id.btn_city);
btn_city_search.setOnClickListener(searchCityListner);
mSearchBtn = ((Button)findViewById(R.id.start_search));
mSearchBtn.setOnClickListener(searchHistroyListner);
localDisplayMetrics = getResources().getDisplayMetrics();
suggestions = new SearchRecentSuggestions(this,
SuggestionProvider.AUTHORITY, SuggestionProvider.MODE);
grid = (GridView)view.findViewById(R.id.my_grid);
ListAdapter adapter = new GridAdapter(this);
grid.setAdapter(adapter);
grid.setOnItemClickListener(mOnClickListener);
}
private Button.OnClickListener searchHistroyListner = new Button.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, SearchActivity.class);
startActivity(intent);
}
};
private Button.OnClickListener searchCityListner = new Button.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, SelectCityActivity.class);
intent.putExtra("SelectCityName", btn_city_search.getText().toString());
startActivityForResult(intent, 100);
}
};
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
LogUtils.i("resultCode:" + resultCode + ", requestCode:" + requestCode);
String str = null;
String cityName = (String) this.btn_city_search.getText();
if (resultCode == RESULT_OK) {
str = data.getStringExtra("cityName");
LogUtils.d(LogUtils.LOG_TAG, "new city:" + str);
LogUtils.d(LogUtils.LOG_TAG, "old city:" + cityName);
super.onActivityResult(requestCode, resultCode, data);
this.btn_city_search.setText(str);
}
}
private AdapterView.OnItemClickListener mOnClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position,long id) {
TextView text = (TextView)v.findViewById(R.id.activity_name);
String keyword = text.getText().toString();
Intent intent = new Intent();
if (keyword != null) {
if ("更多".equals(keyword)) {
intent.setClass(MainActivity.this, MoreKeywordActivity.class);
startActivity(intent);
} else {
intent.setClass(MainActivity.this, SearchResultActivity.class);
Bundle bundle = new Bundle();
bundle.putString("keyword", keyword);
intent.putExtras(bundle);
suggestions.saveRecentQuery(keyword, null);
startActivity(intent);
}
}
}
};
public class GridAdapter extends BaseAdapter
{
private LayoutInflater inflater;
public GridAdapter(Context context)
{
inflater = LayoutInflater.from(context);
}
public final int getCount()
{
return 6;
}
public final Object getItem(int paramInt)
{
return null;
}
public final long getItemId(int paramInt)
{
return paramInt;
}
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup)
{
paramView = inflater.inflate(R.layout.activity_label_item, null);
TextView text = (TextView)paramView.findViewById(R.id.activity_name);
text.setTextSize(15);
text.setTextColor(color.text_color_grey);
switch(paramInt)
{
case 0:
{
text.setText("KTV");
Drawable draw = getResources().getDrawable(R.drawable.ktv);
draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
text.setCompoundDrawables(null, draw, null, null);
break;
}
case 1:
{
text.setText("宾馆");
Drawable draw = getResources().getDrawable(R.drawable.hotel);
draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
text.setCompoundDrawables(null, draw, null, null);
break;
}
case 2:
{
text.setText("加油站");
Drawable draw = getResources().getDrawable(R.drawable.gas);
draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
text.setCompoundDrawables(null, draw, null, null);
break;
}
case 3:
{
text.setText("川菜");
Drawable draw = getResources().getDrawable(R.drawable.chuan);
draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
text.setCompoundDrawables(null, draw, null, null);
break;
}
case 4:
{
text.setText("快递");
Drawable draw = getResources().getDrawable(R.drawable.kuaidi);
draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
text.setCompoundDrawables(null, draw, null, null);
break;
}
case 5:
{
text.setText("更多");
Drawable draw = getResources().getDrawable(R.drawable.more);
draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
text.setCompoundDrawables(null, draw, null, null);
break;
}
// case 6:
// {
// text.setText("最近浏览");
// Drawable draw = getResources().getDrawable(R.drawable.home_button_history);
// draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
// text.setCompoundDrawables(null, draw, null, null);
// break;
// }
//
// case 7:
// {
// text.setText("个人中心");
// Drawable draw = getResources().getDrawable(R.drawable.home_button_myzone);
// draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
// text.setCompoundDrawables(null, draw, null, null);
// break;
// }
// case 8:
// {
// text.setText("更多");
// Drawable draw = getResources().getDrawable(R.drawable.home_button_more);
// draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
// text.setCompoundDrawables(null, draw, null, null);
// break;
// }
}
paramView.setMinimumHeight((int)(96.0F * localDisplayMetrics.density));
paramView.setMinimumWidth(((-12 + localDisplayMetrics.widthPixels) / 3));
return paramView;
}
}
protected static final int MENU_ABOUT = Menu.FIRST;
protected static final int MENU_Quit = Menu.FIRST+1;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_ABOUT, 0, " 关于 ...");
menu.add(0, MENU_Quit, 0, " 结束 ");
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case MENU_ABOUT:
openOptionsDialog();
break;
case MENU_Quit:
showExitAlert();
break;
}
return true;
}
private void openOptionsDialog() {
new AlertDialog.Builder(MainActivity.this)
.setTitle(R.string.about_title)
.setMessage(R.string.about_msg)
.setPositiveButton(R.string.confirm,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i) {}
})
.setNegativeButton(R.string.homepage_label,
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialoginterface, int i){
//go to url
Uri uri = Uri.parse(getString(R.string.homepage_uri));
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
})
.show();
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
// 按下键盘上返回按钮
if(keyCode == KeyEvent.KEYCODE_BACK ){
showExitAlert();
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
private void showExitAlert() {
new AlertDialog.Builder(this)
.setTitle(R.string.prompt)
.setMessage(R.string.quit_desc)
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {}
})
.setPositiveButton(R.string.confirm,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
exitApp();
}
}).show();
}
//彻底关闭程序
protected void exitApp() {
super.onDestroy();
Client.release();
System.exit(0);
// 或者下面这种方式
// android.os.Process.killProcess(android.os.Process.myPid());
}
}
| Java |
package com.besttone.search;
import java.util.ArrayList;
import java.util.List;
import com.besttone.widget.AlphabetBar;
import android.R.integer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.besttone.adapter.CityListAdapter;
import com.besttone.search.model.City;
import com.besttone.search.sql.NativeDBHelper;
import com.besttone.search.util.LogUtils;
import com.besttone.search.util.SharedUtils;
public class SelectCityActivity extends CityListBaseActivity {
private ImageButton btn_back;
private Context mContext;
private NativeDBHelper mDB;
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
//this.imm = ((InputMethodManager)getSystemService("input_method"));
btn_back = (ImageButton) findViewById(R.id.left_title_button);
btn_back.setOnClickListener(backListner);
}
private ImageButton.OnClickListener backListner = new ImageButton.OnClickListener() {
public void onClick(View v) {
finish();
}
};
private void selectComplete(City paramCity) {
String simplifyCode = "";
if(paramCity!=null && paramCity.getCityCode()!=null) {
simplifyCode = paramCity.getCityCode();
if(simplifyCode.endsWith("00")) {
simplifyCode = simplifyCode.substring(0, simplifyCode.length()-2);
}
if(simplifyCode.endsWith("00")) {
simplifyCode = simplifyCode.substring(0, simplifyCode.length()-2);
}
}
paramCity.setSimplifyCode(simplifyCode);
SharedUtils.setCurrentCity(this.mContext, paramCity);
Intent localIntent = getIntent();
localIntent.putExtra("cityName", paramCity.getCityName());
setResult(RESULT_OK, localIntent);
finish();
}
@Override
public void addCityFirstLetter() {
if (this.mCityFirstLetter.length <= 0)
return;
String str = null;
Cursor localCursor = null;
for (int i = 1; i < this.mCityFirstLetter.length; i++) {
str = this.mCityFirstLetter[i];
String[] arrayParm = new String[2];
arrayParm[0] = "2";
arrayParm[1] = (str + "%");
localCursor = this.mDB.select(null, "TYPE=? AND FIRST_PY like ?",
arrayParm);
if (localCursor != null)
if (localCursor.moveToNext()) {
City localCity1 = new City();
localCity1.setCityName("-1");
localCity1.setFirstLetter(str);
this.citylist.add(localCity1);
}
while (true) {
if (localCursor.isAfterLast()) {
localCursor.close();
break;
}
City localCity2 = new City();
localCity2.setBusinessFlag(localCursor.getString(12));
localCity2.setCityCode(localCursor.getString(1));
localCity2.setCityId(localCursor.getString(0));
localCity2.setCityName(localCursor.getString(5));
localCity2.setFirstPy(localCursor.getString(6));
localCity2.setAreaCode(localCursor.getString(9));
localCity2.setProvinceCode(localCursor.getString(2));
localCity2.setFirstLetter(str);
this.citylist.add(localCity2);
localCursor.moveToNext();
}
}
}
public void addHotCityFirstLetter() {
if (this.mCityFirstLetter.length <= 0)
return;
String str;
do {
str = this.mCityFirstLetter[0];
} while (this.mHotCursor == null);
if (this.mHotCursor.moveToNext()) {
City localCity1 = new City();
localCity1.setCityName("-1");
localCity1.setFirstLetter(str);
this.citylist.add(localCity1);
}
while (true) {
if (this.mHotCursor.isAfterLast()) {
this.mHotCursor.close();
break;
}
City localCity2 = new City();
localCity2.setBusinessFlag(this.mHotCursor.getString(12));
localCity2.setCityCode(this.mHotCursor.getString(1));
localCity2.setCityId(this.mHotCursor.getString(0));
localCity2.setCityName(this.mHotCursor.getString(5));
localCity2.setFirstPy(this.mHotCursor.getString(6));
localCity2.setAreaCode(this.mHotCursor.getString(9));
localCity2.setProvinceCode(this.mHotCursor.getString(2));
localCity2.setFirstLetter(str);
this.citylist.add(localCity2);
this.mHotCursor.moveToNext();
}
}
public void initAutoData() {
ArrayList localArrayList = new ArrayList();
for (int i = this.mHotCount;; i++) {
if (i >= this.citylist.size()) {
this.mAutoAdapter = new ArrayAdapter(this, R.id.selected_item,
R.id.city_info, localArrayList);
return;
}
City localCity = (City) this.citylist.get(i);
if ((localCity.getFirstPy() == null)
|| (localCity.getCityName() == null))
continue;
localArrayList.add(localCity.getCityName());
localArrayList.add(localCity.getFirstPy() + ","
+ localCity.getCityName());
}
}
public void initDBHelper() {
this.mAutoTextView = ((EditText) findViewById(R.id.change_city_auto_text));
this.mDB = NativeDBHelper.getInstance(this);
this.mHotCursor = this.mDB.select(null,
"IS_FREQUENT = '1' ORDER BY CAST(SORT_VALUE AS INTEGER)", null);
}
public void setAdapter() {
this.mListView = ((ListView) findViewById(R.id.city_list));
this.mListAdapter = new CityListAdapter(this, this.citylist);
this.mListView.setAdapter(this.mListAdapter);
this.mAutoListView = ((ListView) findViewById(R.id.auto_city_list));
this.mAutoCityAdapter = new AutoCityAdapter(this);
this.mAutoListView.setAdapter(this.mAutoCityAdapter);
this.mAutoListView.setVisibility(View.GONE);
}
public void setAutoCompassTextViewOnItemClickListener() {
mAutoListView.setOnItemClickListener(cityAutoTvOnClickListener);
// this.mAutoTextView.setOnItemClickListener(cityAutoTvOnClickListener);
}
public void setFirstletter() {
this.mCityFirstLetter = getResources().getStringArray(
R.array.city_first_letter);
}
public void setListViewOnItemClickListener() {
this.mListView.setOnItemClickListener(cityLvOnClickListener);
}
public void setTheContentView() {
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.select_city);
}
private AdapterView.OnItemClickListener cityLvOnClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
ListView listView = (ListView) parent;
City localCity = (City) listView.getItemAtPosition(position);
if (!"-1".equals(localCity.getCityName())) {
// Toast.makeText(SelectCityActivity.this,
// "你选择的城市是" + localCity.getCityName(), Toast.LENGTH_SHORT)
// .show();
selectComplete(localCity);
}
}
};
private AdapterView.OnItemClickListener cityAutoTvOnClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
String str1 = (String) mAutoCityAdapter.getItem(position);
if (str1.contains(",")) {
for (String str2 = str1.split(",")[1];; str2 = str1) {
String[] arrayOfString = new String[2];
arrayOfString[0] = "2";
arrayOfString[1] = str2.trim();
Cursor localCursor = mDB.select(null, "TYPE=? AND SHORT_NAME=?",
arrayOfString);
if (localCursor.moveToFirst()) {
City localCity = new City();
localCity.setAreaCode(localCursor.getString(9));
localCity.setCityCode(localCursor.getString(1));
localCity.setCityId(localCursor.getString(0));
localCity.setCityName(localCursor.getString(5));
localCity.setProvinceCode(localCursor.getString(2));
selectComplete(localCity);
}
return;
}
}
}
};
protected void onPause() {
super.onPause();
//this.imm.hideSoftInputFromInputMethod(this.mAutoTextView.getWindowToken(), 0);
}
protected void onResume() {
super.onResume();
//this.imm.hideSoftInputFromInputMethod(this.mAutoTextView.getWindowToken(), 0);
}
public void onScrollStateChanged(AbsListView paramAbsListView, int paramInt) {
}
}
| Java |
package com.besttone.search;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.SearchRecentSuggestions;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.besttone.app.SuggestionProvider;
import com.besttone.http.WebServiceHelper;
import com.besttone.http.WebServiceHelper.WebServiceListener;
import com.besttone.search.util.SharedUtils;
import com.besttone.widget.EditSearchBar;
import com.besttone.widget.EditSearchBar.OnKeywordChangeListner;
import java.util.ArrayList;
import java.util.List;
public class SearchActivity extends Activity implements EditSearchBar.OnKeywordChangeListner{
private View view;
private ImageButton btn_back;
private ListView histroyListView;
private EditText field_keyword;
private Button mSearchBtn;
private ImageButton mClearBtn;
private EditSearchBar editSearchBar;
private HistoryAdapter historyAdapter;
private ArrayList<String> historyData = new ArrayList<String>();
private ArrayList<String> keywordList = new ArrayList<String>();
private SearchRecentSuggestions suggestions;
private Handler mhandler=new Handler();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
view = this.getLayoutInflater().inflate(R.layout.search_histroy, null);
setContentView(view);
suggestions = new SearchRecentSuggestions(this,
SuggestionProvider.AUTHORITY, SuggestionProvider.MODE);
histroyListView = (ListView) findViewById(R.id.search_histroy);
historyAdapter = new HistoryAdapter(this);
histroyListView.setAdapter(historyAdapter);
histroyListView.setOnItemClickListener(mOnClickListener);
field_keyword = (EditText) findViewById(R.id.search_edit);
mSearchBtn = (Button) findViewById(R.id.begin_search);
mSearchBtn.setOnClickListener(searchListner);
// mClearBtn = (ImageButton) findViewById(R.id.search_clear);
// mClearBtn.setOnClickListener(clearListner);
btn_back = (ImageButton) findViewById(R.id.left_title_button);
btn_back.setOnClickListener(backListner);
editSearchBar = (EditSearchBar)findViewById(R.id.search_bar);
editSearchBar.setOnKeywordChangeListner(this);
}
private ImageButton.OnClickListener backListner = new ImageButton.OnClickListener() {
public void onClick(View v) {
finish();
}
};
private ImageButton.OnClickListener clearListner = new ImageButton.OnClickListener() {
public void onClick(View v) {
mClearBtn.setVisibility(View.GONE);
field_keyword.setHint(R.string.search_hint);
}
};
private Button.OnClickListener searchListner = new Button.OnClickListener() {
public void onClick(View v) {
if(NetWorkStatus()) {
String keyword = field_keyword.getText().toString();
if(keyword!=null && !"".equals(keyword)) {
String simplifyCode = SharedUtils.getCurrentSimplifyCode(SearchActivity.this);
Log.v("simplifyCode", simplifyCode);
Intent intent = new Intent();
intent.setClass(SearchActivity.this, SearchResultActivity.class);
Bundle bundle = new Bundle();
bundle.putString("simplifyCode", simplifyCode);
bundle.putString("keyword", keyword);
intent.putExtras(bundle);
suggestions.saveRecentQuery(keyword, null);
finish();
startActivity(intent);
} else {
Toast.makeText(SearchActivity.this, "搜索关键词为空", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(SearchActivity.this, "网络异常,没有可用网络", Toast.LENGTH_SHORT).show();
}
}
};
private ListView.OnItemClickListener mOnClickListener = new ListView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
ListView listView = (ListView) parent;
String searchHistory = (String) listView.getItemAtPosition(position);
if(searchHistory!=null && "清空搜索记录".equals(searchHistory)){
suggestions.clearHistory();
finish();
} else if(!"没有搜索记录".equals(searchHistory)){
Intent intent = new Intent();
intent.setClass(SearchActivity.this, SearchResultActivity.class);
Bundle bundle = new Bundle();
bundle.putString("keyword", searchHistory);
intent.putExtras(bundle);
finish();
startActivity(intent);
}
}
};
public class HistoryAdapter extends BaseAdapter
{
private LayoutInflater mInflater;
public HistoryAdapter(Context context) {
this.mInflater = LayoutInflater.from(context);
historyData = getData();
}
public int getCount()
{
return historyData.size();
}
public Object getItem(int position)
{
return historyData.get(position);
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mInflater.inflate(R.layout.search_history_item, null);
String searchRecord = historyData.get(position);
((TextView) convertView.findViewById(R.id.history_text1)).setText(searchRecord);
return convertView;
}
}
public ArrayList<String> getData() {
historyData = new ArrayList<String>();
String sortStr = " _id desc";
ContentResolver contentResolver = getContentResolver();
Uri quri = Uri.parse("content://" + SuggestionProvider.AUTHORITY + "/suggestions");
Cursor localCursor = contentResolver.query(quri, SuggestionProvider.COLUMNS, null, null, sortStr);
if (localCursor!=null && localCursor.getCount()>0) {
localCursor.moveToFirst();
while (true) {
if (localCursor.isAfterLast()) {
localCursor.close();
break;
}
historyData.add(localCursor.getString(1));
localCursor.moveToNext();
}
}
return historyData;
}
private boolean NetWorkStatus() {
boolean netSataus = false;
ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
cwjManager.getActiveNetworkInfo();
if (cwjManager.getActiveNetworkInfo() != null) {
netSataus = cwjManager.getActiveNetworkInfo().isAvailable();
}
return netSataus;
}
public void onKeywordChanged(final String paramString) {
//获取联想关键词
final WebServiceHelper serviceHelper = new WebServiceHelper();
if(paramString!=null && !"".equals(paramString)){
Client.getThreadPoolForRequest().execute(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
keywordList=serviceHelper.getAssociateList(paramString);
if(keywordList!=null && keywordList.size()>0){
historyData = keywordList;
}else{
historyData = getData();
}
Client.postRunnable(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
// for(int i=0;i<historyData.size();i++)
// {
// Log.d("historyData",""+historyData.get(i));
// }
historyAdapter.notifyDataSetChanged();
}
});
}
});
} else {
historyData = getData();
historyAdapter.notifyDataSetChanged();
}
// ArrayList<String> keywordList = new ArrayList<String>();
// WebServiceHelper serviceHelper = new WebServiceHelper();
// if(paramString!=null && !"".equals(paramString)){
// keywordList = serviceHelper.getAssociateList(paramString);
// } else {
// historyData = getData();
// }
//
// if(keywordList!=null && keywordList.size()>0){
// historyData = keywordList;
// }else{
// historyData = getData();
// }
// historyAdapter.notifyDataSetChanged();
}
} | Java |
package com.besttone.search.util;
import com.besttone.search.model.RequestInfo;
public class XmlHelper {
public static String getRequestXml(RequestInfo info) {
StringBuilder sb = new StringBuilder("");
if(info!=null) {
sb.append("<RequestInfo>");
sb.append("<region><![CDATA["+info.getRegion()+"]]></region>");
sb.append("<deviceid><![CDATA["+info.getDeviceid()+"]]></deviceid>");
sb.append("<imsi><![CDATA["+info.getImsi()+"]]></imsi>");
sb.append("<content><![CDATA["+info.getContent()+"]]></content>");
if(info.getPage()!=null){
sb.append("<Page><![CDATA["+info.getPage()+"]]></Page>");
}
if(info.getPageSize()!=null){
sb.append("<PageSize><![CDATA["+info.getPageSize()+"]]></PageSize>");
}
if(info.getMobile()!=null){
sb.append("<mobile><![CDATA["+info.getMobile()+"]]></mobile>");
}
if(info.getMobguishu()!=null){
sb.append("<mobguishu><![CDATA["+info.getMobguishu()+"]]></mobguishu>");
}
sb.append("</RequestInfo>");
}
return sb.toString();
}
}
| Java |
package com.besttone.search.util;
public class LogUtils {
public static final boolean IF_LOG = false;
public static final String LOG_TAG = "zwj-code";
public static void d(String paramString) {
}
public static void d(String paramString1, String paramString2) {
}
public static void e(String paramString) {
}
public static void e(String paramString1, String paramString2) {
}
public static void e(String paramString, Throwable paramThrowable) {
}
public static void i(String paramString) {
}
public static void i(String paramString1, String paramString2) {
}
} | Java |
package com.besttone.search.util;
public class StringUtils {
public static String getDateByTime(String paramString) {
if ((isEmpty(paramString)) || (paramString.length() < 16));
while (true) {
paramString = paramString.substring(0, 10);
}
}
public static String getString(String paramString) {
if ((paramString == null) || ("null".equals(paramString))
|| ("NULL".equals(paramString)))
paramString = "";
return paramString;
}
public static boolean isEmpty(String paramString) {
if (paramString == null)
return true;
if (paramString!=null && paramString.trim().length() == 0)
return true;
return false;
}
public static String toZero(String paramString) {
if (paramString == null)
paramString = "0";
return paramString;
}
}
| Java |
package com.besttone.search.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import com.besttone.search.model.City;
import com.besttone.search.model.PhoneInfo;
public class SharedUtils {
public static final String Custom_Channel = "custom_channel";
public static final String Data_Selected_City = "Data_Selected_City";
public static final String First_Selected_City = "First_Selected_City";
public static final String Location_AreaCode = "Location_AreaCode";
public static final String Location_City = "Location_City";
public static final String Location_CityCode = "Location_CityCode";
public static final String Location_CityId = "Location_CityId";
public static final String Location_ProvinceCode = "Location_ProvinceCode";
public static final String NOTIFICATION_SET = "notification_set";
public static final String SHORT_CUT_INSTALLED = "short_cut_installed";
public static final String Switch_City_Notice = "Switch_City_Notice";
public static final String Total_Channel = "total_channel";
public static SharedPreferences mPreference;
public static String getCurrentCityCode(Context paramContext) {
return getPreference(paramContext).getString("Location_CityCode", "");
}
public static String getCurrentCityId(Context paramContext) {
return getPreference(paramContext).getString("Location_CityId", "");
}
public static String getCurrentCityName(Context paramContext) {
return getPreference(paramContext).getString("Location_City", "");
}
public static String getCurrentProvinceCode(Context paramContext) {
return getPreference(paramContext).getString("Location_ProvinceCode",
"");
}
public static String getCurrentSimplifyCode(Context paramContext) {
return getPreference(paramContext).getString("Location_SimplifyCode", "");
}
public static long getNotificationHistory(Context paramContext,
String paramString) {
return getPreference(paramContext).getLong(paramString, 0L);
}
public static int getNotificationSet(Context paramContext) {
return getPreference(paramContext).getInt("notification_set", 0);
}
public static SharedPreferences getPreference(Context paramContext) {
if (mPreference == null)
mPreference = PreferenceManager
.getDefaultSharedPreferences(paramContext);
return mPreference;
}
public static String getUseVersion(Context paramContext) {
return getPreference(paramContext).getString("USE_VERSION", "");
}
public static String getVersionChannelList(Context paramContext) {
String str1 = getUseVersion(paramContext);
String str2 = getPreference(paramContext).getString(
"CHANNEL_VERSION_" + str1, "");
LogUtils.d("getCityChannelList: CHANNEL_VERSION_" + str1 + ", " + str2);
return str2;
}
public static boolean hasShowHelp(Context paramContext) {
return getPreference(paramContext).getBoolean("SHOW_HELP", false);
}
public static boolean isFirstSelectedCityComplete(Context paramContext) {
return getPreference(paramContext).getBoolean("First_Selected_City",
false);
}
public static boolean isShortCutInstalled(Context paramContext) {
return getPreference(paramContext).getBoolean("short_cut_installed",
false);
}
public static boolean isShowSwitchCityNotice(Context paramContext) {
return getPreference(paramContext).getBoolean("Switch_City_Notice",
true);
}
public static void setCurrentCity(Context paramContext, City paramCity) {
SharedPreferences.Editor localEditor = getPreference(paramContext)
.edit();
localEditor.putString("Location_City", paramCity.getCityName());
localEditor.putString("Location_CityCode", paramCity.getCityCode());
localEditor.putString("Location_CityId", paramCity.getCityId());
localEditor.putString("Location_ProvinceCode",
paramCity.getProvinceCode());
localEditor.putString("Location_AreaCode", paramCity.getAreaCode());
localEditor.putString("Location_SimplifyCode", paramCity.getSimplifyCode());
LogUtils.d("setCurrentCity================");
LogUtils.d("cityCode:" + paramCity.getCityCode());
LogUtils.d("cityName:" + paramCity.getCityName());
LogUtils.d("areaCode:" + paramCity.getAreaCode());
LogUtils.d("SimplifyCode:" + paramCity.getSimplifyCode());
localEditor.commit();
}
public static void setFirstSelectedCityComplete(Context paramContext) {
getPreference(paramContext).edit()
.putBoolean("First_Selected_City", true).commit();
}
public static void setNotificationHistory(Context paramContext,
String paramString, long paramLong) {
if (!TextUtils.isEmpty(paramString)) {
getPreference(paramContext).edit().putLong(paramString, paramLong)
.commit();
LogUtils.d("SET:" + paramString + " ," + paramLong);
}
}
public static void setNotificationSet(Context paramContext, int paramInt) {
getPreference(paramContext).edit().putInt("notification_set", paramInt)
.commit();
}
public static void setShortCutInstalled(Context paramContext) {
getPreference(paramContext).edit()
.putBoolean("short_cut_installed", true).commit();
}
public static void setShowHelp(Context paramContext) {
getPreference(paramContext).edit().putBoolean("SHOW_HELP", true)
.commit();
}
public static void setSwitchCityNotice(Context paramContext,
boolean paramBoolean) {
getPreference(paramContext).edit()
.putBoolean("Switch_City_Notice", paramBoolean).commit();
}
public static void setUseVersion(Context paramContext, String paramString) {
getPreference(paramContext).edit()
.putString("USE_VERSION", paramString).commit();
LogUtils.d("setUseVersion: " + paramString);
}
public static void setVersionChannelList(Context paramContext,
String paramString1, String paramString2) {
getPreference(paramContext).edit()
.putString("CHANNEL_VERSION_" + paramString1, paramString2)
.commit();
LogUtils.d("setCityChannelList: CHANNEL_VERSION_" + paramString1 + ", "
+ paramString2);
}
public static boolean versionListExist(Context paramContext,
String paramString) {
if (getPreference(paramContext).contains(
"CHANNEL_VERSION_" + paramString))
LogUtils.d("Version:" + paramString + "Exist!");
return true;
}
public static void setCurrentPhoneInfo(Context paramContext, PhoneInfo info) {
SharedPreferences.Editor localEditor = getPreference(paramContext)
.edit();
localEditor.putString("Phone_DeviceId", info.getImei());
localEditor.putString("Phone_Imsi", info.getImsi());
localEditor.putString("Phone_No", info.getPhoneNo());
localEditor.putString("Phone_Provider", info.getProvider());
localEditor.commit();
}
public static String getCurrentPhoneDeviceId(Context paramContext) {
return getPreference(paramContext).getString("Phone_DeviceId", "");
}
public static String getCurrentPhoneImsi(Context paramContext) {
return getPreference(paramContext).getString("Phone_Imsi", "");
}
public static String getCurrentPhoneNo(Context paramContext) {
return getPreference(paramContext).getString("Phone_No", "");
}
public static String getCurrentPhoneProvider(Context paramContext) {
return getPreference(paramContext).getString("Phone_Provider", "");
}
} | Java |
package com.besttone.search.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Logger;
public class MD5Builder {
public static Logger logger = Logger.getLogger("MD5Builder");
// 用来将字节转换成 16 进制表示的字符
public static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
/**
* 对文件全文生成MD5摘要
*
* @param file
* 要加密的文件
* @return MD5摘要码
*/
public static String getMD5(File file) {
FileInputStream fis = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
logger.info("MD5摘要长度:" + md.getDigestLength());
fis = new FileInputStream(file);
byte[] buffer = new byte[2048];
int length = -1;
logger.info("开始生成摘要");
long s = System.currentTimeMillis();
while ((length = fis.read(buffer)) != -1) {
md.update(buffer, 0, length);
}
logger.info("摘要生成成功,总用时: " + (System.currentTimeMillis() - s)
+ "ms");
byte[] b = md.digest();
return byteToHexString(b);
// 16位加密
// return buf.toString().substring(8, 24);
} catch (Exception ex) {
ex.printStackTrace();
return null;
} finally {
try {
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/**
* 对一段String生成MD5加密信息
*
* @param message
* 要加密的String
* @return 生成的MD5信息
*/
public static String getMD5(String message) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
logger.info("MD5摘要长度:" + md.getDigestLength());
byte[] b = md.digest(message.getBytes());
return byteToHexString(b);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
/**
* 把byte[]数组转换成十六进制字符串表示形式
*
* @param tmp
* 要转换的byte[]
* @return 十六进制字符串表示形式
*/
private static String byteToHexString(byte[] tmp) {
String s;
// 用字节表示就是 16 个字节
char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话,使用两个字符,
// 所以表示成 16 进制需要 32 个字符
int k = 0; // 表示转换结果中对应的字符位置
for (int i = 0; i < 16; i++) { // 从第一个字节开始,对 MD5 的每一个字节
// 转换成 16 进制字符的转换
byte byte0 = tmp[i]; // 取第 i 个字节
str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换,
// >>> 为逻辑右移,将符号位一起右移
str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换
}
s = new String(str); // 换后的结果转换为字符串
return s;
}
/**
*
* @param message
* @return
*/
public static String getMD5Str(String source) {
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance("MD5");
byte[] byteArray = messageDigest.digest(source.getBytes("UTF-8"));
StringBuffer md5StrBuff = new StringBuffer();
for (int i = 0; i < byteArray.length; i++) {
if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
} else {
md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
}
}
return md5StrBuff.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
String tmp = "sasdfafd";
System.out.println(getMD5(tmp));
System.out.println(getMD5Str(tmp));
}
} | Java |
package com.besttone.search.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.besttone.search.model.City;
import com.besttone.search.model.District;
import com.besttone.search.sql.NativeDBHelper;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.util.DisplayMetrics;
public class Constants {
public static String appKey = "50D033D17E0140F1919EF0508FC9A41E";
public static String appSecret = "35D31BE854EC4F2BAF9F9A61821C7460";
public static String apiName = "mobile";
public static String apiMethod = "getMobileByIMSI";
// public static String serverAddress =
// "http://116.228.55.196:8060/open_api/";
public static String serverAddress = "http://open.118114.cn/api";
// public static String serverAddress = "http://116.228.55.106/api";
public static String abServerAddress = "http://openapi.aibang.com/search";
// public static String abAppKey = "a312b2321506db8a3a566370fdca7e29";
public static String abAppKey = "f41c8afccc586de03a99c86097e98ccb";
public static String SPACE = "";
public static int PAGE_SIZE = 10;
// 测试地址
public static final String serviceURL = "http://116.228.55.13:8085/ch_trs_ws/ch_search";
public static String chName= "jichu_client";
public static String chKey = "123456";
//public static final String serviceURL = "http://116.228.55.103:9273/ch_trs_ws/ch_search";
// public static String chName = "jichu_client";
// public static String chKey = "j0c7c2t9";
//关键词联想
public static String associate_method = "searchCHkeyNum";
public static final String NATIVE_DATABASE_NAME = "native_database.db";
public static int mDeviceHeight;
public static int mDeviceWidth = 0;
static {
mDeviceHeight = 0;
}
public static void copyNativeDB(Context paramContext,
InputStream paramInputStream) {
try {
File localFile1 = new File("/data/data/"
+ paramContext.getPackageName() + "/databases/");
if (!localFile1.exists())
localFile1.mkdir();
String str = "/data/data/" + paramContext.getPackageName()
+ "/databases/" + "native_database.db";
File localFile2 = new File(str);
if (localFile2.exists())
localFile2.delete();
FileOutputStream localFileOutputStream = new FileOutputStream(str);
byte[] arrayOfByte = new byte[18000];
while (true) {
int i = paramInputStream.read(arrayOfByte);
if (i <= 0) {
localFileOutputStream.close();
paramInputStream.close();
break;
}
localFileOutputStream.write(arrayOfByte, 0, i);
}
} catch (Exception localException) {
}
}
public static City getCity(Context paramContext, String paramString) {
City localCity = null;
if ((paramString != null) && (!paramString.equals(""))) {
NativeDBHelper localNativeDBHelper = NativeDBHelper
.getInstance(paramContext);
String[] arrayOfString = new String[2];
arrayOfString[0] = "2";
arrayOfString[1] = paramString.trim();
Cursor localCursor = localNativeDBHelper.select(null,
"TYPE=? AND REGION_CODE=?", arrayOfString);
if ((localCursor != null) && (localCursor.getCount() > 0)
&& (localCursor.moveToFirst())) {
localCity = new City();
localCity.setAreaCode(localCursor.getString(9));
localCity.setCityCode(localCursor.getString(1));
localCity.setCityId(localCursor.getString(0));
localCity.setCityName(localCursor.getString(5));
localCity.setProvinceCode(localCursor.getString(2));
}
if (localCursor != null)
localCursor.close();
if (localNativeDBHelper != null)
localNativeDBHelper.close();
}
return localCity;
}
public static String getCityCode(Context paramContext, String paramString) {
String str = "";
if ((paramString != null) && (!paramString.equals(""))) {
NativeDBHelper localNativeDBHelper = NativeDBHelper
.getInstance(paramContext);
if (!paramString.startsWith("0"))
paramString = "0" + paramString;
String[] arrayOfString1 = new String[4];
arrayOfString1[0] = "ID";
arrayOfString1[1] = "REGION_CODE";
arrayOfString1[2] = "NAME";
arrayOfString1[3] = "AREA_CODE";
String[] arrayOfString2 = new String[2];
arrayOfString2[0] = "2";
arrayOfString2[1] = paramString;
Cursor localCursor = localNativeDBHelper.select(arrayOfString1,
"TYPE=? AND AREA_CODE=?", arrayOfString2);
if ((localCursor != null) && (localCursor.getCount() > 0)
&& (localCursor.moveToFirst()))
str = localCursor.getString(1);
if (localCursor != null)
localCursor.close();
if (localNativeDBHelper != null)
localNativeDBHelper.close();
}
return str;
}
public static String getCodeByName(Context paramContext, String paramString) {
String str = null;
NativeDBHelper localNativeDBHelper = NativeDBHelper
.getInstance(paramContext);
Cursor localCursor = localNativeDBHelper.selectCodeByName(paramString);
if ((localCursor != null) && (localCursor.getCount() > 0))
localCursor.moveToFirst();
while (true) {
if (localCursor.isAfterLast()) {
if (localCursor != null)
localCursor.close();
if (localNativeDBHelper != null)
localNativeDBHelper.close();
}
str = localCursor.getString(1);
localCursor.moveToNext();
return str;
}
}
public static String getSimplifyCodeByName(Context paramContext, String paramString) {
String cityCode = getCodeByName(paramContext, paramString);
return getSimplifyCode(cityCode);
}
public static int getDeviceWidth(Activity paramActivity) {
if (mDeviceWidth == 0) {
DisplayMetrics localDisplayMetrics = new DisplayMetrics();
paramActivity.getWindowManager().getDefaultDisplay()
.getMetrics(localDisplayMetrics);
mDeviceWidth = localDisplayMetrics.widthPixels;
}
return mDeviceWidth;
}
public static String[] getDistrictArray(Context paramContext, String paramString)
{
String[] arrayOfString = null;
List localList = getDistrictList(paramContext, paramString);
if ((localList != null) && (localList.size() > 0))
{
arrayOfString = new String[1 + localList.size()];
arrayOfString[0] = "全部区域";
}
for (int i = 0; ; i++)
{
if (i >= localList.size())
return arrayOfString;
arrayOfString[(i + 1)] = ((District)localList.get(i)).getDistrictName();
}
}
public static List<District> getDistrictList(Context paramContext, String paramString)
{
ArrayList localArrayList = null;
NativeDBHelper localNativeDBHelper = NativeDBHelper.getInstance(paramContext);
paramString = paramString.substring(0,2) + "%";
Cursor localCursor = localNativeDBHelper.selectDistrict(paramString);
if ((localCursor != null) && (localCursor.getCount() > 0))
{
localArrayList = new ArrayList();
localCursor.moveToFirst();
}
while (true)
{
if (localCursor.isAfterLast())
{
if (localCursor != null)
localCursor.close();
if (localNativeDBHelper != null)
localNativeDBHelper.close();
return localArrayList;
}
District localDistrict = new District();
localDistrict.setDistrictId(localCursor.getString(0));
localDistrict.setDistrictName(localCursor.getString(4));
localDistrict.setDistrictCode(localCursor.getString(1));
localDistrict.setCityCode(localCursor.getString(2));
String simplifyCode = localCursor.getString(2);
if (simplifyCode != null && simplifyCode.endsWith("00")) {
simplifyCode = simplifyCode.substring(0,
simplifyCode.length() - 2);
}
if (simplifyCode != null && simplifyCode.endsWith("00")) {
simplifyCode = simplifyCode.substring(0,
simplifyCode.length() - 2);
}
localDistrict.setSimplifyCode(simplifyCode);
localArrayList.add(localDistrict);
localCursor.moveToNext();
}
}
public static JSONObject getJSONObject(HashMap<String, String> paramHashMap) {
JSONObject localJSONObject = new JSONObject();
Iterator localIterator = paramHashMap.entrySet().iterator();
while (true) {
if (!localIterator.hasNext())
return localJSONObject;
Map.Entry localEntry = (Map.Entry) localIterator.next();
try {
localJSONObject.put((String) localEntry.getKey(),
localEntry.getValue());
} catch (JSONException localJSONException) {
localJSONException.printStackTrace();
}
}
}
public static String getNameByCode(Context paramContext, String paramString) {
String str = null;
NativeDBHelper localNativeDBHelper = NativeDBHelper
.getInstance(paramContext);
Cursor localCursor = localNativeDBHelper.selectNameByCode(paramString);
if ((localCursor != null) && (localCursor.getCount() > 0))
localCursor.moveToFirst();
while (true) {
if (localCursor.isAfterLast()) {
if (localCursor != null)
localCursor.close();
if (localNativeDBHelper != null)
localNativeDBHelper.close();
return str;
}
str = localCursor.getString(4);
localCursor.moveToNext();
}
}
public static String getProvinceId(Context paramContext, String paramString) {
String str = "";
if (!StringUtils.isEmpty(paramString)) {
NativeDBHelper localNativeDBHelper = NativeDBHelper
.getInstance(paramContext);
String[] arrayOfString1 = new String[1];
arrayOfString1[0] = "ID";
String[] arrayOfString2 = new String[2];
arrayOfString2[0] = "1";
arrayOfString2[1] = paramString;
Cursor localCursor = localNativeDBHelper.select(arrayOfString1,
"TYPE=? AND REGION_CODE=?", arrayOfString2);
if ((localCursor != null) && (localCursor.getCount() > 0)
&& (localCursor.moveToFirst()))
str = localCursor.getString(0);
if (localCursor != null)
localCursor.close();
if (localNativeDBHelper != null)
localNativeDBHelper.close();
}
return str;
}
public static boolean isBusinessOpen(Context paramContext,
String paramString) {
boolean flag = false;
if ((paramString != null) && (!paramString.equals(""))) {
NativeDBHelper localNativeDBHelper = NativeDBHelper
.getInstance(paramContext);
String[] arrayOfString1 = new String[1];
arrayOfString1[0] = "BUSINESS_FLAG";
String[] arrayOfString2 = new String[1];
arrayOfString2[0] = paramString;
Cursor localCursor = localNativeDBHelper.select(arrayOfString1,
"REGION_CODE=?", arrayOfString2);
if ((localCursor != null) && (localCursor.getCount() > 0)
&& (localCursor.moveToFirst())) {
String str = localCursor.getString(0);
if ((str != null) && (str.equals("1")))
flag = true;
}
if (localCursor != null)
localCursor.close();
if (localNativeDBHelper != null)
localNativeDBHelper.close();
}
return flag;
}
public static String getSimplifyCode(String cityCode) {
if(cityCode!=null) {
if(cityCode.endsWith("00")) {
cityCode = cityCode.substring(0, cityCode.length()-2);
}
if(cityCode.endsWith("00")) {
cityCode = cityCode.substring(0, cityCode.length()-2);
}
}
return cityCode;
}
public static boolean isAlphabet(String s) {
if(s!=null) {
return s.matches("^[a-zA-Z]*$");
}
return false;
}
public static String getCity(String s){
String city = null;
if(s!=null && s.trim().length()!=0) {
String[] cityArray = s.split("\\|\\|");
int index = cityArray.length - 1;
city = cityArray[index];
}
return city;
}
}
| Java |
package com.besttone.search.util;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.util.Log;
import com.besttone.search.model.PhoneInfo;
public class PhoneUtil {
private static final String TAG = "PhoneUtil";
public PhoneInfo getPhoneNoByIMSI(String imsi) throws Exception {
PhoneInfo info;
// 生成请求xml
String reqXml = createParm(imsi);
//返回XML
String rtnXml = getRtnXml(reqXml);
//DOM方式解析XML
info = dealXml(rtnXml);
return info;
}
public PhoneInfo dealXml(String rtnXml) {
PhoneInfo info = new PhoneInfo();
try {
// 创建解析工厂
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// 指定DocumentBuilder
DocumentBuilder builder = factory.newDocumentBuilder();
// 从文件构造一个Document,因为XML文件中已经指定了编码,所以这里不必了
ByteArrayInputStream is = new ByteArrayInputStream(rtnXml.getBytes("UTF-8"));
Document document = builder.parse(is);
//得到Document的根
Element root = document.getDocumentElement();
NodeList nodes = root.getElementsByTagName("data");
// 遍历根节点所有子节点
for (int i = 0; i < nodes.getLength(); i++) {
// 获取data元素节点
Element phoneElement = (Element) (nodes.item(i));
// 获取data中mobile属性值
info.setPhoneNo(phoneElement.getAttribute("mobile"));
}
NodeList list = root.getElementsByTagName("error");
// 遍历根节点所有子节点
for (int i = 0; i < list.getLength(); i++) {
info.setErrorFlag(true);
Element errElement = (Element) (list.item(i));
// 获取errorCode属性
NodeList codeNode = errElement.getElementsByTagName("errorCode");
// 获取errorCode元素
Element codeElement = (Element)codeNode.item(0);
//获得errorCode元素的第一个值
String errorCode = codeElement.getFirstChild().getNodeValue();
info.setErrorCode(errorCode);
// 获取errorMsg属性
NodeList msgNode = errElement.getElementsByTagName("errorMessage");
// 获取errorMsg元素
Element msgElement = (Element)msgNode.item(0);
//获得errorMsg元素的第一个值
String errorMsg = msgElement.getFirstChild().getNodeValue();
info.setErrorMsg(errorMsg);
}
} catch (Exception e) {
Log.e(TAG, "XML解析出错;"+e.getMessage());
}
return info;
}
public String getRtnXml(String reqXml) throws UnsupportedEncodingException,
IOException, ClientProtocolException {
//返回XML
String rtnXml = "";
//http地址
StringBuilder requestUrl = new StringBuilder(Constants.serverAddress);
String parm = "?reqXml=" + URLEncoder.encode(reqXml, "UTF-8") + "&sign=" + MD5Builder.getMD5Str(reqXml + Constants.appSecret);
requestUrl.append(parm);
String httpUrl = requestUrl.toString();
//HttpGet连接对象
HttpGet httpRequest = new HttpGet(httpUrl);
//取得HttpClient对象
HttpClient httpclient = new DefaultHttpClient();
//请求HttpClient,取得HttpResponse
HttpResponse httpResponse = httpclient.execute(httpRequest);
//请求成功
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//取得返回的字符串
rtnXml = EntityUtils.toString(httpResponse.getEntity()).trim();
}
return rtnXml;
}
public String createParm(String imsi) {
StringBuffer parmXml = new StringBuffer("");
parmXml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
parmXml.append("<reqXML version=\"1.0\">");
String appKeyParm = "<appKey>" + Constants.appKey + "</appKey>";
String apiNameParm = "<apiName>" + Constants.apiName + "</apiName>";
String apiMethodParm = "<apiMethod>" + Constants.apiMethod + "</apiMethod>";
String timestampParm = "<timestamp>" + getTimeStamp() + "</timestamp>";
parmXml.append(appKeyParm);
parmXml.append(apiNameParm);
parmXml.append(apiMethodParm);
parmXml.append(timestampParm);
parmXml.append("<params>");
String mobileParm = "<param name=\"imsi\" value=\"" + imsi + "\"/>";
parmXml.append(mobileParm);
parmXml.append("</params>");
parmXml.append("</reqXML>");
String parmXmlStr = parmXml.toString();
return parmXmlStr;
}
public String getTimeStamp() {
String timestamp = "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
timestamp = sdf.format(new Date());
return timestamp;
}
}
| Java |
package com.besttone.search.model;
public class PhoneInfo {
private String model; //手机型号
private String phoneNo; //手机号码
private String imei; //IMEI
private String simSN; //sim卡序列号
private String country; //国家
private String providerNo; //运营商编号
private String provider; //运营商
private String imsi;
private boolean errorFlag = false;//错误标志位
private String errorCode = "";//错误代码
private String errorMsg = "";//错误信息
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public String getImei() {
return imei;
}
public void setImei(String imei) {
this.imei = imei;
}
public String getSimSN() {
return simSN;
}
public void setSimSN(String simSN) {
this.simSN = simSN;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getProviderNo() {
return providerNo;
}
public void setProviderNo(String providerNo) {
this.providerNo = providerNo;
}
public String getProvider() {
return provider;
}
public void setProvider(String provider) {
this.provider = provider;
}
public String getImsi() {
return imsi;
}
public void setImsi(String imsi) {
this.imsi = imsi;
}
public boolean isErrorFlag() {
return errorFlag;
}
public void setErrorFlag(boolean errorFlag) {
this.errorFlag = errorFlag;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
} | Java |
package com.besttone.search.model;
public class OrgInfo {
private String name;
private String tel;
private String addr;
private int chId;
private String orgId;
private String city;
private int regionCode;
private int isQymp;
private int isDc;
private int isDf;
private long relevance;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public int getChId() {
return chId;
}
public void setChId(int chId) {
this.chId = chId;
}
public String getOrgId() {
return orgId;
}
public void setOrgId(String orgId) {
this.orgId = orgId;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getRegionCode() {
return regionCode;
}
public void setRegionCode(int regionCode) {
this.regionCode = regionCode;
}
public int getIsQymp() {
return isQymp;
}
public void setIsQymp(int isQymp) {
this.isQymp = isQymp;
}
public int getIsDc() {
return isDc;
}
public void setIsDc(int isDc) {
this.isDc = isDc;
}
public int getIsDf() {
return isDf;
}
public void setIsDf(int isDf) {
this.isDf = isDf;
}
public long getRelevance() {
return relevance;
}
public void setRelevance(long relevance) {
this.relevance = relevance;
}
}
| Java |
package com.besttone.search.model;
import java.io.Serializable;
public class City implements Serializable {
private static final long serialVersionUID = 4060207134630300518L;
private String areaCode;
private String businessFlag;
private String cityCode;
private String cityId;
private String cityName;
private String firstLetter;
private String firstPy;
private String isFrequent;
private String provinceCode;
private String provinceId;
private String simplifyCode;
public String getAreaCode() {
return areaCode;
}
public void setAreaCode(String areaCode) {
this.areaCode = areaCode;
}
public String getBusinessFlag() {
return businessFlag;
}
public void setBusinessFlag(String businessFlag) {
this.businessFlag = businessFlag;
}
public String getCityCode() {
return cityCode;
}
public void setCityCode(String cityCode) {
this.cityCode = cityCode;
}
public String getCityId() {
return cityId;
}
public void setCityId(String cityId) {
this.cityId = cityId;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getFirstLetter() {
return firstLetter;
}
public void setFirstLetter(String firstLetter) {
this.firstLetter = firstLetter;
}
public String getFirstPy() {
return firstPy;
}
public void setFirstPy(String firstPy) {
this.firstPy = firstPy;
}
public String getIsFrequent() {
return isFrequent;
}
public void setIsFrequent(String isFrequent) {
this.isFrequent = isFrequent;
}
public String getProvinceCode() {
return provinceCode;
}
public void setProvinceCode(String provinceCode) {
this.provinceCode = provinceCode;
}
public String getProvinceId() {
return provinceId;
}
public void setProvinceId(String provinceId) {
this.provinceId = provinceId;
}
public String getSimplifyCode() {
return simplifyCode;
}
public void setSimplifyCode(String simplifyCode) {
this.simplifyCode = simplifyCode;
}
}
| Java |
package com.besttone.search.model;
import java.io.Serializable;
public class District implements Serializable {
private static final long serialVersionUID = 1428165031459553637L;
private String cityCode;
private String simplifyCode;
private String districtCode;
private String districtId;
private String districtName;
public String getCityCode() {
return cityCode;
}
public void setCityCode(String cityCode) {
this.cityCode = cityCode;
}
public String getSimplifyCode() {
return simplifyCode;
}
public void setSimplifyCode(String simplifyCode) {
this.simplifyCode = simplifyCode;
}
public String getDistrictCode() {
return districtCode;
}
public void setDistrictCode(String districtCode) {
this.districtCode = districtCode;
}
public String getDistrictId() {
return districtId;
}
public void setDistrictId(String districtId) {
this.districtId = districtId;
}
public String getDistrictName() {
return districtName;
}
public void setDistrictName(String districtName) {
this.districtName = districtName;
}
}
| Java |
package com.besttone.search.model;
import java.util.List;
public class ChResultInfo {
private String source;
private String searchFlag;
private int count;
private int searchTime;
private List<OrgInfo> orgList;
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getSearchFlag() {
return searchFlag;
}
public void setSearchFlag(String searchFlag) {
this.searchFlag = searchFlag;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getSearchTime() {
return searchTime;
}
public void setSearchTime(int searchTime) {
this.searchTime = searchTime;
}
public List<OrgInfo> getOrgList() {
return orgList;
}
public void setOrgList(List<OrgInfo> orgList) {
this.orgList = orgList;
}
}
| Java |
package com.besttone.search.model;
public class RequestInfo {
private String region;
private String deviceid;
private String imsi;
private String content;
private String Page;
private String PageSize;
private String mobile;
private String mobguishu;
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getDeviceid() {
return deviceid;
}
public void setDeviceid(String deviceid) {
this.deviceid = deviceid;
}
public String getImsi() {
return imsi;
}
public void setImsi(String imsi) {
this.imsi = imsi;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getPage() {
return Page;
}
public void setPage(String page) {
Page = page;
}
public String getPageSize() {
return PageSize;
}
public void setPageSize(String pageSize) {
PageSize = pageSize;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getMobguishu() {
return mobguishu;
}
public void setMobguishu(String mobguishu) {
this.mobguishu = mobguishu;
}
}
| Java |
package com.besttone.search;
import com.besttone.app.SuggestionProvider;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.SearchRecentSuggestions;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
public class MoreKeywordActivity extends Activity {
private View view;
private ImageButton btn_back;
private ListView keywordListView;
private String[] mKeywordArray = null;
private SearchRecentSuggestions suggestions;
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
requestWindowFeature(Window.FEATURE_NO_TITLE);
view = this.getLayoutInflater().inflate(R.layout.more_keyword, null);
setContentView(view);
btn_back = (ImageButton) findViewById(R.id.left_title_button);
btn_back.setOnClickListener(backListner);
suggestions = new SearchRecentSuggestions(this,
SuggestionProvider.AUTHORITY, SuggestionProvider.MODE);
mKeywordArray = getResources().getStringArray(R.array.hot_search_items);
keywordListView =(ListView) findViewById(R.id.keyword_list);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.more_keyword_item, mKeywordArray);
keywordListView.setFastScrollEnabled(true);
keywordListView.setTextFilterEnabled(true);
keywordListView.setAdapter(arrayAdapter);
keywordListView.setOnItemClickListener(mOnClickListener);
}
private ImageButton.OnClickListener backListner = new ImageButton.OnClickListener() {
public void onClick(View v) {
finish();
}
};
private AdapterView.OnItemClickListener mOnClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
TextView text = (TextView)v;
String keyword = text.getText().toString();
Intent intent = new Intent();
intent.setClass(MoreKeywordActivity.this, SearchResultActivity.class);
Bundle bundle = new Bundle();
bundle.putString("keyword", keyword);
intent.putExtras(bundle);
suggestions.saveRecentQuery(keyword, null);
startActivity(intent);
}
};
} | Java |
package com.besttone.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
public class MarqueeTextView extends TextView {
public MarqueeTextView(Context context) {
super(context);
}
public MarqueeTextView(Context context, AttributeSet attrs){
super(context,attrs);
}
public MarqueeTextView(Context context, AttributeSet attrs, int defStyle){
super(context, attrs, defStyle);
}
public boolean isFocused(){
return true;// 返回true,任何时候都处于focused状态,就能跑马
}
} | Java |
package com.besttone.widget;
import com.besttone.search.R;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class EditSearchBar extends LinearLayout implements TextWatcher,
View.OnClickListener, TextView.OnEditorActionListener {
private static final int CMD_CHANGED = 1;
private static final long DEALY = 500L;
private MSCButton mBtnMsc;
private ImageButton mClear;
private Handler mDelayHandler = new Handler() {
public void handleMessage(Message paramMessage) {
if (paramMessage.what == 1) {
String str = (String) paramMessage.obj;
if (EditSearchBar.this.mListener != null)
EditSearchBar.this.mListener.onKeywordChanged(str);
}
}
};
private EditText mEdit;
private OnKeywordChangeListner mListener;
private OnStartSearchListner mStartListener;
public EditSearchBar(Context paramContext) {
super(paramContext);
}
public EditSearchBar(Context paramContext, AttributeSet paramAttributeSet) {
super(paramContext, paramAttributeSet);
}
private void publishKeywordChange(String paramString) {
this.mDelayHandler.removeMessages(1);
this.mDelayHandler.sendMessageDelayed(
this.mDelayHandler.obtainMessage(1, paramString), 500L);
}
public void afterTextChanged(Editable paramEditable) {
}
public void beforeTextChanged(CharSequence paramCharSequence,
int paramInt1, int paramInt2, int paramInt3) {
}
public String getKeyword() {
String str;
if (this.mEdit != null) {
str = this.mEdit.getText().toString().trim();
if (TextUtils.isEmpty(str))
this.mEdit.setText("");
}
while (true) {
str = "";
}
}
public void onClick(View paramView) {
if ((paramView == this.mClear) && (this.mEdit != null)) {
this.mEdit.setText("");
publishKeywordChange("");
}
}
public boolean onEditorAction(TextView paramTextView, int paramInt,
KeyEvent paramKeyEvent) {
String str = getKeyword();
if ((this.mStartListener != null) && (!TextUtils.isEmpty(str))) {
this.mStartListener.onStartSearch(str);
return true;
}
return false;
}
protected void onFinishInflate() {
super.onFinishInflate();
this.mEdit = ((EditText) findViewById(R.id.search_edit));
this.mEdit.addTextChangedListener(this);
this.mEdit.setOnEditorActionListener(this);
new InputFilter() {
private static final String FORBID_CHARS = " ~`!@#$%^&*()_-+={[}]|\\:;\"'<,>.?/";
private StringBuilder sb = new StringBuilder();
public CharSequence filter(CharSequence paramCharSequence,
int paramInt1, int paramInt2, Spanned paramSpanned,
int paramInt3, int paramInt4) {
String str;
if (paramInt1 == paramInt2)
str = null;
while (true) {
this.sb.setLength(0);
for (int i = paramInt1;; i++) {
if (i >= paramInt2) {
if (this.sb.length() <= 0)
break;
str = this.sb.toString();
break;
}
char c = paramCharSequence.charAt(i);
if (" ~`!@#$%^&*()_-+={[}]|\\:;\"'<,>.?/".indexOf(c) >= 0)
continue;
this.sb.append(c);
}
str = "";
}
}
};
this.mClear = ((ImageButton) findViewById(R.id.search_clear));
this.mClear.setOnClickListener(this);
}
public void onTextChanged(CharSequence paramCharSequence, int paramInt1,
int paramInt2, int paramInt3) {
if (TextUtils.isEmpty(paramCharSequence)) {
this.mClear.setVisibility(View.GONE);
publishKeywordChange(paramCharSequence.toString());
} else {
while (true) {
publishKeywordChange(paramCharSequence.toString());
this.mClear.setVisibility(View.VISIBLE);
return;
}
}
}
public void onVoiceKeyword(String paramString) {
if ((this.mStartListener != null) && (!TextUtils.isEmpty(paramString)))
this.mStartListener.onStartSearch(paramString);
}
public void setHint(int paramInt) {
if (this.mEdit != null)
this.mEdit.setHint(paramInt);
}
public void setKeyword(String paramString) {
if (paramString == null) {
while (true) {
if ((this.mEdit != null)
&& (paramString.compareTo(this.mEdit.getText()
.toString()) != 0)) {
this.mEdit.setText(paramString);
this.mEdit.setSelection(-1 + paramString.length());
continue;
}
return;
}
}
}
public void setOnKeywordChangeListner(
OnKeywordChangeListner paramOnKeywordChangeListner) {
this.mListener = paramOnKeywordChangeListner;
}
public void setOnStartSearchListner(
OnStartSearchListner paramOnStartSearchListner) {
this.mStartListener = paramOnStartSearchListner;
}
public static abstract interface OnKeywordChangeListner {
public abstract void onKeywordChanged(String paramString);
}
public static abstract interface OnStartSearchListner {
public abstract void onStartSearch(String paramString);
}
}
| Java |
package com.besttone.widget;
import com.besttone.search.R;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import android.widget.TextView;
public class PoiListItem extends LinearLayout
{
TextView name;
TextView tel;
TextView addr;
public PoiListItem(Context context) {
super(context);
}
public PoiListItem(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setPoiData(String name, String tel, String addr, String city) {
int m = 0;
if(city!=null && city.trim().length()!=0){
this.addr.setText("【" + city +"】" + addr);
} else {
this.addr.setText(addr);
}
this.tel.setText(tel);
this.name.setText(name);
this.name.setPadding(this.name.getPaddingLeft(), this.name.getPaddingTop(), m, this.name.getPaddingBottom());
}
protected void onFinishInflate() {
super.onFinishInflate();
this.name = ((TextView) findViewById(R.id.name));
this.tel = ((TextView) findViewById(R.id.tel));
this.addr = ((TextView) findViewById(R.id.addr));
}
} | Java |
package com.besttone.widget;
public class MSCButton {
}
| Java |
package com.besttone.widget;
import com.besttone.search.R;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
public class ButtonSearchBar extends LinearLayout implements
View.OnClickListener {
private Button btnSearch;
private ButtonSearchBarListener mListener;
public ButtonSearchBar(Context paramContext) {
super(paramContext);
}
public ButtonSearchBar(Context paramContext, AttributeSet paramAttributeSet) {
super(paramContext, paramAttributeSet);
}
public void onClick(View paramView) {
// if (this.mListener != null)
// this.mListener.onSearchRequested();
}
protected void onFinishInflate() {
super.onFinishInflate();
// this.btnSearch = ((Button) findViewById(R.id.start_search));
// this.btnSearch.setOnClickListener(this);
}
public void onVoiceKeyword(String paramString) {
if (this.mListener != null)
this.mListener.onSearchRequested(paramString);
}
public void setButtonSearchBarListener(
ButtonSearchBarListener paramButtonSearchBarListener) {
this.mListener = paramButtonSearchBarListener;
}
public void setGaTag(String paramString) {
}
public void setHint(int paramInt) {
if (this.btnSearch == null);
while (true) {
if (paramInt > 0) {
this.btnSearch.setHint(paramInt);
continue;
}
this.btnSearch.setHint(R.string.search_hint);
return;
}
}
public void setHint(String paramString) {
if (this.btnSearch != null)
this.btnSearch.setHint(paramString);
}
public void setKeyword(String paramString) {
if (this.btnSearch != null)
this.btnSearch.setText(paramString);
}
public static abstract interface ButtonSearchBarListener {
public abstract void onSearchRequested();
public abstract void onSearchRequested(String paramString);
}
} | Java |
package com.besttone.widget;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ListView;
import android.widget.SectionIndexer;
@SuppressLint("ResourceAsColor")
public class AlphabetBar extends View {
private String[] l;
private ListView list;
private int mCurIdx;
private OnSelectedListener mOnSelectedListener;
private int m_nItemHeight;
private SectionIndexer sectionIndexter;
public AlphabetBar(Context paramContext) {
super(paramContext);
String[] arrayOfString = new String[27];
arrayOfString[0] = "热门";
arrayOfString[1] = "A";
arrayOfString[2] = "B";
arrayOfString[3] = "C";
arrayOfString[4] = "D";
arrayOfString[5] = "E";
arrayOfString[6] = "F";
arrayOfString[7] = "G";
arrayOfString[8] = "H";
arrayOfString[9] = "I";
arrayOfString[10] = "J";
arrayOfString[11] = "K";
arrayOfString[12] = "L";
arrayOfString[13] = "M";
arrayOfString[14] = "N";
arrayOfString[15] = "O";
arrayOfString[16] = "P";
arrayOfString[17] = "Q";
arrayOfString[18] = "R";
arrayOfString[19] = "S";
arrayOfString[20] = "T";
arrayOfString[21] = "U";
arrayOfString[22] = "V";
arrayOfString[23] = "W";
arrayOfString[24] = "X";
arrayOfString[25] = "Y";
arrayOfString[26] = "Z";
this.l = arrayOfString;
this.sectionIndexter = null;
this.m_nItemHeight = 25;
setBackgroundColor(1157627903);
}
public AlphabetBar(Context paramContext, AttributeSet paramAttributeSet) {
super(paramContext, paramAttributeSet);
String[] arrayOfString = new String[27];
arrayOfString[0] = "热门";
arrayOfString[1] = "A";
arrayOfString[2] = "B";
arrayOfString[3] = "C";
arrayOfString[4] = "D";
arrayOfString[5] = "E";
arrayOfString[6] = "F";
arrayOfString[7] = "G";
arrayOfString[8] = "H";
arrayOfString[9] = "I";
arrayOfString[10] = "J";
arrayOfString[11] = "K";
arrayOfString[12] = "L";
arrayOfString[13] = "M";
arrayOfString[14] = "N";
arrayOfString[15] = "O";
arrayOfString[16] = "P";
arrayOfString[17] = "Q";
arrayOfString[18] = "R";
arrayOfString[19] = "S";
arrayOfString[20] = "T";
arrayOfString[21] = "U";
arrayOfString[22] = "V";
arrayOfString[23] = "W";
arrayOfString[24] = "X";
arrayOfString[25] = "Y";
arrayOfString[26] = "Z";
this.l = arrayOfString;
this.sectionIndexter = null;
this.m_nItemHeight = 25;
setBackgroundColor(1157627903);
}
public AlphabetBar(Context paramContext, AttributeSet paramAttributeSet,
int paramInt) {
super(paramContext, paramAttributeSet, paramInt);
String[] arrayOfString = new String[27];
arrayOfString[0] = "热门";
arrayOfString[1] = "A";
arrayOfString[2] = "B";
arrayOfString[3] = "C";
arrayOfString[4] = "D";
arrayOfString[5] = "E";
arrayOfString[6] = "F";
arrayOfString[7] = "G";
arrayOfString[8] = "H";
arrayOfString[9] = "I";
arrayOfString[10] = "J";
arrayOfString[11] = "K";
arrayOfString[12] = "L";
arrayOfString[13] = "M";
arrayOfString[14] = "N";
arrayOfString[15] = "O";
arrayOfString[16] = "P";
arrayOfString[17] = "Q";
arrayOfString[18] = "R";
arrayOfString[19] = "S";
arrayOfString[20] = "T";
arrayOfString[21] = "U";
arrayOfString[22] = "V";
arrayOfString[23] = "W";
arrayOfString[24] = "X";
arrayOfString[25] = "Y";
arrayOfString[26] = "Z";
this.l = arrayOfString;
this.sectionIndexter = null;
this.m_nItemHeight = 25;
setBackgroundColor(1157627903);
}
public int getCurIndex() {
return this.mCurIdx;
}
@SuppressLint("ResourceAsColor")
protected void onDraw(Canvas paramCanvas) {
Paint localPaint = new Paint();
localPaint.setColor(Color.LTGRAY);
float f = 0;
if (this.m_nItemHeight > 25) {
localPaint.setTextSize(20.0F);
localPaint.setTextAlign(Paint.Align.CENTER);
f = getMeasuredWidth() / 2;
}
for (int i = 0;; i++) {
if (i >= this.l.length) {
super.onDraw(paramCanvas);
if (-5 + this.m_nItemHeight < 5) {
localPaint.setTextSize(5.0F);
break;
}
localPaint.setTextSize(-5 + this.m_nItemHeight);
break;
}
paramCanvas.drawText(String.valueOf(this.l[i]), f,
this.m_nItemHeight + i * this.m_nItemHeight, localPaint);
return;
}
}
protected void onLayout(boolean paramBoolean, int paramInt1, int paramInt2,
int paramInt3, int paramInt4) {
super.onLayout(paramBoolean, paramInt1, paramInt2, paramInt3, paramInt4);
this.m_nItemHeight = ((-10 + (paramInt4 - paramInt2)) / this.l.length);
}
public boolean onTouchEvent(MotionEvent paramMotionEvent) {
super.onTouchEvent(paramMotionEvent);
int i = (int) paramMotionEvent.getY() / this.m_nItemHeight;
int j = 0;
if (i >= this.l.length) {
i = -1 + this.l.length;
this.mCurIdx = i;
if (this.sectionIndexter == null)
this.sectionIndexter = ((SectionIndexer) this.list.getAdapter());
j = this.sectionIndexter.getPositionForSection(i);
}
while (true) {
if (i >= 0)
break;
i = 0;
this.list.setSelection(j);
if (this.mOnSelectedListener != null)
this.mOnSelectedListener.onSelected(j);
setBackgroundColor(-3355444);
return true;
}
return false;
}
public void setListView(ListView paramListView) {
this.list = paramListView;
}
public void setOnSelectedListener(OnSelectedListener paramOnSelectedListener) {
this.mOnSelectedListener = paramOnSelectedListener;
}
public void setSectionIndexter(SectionIndexer paramSectionIndexer) {
this.sectionIndexter = paramSectionIndexer;
}
public static abstract interface OnSelectedListener {
public abstract void onSelected(int paramInt);
public abstract void onUnselected();
}
}
| Java |
package com.besttone.adapter;
import java.util.ArrayList;
import com.besttone.search.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
public class CateAdapter extends BaseAdapter
{
private String[] data;
Context mContext;
private LayoutInflater mInflater;
private int typeIndex = 0;
public CateAdapter(Context context, String[] mChannelArray)
{
mContext = context;
data = mChannelArray;
this.mInflater = LayoutInflater.from(context);
}
public String getSelect() {
return data[typeIndex];
}
public void setTypeIndex(int index) {
typeIndex = index;
}
public int getCount()
{
return data.length;
}
public Object getItem(int position)
{
return data[position];
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mInflater.inflate(R.layout.dialog_list_item, null);
String area = data[position];
((TextView) convertView.findViewById(R.id.id_area)).setText(area);
View view = new View(mContext);
LayoutParams param = new LayoutParams(30, 30);
view.setLayoutParams(param);
if (position == typeIndex) {
convertView.findViewById(R.id.ic_checked).setVisibility(
View.VISIBLE);
}
((LinearLayout) convertView).addView(view, 0);
return convertView;
}
private ArrayList<String> getData()
{
ArrayList<String> data = new ArrayList<String>();
data.add("全部频道");
data.add("美食");
data.add("休闲娱乐");
data.add("购物");
data.add("酒店");
data.add("丽人");
data.add("运动健身");
data.add("结婚");
data.add("生活服务");
return data;
}
} | Java |
package com.besttone.adapter;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.besttone.search.R;
import com.besttone.search.model.City;
import com.besttone.search.util.SharedUtils;
import com.besttone.search.util.StringUtils;
import java.util.ArrayList;
public class CityListAdapter extends LetterListAdapter {
public CityListAdapter() {
}
public CityListAdapter(Context paramContext, ArrayList<City> paramArrayList) {
super(paramContext, paramArrayList);
}
public View setTheView(int paramInt, View paramView,
ViewGroup paramViewGroup) {
City localCity = (City) this.mCitylist.get(paramInt);
if ("-1".equals(localCity.getCityName())) {
TextView localTextView = new TextView(this.mContext);
localTextView.setTextAppearance(this.mContext, R.style.text_18_black);
localTextView.setPadding(15, 0, 0, 0);
localTextView.setBackgroundResource(R.color.title_grey);
localTextView.setGravity(16);
localTextView.setText(localCity.getFirstLetter());
return localTextView;
}
View localView = LayoutInflater.from(this.mContext).inflate(R.layout.select_city_list_item,
null);
String str1 = localCity.getCityName();
((TextView) localView.findViewById(R.id.city_info)).setText(str1);
ImageView localImageView = (ImageView) localView.findViewById(R.id.selected_item);
String str2 = SharedUtils.getCurrentCityName(this.mContext);
if ((!StringUtils.isEmpty(str2)) && (str2.equals(str1))) {
localImageView.setVisibility(View.VISIBLE);
} else {
while (true) {
localImageView.setVisibility(View.INVISIBLE);
break;
}
}
return localView;
}
}
| Java |
package com.besttone.adapter;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.besttone.search.model.City;
import java.util.ArrayList;
public abstract class LetterListAdapter extends BaseAdapter {
ArrayList<City> mCitylist;
Context mContext;
public LetterListAdapter() {
}
public LetterListAdapter(Context paramContext,
ArrayList<City> paramArrayList) {
this.mCitylist = paramArrayList;
this.mContext = paramContext;
}
public int getCount() {
return this.mCitylist.size();
}
public Object getItem(int paramInt) {
return this.mCitylist.get(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
return setTheView(paramInt, paramView, paramViewGroup);
}
public abstract View setTheView(int paramInt, View paramView,
ViewGroup paramViewGroup);
} | Java |
package com.besttone.adapter;
import java.util.ArrayList;
import com.besttone.search.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
public class SortAdapter extends BaseAdapter
{
private String[] data;
Context mContext;
private LayoutInflater mInflater;
private int disableIndex = -1;
private int typeIndex = 0;
public SortAdapter(Context context, String[] mSortArray)
{
mContext = context;
data = mSortArray;
this.mInflater = LayoutInflater.from(context);
}
public String[] getDataArray() {
return data;
}
public String getSelect() {
return data[typeIndex];
}
public void setTypeIndex(int index) {
typeIndex = index;
}
public int getCount()
{
return data.length;
}
public Object getItem(int position)
{
return data[position];
}
public long getItemId(int position)
{
return position;
}
public boolean isEnabled(int position)
{
return true;
}
public View getView(int position, View convertView, ViewGroup parent)
{
convertView = mInflater.inflate(R.layout.dialog_list_item, null);
String area = data[position];
((TextView) convertView.findViewById(R.id.id_area)).setText(area);
View view = new View(mContext);
LayoutParams param = new LayoutParams(30, 30);
view.setLayoutParams(param);
if (position == typeIndex) {
convertView.findViewById(R.id.ic_checked).setVisibility(
View.VISIBLE);
}
((LinearLayout) convertView).addView(view, 0);
return convertView;
}
private ArrayList<String> getData()
{
ArrayList<String> data = new ArrayList<String>();
data.add("按默认排序");
data.add("按距离排序");
data.add("按人气排序");
data.add("按星级排序");
data.add("按点评数排序");
data.add("优惠劵商户优先");
data.add("titlebar");
data.add("20元以下");
data.add("21-50");
data.add("51-80");
data.add("81-120");
data.add("121-200");
data.add("201以上");
return data;
}
} | Java |
package com.besttone.adapter;
import java.util.ArrayList;
import java.util.Map;
import com.besttone.search.R;
import com.besttone.search.util.Constants;
import com.besttone.search.util.SharedUtils;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
public class AreaAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private String[] mData;
private int typeIndex = 0;
private Context context;
public AreaAdapter(Context context, String[] mAreaArray) {
this.context = context;
this.mInflater = LayoutInflater.from(context);
mData = mAreaArray;
}
public String[] getDataArray() {
return mData;
}
public String getSelect() {
return mData[typeIndex];
}
public void setTypeIndex(int index) {
typeIndex = index;
}
public int getCount() {
return mData.length;
}
public Object getItem(int position) {
return mData[position];
}
public long getItemId(int arg0) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mInflater.inflate(R.layout.dialog_list_item, null);
View view = new View(context);
LayoutParams param = new LayoutParams(30, 30);
view.setLayoutParams(param);
String area = mData[position];
((TextView)convertView.findViewById(R.id.id_area)).setText(area);
if(position == typeIndex)
{
convertView.findViewById(R.id.ic_checked).setVisibility(View.VISIBLE);
}
((LinearLayout)convertView).addView(view, 0);
return convertView;
}
// private ArrayList<ArrayList<String>> getData()
// {
// ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
//
// ArrayList<String> quanbu = new ArrayList<String>();
// quanbu.add("全部地区");
// quanbu.add("全部地区 ");
// data.add(quanbu);
//
// ArrayList<String> hongkou = new ArrayList<String>();
// hongkou.add("全部地区");
// hongkou.add("虹口区");
// hongkou.add("海宁路/七浦路");
// hongkou.add("临平路/和平公园");
// hongkou.add("曲阳地区");
// hongkou.add("四川北路");
// hongkou.add("鲁迅公园");
// data.add(hongkou);
//
// ArrayList<String> zhabei = new ArrayList<String>();
// zhabei.add("全部地区");
// zhabei.add("闸北区");
// zhabei.add("大宁大区");
// zhabei.add("北区汽车站");
// zhabei.add("火车站");
// zhabei.add("闸北公园");
// data.add(zhabei);
//
// ArrayList<String> xuhui = new ArrayList<String>();
// xuhui.add("全部地区");
// xuhui.add("徐汇区");
// xuhui.add("衡山路");
// xuhui.add("音乐学院");
// xuhui.add("肇家浜路沿线");
// xuhui.add("漕河泾/田林");
// data.add(xuhui);
//
// ArrayList<String> changning = new ArrayList<String>();
// changning.add("全部地区");
// changning.add("长宁区");
// changning.add("天山");
// changning.add("上海影城/新华路");
// changning.add("中山公园");
// changning.add("古北");
// data.add(changning);
//
// ArrayList<String> yangpu = new ArrayList<String>();
// yangpu.add("全部地区");
// yangpu.add("杨浦区");
// yangpu.add("五角场");
// yangpu.add("控江地区");
// yangpu.add("平凉路");
// yangpu.add("黄兴公园");
// data.add(yangpu);
//
// ArrayList<String> qingpu = new ArrayList<String>();
// qingpu.add("全部地区");
// qingpu.add("青浦区");
// qingpu.add("朱家角");
// data.add(qingpu);
//
// ArrayList<String> songjiang = new ArrayList<String>();
// songjiang.add("全部地区");
// songjiang.add("松江区");
// songjiang.add("松江镇");
// songjiang.add("九亭");
// songjiang.add("佘山");
// songjiang.add("松江大学城");
// data.add(songjiang);
//
// ArrayList<String> baoshan = new ArrayList<String>();
// baoshan.add("全部地区");
// baoshan.add("宝山区");
// baoshan.add("大华大区");
// baoshan.add("庙行镇");
// baoshan.add("吴淞");
// baoshan.add("上海大学");
// data.add(baoshan);
//
// ArrayList<String> pudong = new ArrayList<String>();
// pudong.add("全部地区");
// pudong.add("康桥/周浦");
// pudong.add("陆家嘴");
// pudong.add("世纪公园");
// pudong.add("八佰伴");
// data.add(pudong);
//
// return data;
// }
}
| Java |
package com.amap.cn.apis.util;
public class ConstantsAmap {
public static final int POISEARCH=1000;
public static final int ERROR=1001;
public static final int FIRST_LOCATION=1002;
public static final int ROUTE_START_SEARCH=2000;//路径规划起点搜索
public static final int ROUTE_END_SEARCH=2001;//路径规划起点搜索
public static final int ROUTE_SEARCH_RESULT=2002;//路径规划结果
public static final int ROUTE_SEARCH_ERROR=2004;//路径规划起起始点搜索异常
public static final int REOCODER_RESULT=3000;//地理编码结果
public static final int DIALOG_LAYER=4000;
public static final int POISEARCH_NEXT=5000;
public static final int BUSLINE_RESULT=6000;
public static final int BUSLINE_DETAIL_RESULT=6001;
public static final int BUSLINE_ERROR_RESULT=6002;
}
| Java |
/*
* Copyright (C) 2008 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.google.android.photostream;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpVersion;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.params.HttpParams;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.net.URL;
import android.util.Xml;
import android.view.InflateException;
import android.net.Uri;
import android.os.Parcelable;
import android.os.Parcel;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
/**
* Utility class to interact with the Flickr REST-based web services.
*
* This class uses a default Flickr API key that you should replace with your own if
* you reuse this code to redistribute it with your application(s).
*
* This class is used as a singleton and cannot be instanciated. Instead, you must use
* {@link #get()} to retrieve the unique instance of this class.
*/
class Flickr {
static final String LOG_TAG = "Photostream";
// IMPORTANT: Replace this Flickr API key with your own
private static final String API_KEY = "730e3a4f253b30adf30177df803d38c4";
private static final String API_REST_HOST = "api.flickr.com";
private static final String API_REST_URL = "/services/rest/";
private static final String API_FEED_URL = "/services/feeds/photos_public.gne";
private static final String API_PEOPLE_FIND_BY_USERNAME = "flickr.people.findByUsername";
private static final String API_PEOPLE_GET_INFO = "flickr.people.getInfo";
private static final String API_PEOPLE_GET_PUBLIC_PHOTOS = "flickr.people.getPublicPhotos";
private static final String API_PEOPLE_GET_LOCATION = "flickr.photos.geo.getLocation";
private static final String PARAM_API_KEY = "api_key";
private static final String PARAM_METHOD= "method";
private static final String PARAM_USERNAME = "username";
private static final String PARAM_USERID = "user_id";
private static final String PARAM_PER_PAGE = "per_page";
private static final String PARAM_PAGE = "page";
private static final String PARAM_EXTRAS = "extras";
private static final String PARAM_PHOTO_ID = "photo_id";
private static final String PARAM_FEED_ID = "id";
private static final String PARAM_FEED_FORMAT = "format";
private static final String VALUE_DEFAULT_EXTRAS = "date_taken";
private static final String VALUE_DEFAULT_FORMAT = "atom";
private static final String RESPONSE_TAG_RSP = "rsp";
private static final String RESPONSE_ATTR_STAT = "stat";
private static final String RESPONSE_STATUS_OK = "ok";
private static final String RESPONSE_TAG_USER = "user";
private static final String RESPONSE_ATTR_NSID = "nsid";
private static final String RESPONSE_TAG_PHOTOS = "photos";
private static final String RESPONSE_ATTR_PAGE = "page";
private static final String RESPONSE_ATTR_PAGES = "pages";
private static final String RESPONSE_TAG_PHOTO = "photo";
private static final String RESPONSE_ATTR_ID = "id";
private static final String RESPONSE_ATTR_SECRET = "secret";
private static final String RESPONSE_ATTR_SERVER = "server";
private static final String RESPONSE_ATTR_FARM = "farm";
private static final String RESPONSE_ATTR_TITLE = "title";
private static final String RESPONSE_ATTR_DATE_TAKEN = "datetaken";
private static final String RESPONSE_TAG_PERSON = "person";
private static final String RESPONSE_ATTR_ISPRO = "ispro";
private static final String RESPONSE_ATTR_ICONSERVER = "iconserver";
private static final String RESPONSE_ATTR_ICONFARM = "iconfarm";
private static final String RESPONSE_TAG_USERNAME = "username";
private static final String RESPONSE_TAG_REALNAME = "realname";
private static final String RESPONSE_TAG_LOCATION = "location";
private static final String RESPONSE_ATTR_LATITUDE = "latitude";
private static final String RESPONSE_ATTR_LONGITUDE = "longitude";
private static final String RESPONSE_TAG_PHOTOSURL = "photosurl";
private static final String RESPONSE_TAG_PROFILEURL = "profileurl";
private static final String RESPONSE_TAG_MOBILEURL = "mobileurl";
private static final String RESPONSE_TAG_FEED = "feed";
private static final String RESPONSE_TAG_UPDATED = "updated";
private static final String PHOTO_IMAGE_URL = "http://farm%s.static.flickr.com/%s/%s_%s%s.jpg";
private static final String BUDDY_ICON_URL =
"http://farm%s.static.flickr.com/%s/buddyicons/%s.jpg";
private static final String DEFAULT_BUDDY_ICON_URL =
"http://www.flickr.com/images/buddyicon.jpg";
private static final int IO_BUFFER_SIZE = 4 * 1024;
private static final boolean FLAG_DECODE_PHOTO_STREAM_WITH_SKIA = false;
private static final Flickr sInstance = new Flickr();
private HttpClient mClient;
/**
* Defines the size of the image to download from Flickr.
*
* @see com.google.android.photostream.Flickr.Photo
*/
enum PhotoSize {
/**
* Small square image (75x75 px).
*/
SMALL_SQUARE("_s", 75),
/**
* Thumbnail image (the longest side measures 100 px).
*/
THUMBNAIL("_t", 100),
/**
* Small image (the longest side measures 240 px).
*/
SMALL("_m", 240),
/**
* Medium image (the longest side measures 500 px).
*/
MEDIUM("", 500),
/**
* Large image (the longest side measures 1024 px).
*/
LARGE("_b", 1024);
private final String mSize;
private final int mLongSide;
private PhotoSize(String size, int longSide) {
mSize = size;
mLongSide = longSide;
}
/**
* Returns the size in pixels of the longest side of the image.
*
* @return THe dimension in pixels of the longest side.
*/
int longSide() {
return mLongSide;
}
/**
* Returns the name of the size, as defined by Flickr. For instance,
* the LARGE size is defined by the String "_b".
*
* @return
*/
String size() {
return mSize;
}
@Override
public String toString() {
return name() + ", longSide=" + mLongSide;
}
}
/**
* Represents the geographical location of a photo.
*/
static class Location {
private float mLatitude;
private float mLongitude;
private Location(float latitude, float longitude) {
mLatitude = latitude;
mLongitude = longitude;
}
float getLatitude() {
return mLatitude;
}
float getLongitude() {
return mLongitude;
}
}
/**
* A Flickr user, in the strictest sense, is only defined by its NSID. The NSID
* is usually obtained by {@link Flickr#findByUserName(String)
* looking up a user by its user name}.
*
* To obtain more information about a given user, refer to the UserInfo class.
*
* @see Flickr#findByUserName(String)
* @see Flickr#getUserInfo(com.google.android.photostream.Flickr.User)
* @see com.google.android.photostream.Flickr.UserInfo
*/
static class User implements Parcelable {
private final String mId;
private User(String id) {
mId = id;
}
private User(Parcel in) {
mId = in.readString();
}
/**
* Returns the Flickr NSDID of the user. The NSID is used to identify the
* user with any operation performed on Flickr.
*
* @return The user's NSID.
*/
String getId() {
return mId;
}
/**
* Creates a new instance of this class from the specified Flickr NSID.
*
* @param id The NSID of the Flickr user.
*
* @return An instance of User whose id might not be valid.
*/
static User fromId(String id) {
return new User(id);
}
@Override
public String toString() {
return "User[" + mId + "]";
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mId);
}
public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() {
public User createFromParcel(Parcel in) {
return new User(in);
}
public User[] newArray(int size) {
return new User[size];
}
};
}
/**
* A set of information for a given Flickr user. The information exposed include:
* - The user's NSDID
* - The user's name
* - The user's real name
* - The user's location
* - The URL to the user's photos
* - The URL to the user's profile
* - The URL to the user's mobile web site
* - Whether the user has a pro account
*/
static class UserInfo implements Parcelable {
private String mId;
private String mUserName;
private String mRealName;
private String mLocation;
private String mPhotosUrl;
private String mProfileUrl;
private String mMobileUrl;
private boolean mIsPro;
private String mIconServer;
private String mIconFarm;
private UserInfo(String nsid) {
mId = nsid;
}
private UserInfo(Parcel in) {
mId = in.readString();
mUserName = in.readString();
mRealName = in.readString();
mLocation = in.readString();
mPhotosUrl = in.readString();
mProfileUrl = in.readString();
mMobileUrl = in.readString();
mIsPro = in.readInt() == 1;
mIconServer = in.readString();
mIconFarm = in.readString();
}
/**
* Returns the Flickr NSID that identifies this user.
*
* @return The Flickr NSID.
*/
String getId() {
return mId;
}
/**
* Returns the user's name. This is the name that the user authenticates with,
* and the name that Flickr uses in the URLs
* (for instance, http://flickr.com/photos/romainguy, where romainguy is the user
* name.)
*
* @return The user's Flickr name.
*/
String getUserName() {
return mUserName;
}
/**
* Returns the user's real name. The real name is chosen by the user when
* creating his account and might not reflect his civil name.
*
* @return The real name of the user.
*/
String getRealName() {
return mRealName;
}
/**
* Returns the user's location, if publicly exposed.
*
* @return The location of the user.
*/
String getLocation() {
return mLocation;
}
/**
* Returns the URL to the photos of the user. For instance,
* http://flickr.com/photos/romainguy.
*
* @return The URL to the photos of the user.
*/
String getPhotosUrl() {
return mPhotosUrl;
}
/**
* Returns the URL to the profile of the user. For instance,
* http://flickr.com/people/romainguy/.
*
* @return The URL to the photos of the user.
*/
String getProfileUrl() {
return mProfileUrl;
}
/**
* Returns the mobile URL of the user.
*
* @return The mobile URL of the user.
*/
String getMobileUrl() {
return mMobileUrl;
}
/**
* Indicates whether the user owns a pro account.
*
* @return true, if the user has a pro account, false otherwise.
*/
boolean isPro() {
return mIsPro;
}
/**
* Returns the URL to the user's buddy icon. The buddy icon is a 48x48
* image chosen by the user. If no icon can be found, a default image
* URL is returned.
*
* @return The URL to the user's buddy icon.
*/
String getBuddyIconUrl() {
if (mIconFarm == null || mIconServer == null || mId == null) {
return DEFAULT_BUDDY_ICON_URL;
}
return String.format(BUDDY_ICON_URL, mIconFarm, mIconServer, mId);
}
/**
* Loads the user's buddy icon as a Bitmap. The user's buddy icon is loaded
* from the URL returned by {@link #getBuddyIconUrl()}. The buddy icon is
* not cached locally.
*
* @return A 48x48 bitmap if the icon was loaded successfully or null otherwise.
*/
Bitmap loadBuddyIcon() {
Bitmap bitmap = null;
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new URL(getBuddyIconUrl()).openStream(),
IO_BUFFER_SIZE);
if (FLAG_DECODE_PHOTO_STREAM_WITH_SKIA) {
bitmap = BitmapFactory.decodeStream(in);
} else {
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
}
} catch (IOException e) {
android.util.Log.e(Flickr.LOG_TAG, "Could not load buddy icon: " + this, e);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
@Override
public String toString() {
return mRealName + " (" + mUserName + ", " + mId + ")";
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mId);
dest.writeString(mUserName);
dest.writeString(mRealName);
dest.writeString(mLocation);
dest.writeString(mPhotosUrl);
dest.writeString(mProfileUrl);
dest.writeString(mMobileUrl);
dest.writeInt(mIsPro ? 1 : 0);
dest.writeString(mIconServer);
dest.writeString(mIconFarm);
}
public static final Parcelable.Creator<UserInfo> CREATOR =
new Parcelable.Creator<UserInfo>() {
public UserInfo createFromParcel(Parcel in) {
return new UserInfo(in);
}
public UserInfo[] newArray(int size) {
return new UserInfo[size];
}
};
}
/**
* A photo is represented by a title, the date at which it was taken and a URL.
* The URL depends on the desired {@link com.google.android.photostream.Flickr.PhotoSize}.
*/
static class Photo implements Parcelable {
private String mId;
private String mSecret;
private String mServer;
private String mFarm;
private String mTitle;
private String mDate;
private Photo() {
}
private Photo(Parcel in) {
mId = in.readString();
mSecret = in.readString();
mServer = in.readString();
mFarm = in.readString();
mTitle = in.readString();
mDate = in.readString();
}
/**
* Returns the title of the photo, if specified.
*
* @return The title of the photo. The returned value can be empty or null.
*/
String getTitle() {
return mTitle;
}
/**
* Returns the date at which the photo was taken, formatted in the current locale
* with the following pattern: MMMM d, yyyy.
*
* @return The title of the photo. The returned value can be empty or null.
*/
String getDate() {
return mDate;
}
/**
* Returns the URL to the photo for the specified size.
*
* @param photoSize The required size of the photo.
*
* @return A URL to the photo for the specified size.
*
* @see com.google.android.photostream.Flickr.PhotoSize
*/
String getUrl(PhotoSize photoSize) {
return String.format(PHOTO_IMAGE_URL, mFarm, mServer, mId, mSecret, photoSize.size());
}
/**
* Loads a Bitmap representing the photo for the specified size. The Bitmap is loaded
* from the URL returned by
* {@link #getUrl(com.google.android.photostream.Flickr.PhotoSize)}.
*
* @param size The size of the photo to load.
*
* @return A Bitmap whose longest size is the same as the longest side of the
* specified {@link com.google.android.photostream.Flickr.PhotoSize}, or null
* if the photo could not be loaded.
*/
Bitmap loadPhotoBitmap(PhotoSize size) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(getUrl(size)).openStream(),
IO_BUFFER_SIZE);
if (FLAG_DECODE_PHOTO_STREAM_WITH_SKIA) {
bitmap = BitmapFactory.decodeStream(in);
} else {
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
}
} catch (IOException e) {
android.util.Log.e(Flickr.LOG_TAG, "Could not load photo: " + this, e);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
@Override
public String toString() {
return mTitle + ", " + mDate + " @" + mId;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mId);
dest.writeString(mSecret);
dest.writeString(mServer);
dest.writeString(mFarm);
dest.writeString(mTitle);
dest.writeString(mDate);
}
public static final Parcelable.Creator<Photo> CREATOR = new Parcelable.Creator<Photo>() {
public Photo createFromParcel(Parcel in) {
return new Photo(in);
}
public Photo[] newArray(int size) {
return new Photo[size];
}
};
}
/**
* A list of {@link com.google.android.photostream.Flickr.Photo photos}. A list
* represents a series of photo on a page from the user's photostream, a list is
* therefore associated with a page index and a page count. The page index and the
* page count both depend on the number of photos per page.
*/
static class PhotoList {
private ArrayList<Photo> mPhotos;
private int mPage;
private int mPageCount;
private void add(Photo photo) {
mPhotos.add(photo);
}
/**
* Returns the photo at the specified index in the current set. An
* {@link ArrayIndexOutOfBoundsException} can be thrown if the index is
* less than 0 or greater then or equals to {@link #getCount()}.
*
* @param index The index of the photo to retrieve from the list.
*
* @return A valid {@link com.google.android.photostream.Flickr.Photo}.
*/
public Photo get(int index) {
return mPhotos.get(index);
}
/**
* Returns the number of photos in the list.
*
* @return A positive integer, or 0 if the list is empty.
*/
public int getCount() {
return mPhotos.size();
}
/**
* Returns the page index of the photos from this list.
*
* @return The index of the Flickr page that contains the photos of this list.
*/
public int getPage() {
return mPage;
}
/**
* Returns the total number of photo pages.
*
* @return A positive integer, or 0 if the photostream is empty.
*/
public int getPageCount() {
return mPageCount;
}
}
/**
* Returns the unique instance of this class.
*
* @return The unique instance of this class.
*/
static Flickr get() {
return sInstance;
}
private Flickr() {
final HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
final SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
final ThreadSafeClientConnManager manager =
new ThreadSafeClientConnManager(params, registry);
mClient = new DefaultHttpClient(manager, params);
}
/**
* Finds a user by its user name. This method will return an instance of
* {@link com.google.android.photostream.Flickr.User} containing the user's
* NSID, or null if the user could not be found.
*
* The returned User contains only the user's NSID. To retrieve more information
* about the user, please refer to
* {@link #getUserInfo(com.google.android.photostream.Flickr.User)}
*
* @param userName The name of the user to find.
*
* @return A User instance with a valid NSID, or null if the user cannot be found.
*
* @see #getUserInfo(com.google.android.photostream.Flickr.User)
* @see com.google.android.photostream.Flickr.User
* @see com.google.android.photostream.Flickr.UserInfo
*/
User findByUserName(String userName) {
final Uri.Builder uri = buildGetMethod(API_PEOPLE_FIND_BY_USERNAME);
uri.appendQueryParameter(PARAM_USERNAME, userName);
final HttpGet get = new HttpGet(uri.build().toString());
final String[] userId = new String[1];
try {
executeRequest(get, new ResponseHandler() {
public void handleResponse(InputStream in) throws IOException {
parseResponse(in, new ResponseParser() {
public void parseResponse(XmlPullParser parser)
throws XmlPullParserException, IOException {
parseUser(parser, userId);
}
});
}
});
if (userId[0] != null) {
return new User(userId[0]);
}
} catch (IOException e) {
android.util.Log.e(LOG_TAG, "Could not find the user with name: " + userName);
}
return null;
}
/**
* Retrieves a public set of information about the specified user. The user can
* either be {@link com.google.android.photostream.Flickr.User#fromId(String) created manually}
* or {@link #findByUserName(String) obtained from a user name}.
*
* @param user The user, whose NSID is valid, to retrive public information for.
*
* @return An instance of {@link com.google.android.photostream.Flickr.UserInfo} or null
* if the user could not be found.
*
* @see com.google.android.photostream.Flickr.UserInfo
* @see com.google.android.photostream.Flickr.User
* @see #findByUserName(String)
*/
UserInfo getUserInfo(User user) {
final String nsid = user.getId();
final Uri.Builder uri = buildGetMethod(API_PEOPLE_GET_INFO);
uri.appendQueryParameter(PARAM_USERID, nsid);
final HttpGet get = new HttpGet(uri.build().toString());
try {
final UserInfo info = new UserInfo(nsid);
executeRequest(get, new ResponseHandler() {
public void handleResponse(InputStream in) throws IOException {
parseResponse(in, new ResponseParser() {
public void parseResponse(XmlPullParser parser)
throws XmlPullParserException, IOException {
parseUserInfo(parser, info);
}
});
}
});
return info;
} catch (IOException e) {
android.util.Log.e(LOG_TAG, "Could not find the user with id: " + nsid);
}
return null;
}
/**
* Retrives a list of photos for the specified user. The list contains at most the
* number of photos specified by <code>perPage</code>. The photos are retrieved
* starting a the specified page index. For instance, if a user has 10 photos in
* his photostream, calling getPublicPhotos(user, 5, 2) will return the last 5 photos
* of the photo stream.
*
* The page index starts at 1, not 0.
*
* @param user The user to retrieve photos from.
* @param perPage The maximum number of photos to retrieve.
* @param page The index (starting at 1) of the page in the photostream.
*
* @return A list of at most perPage photos.
*
* @see com.google.android.photostream.Flickr.Photo
* @see com.google.android.photostream.Flickr.PhotoList
* @see #downloadPhoto(com.google.android.photostream.Flickr.Photo,
* com.google.android.photostream.Flickr.PhotoSize, java.io.OutputStream)
*/
PhotoList getPublicPhotos(User user, int perPage, int page) {
final Uri.Builder uri = buildGetMethod(API_PEOPLE_GET_PUBLIC_PHOTOS);
uri.appendQueryParameter(PARAM_USERID, user.getId());
uri.appendQueryParameter(PARAM_PER_PAGE, String.valueOf(perPage));
uri.appendQueryParameter(PARAM_PAGE, String.valueOf(page));
uri.appendQueryParameter(PARAM_EXTRAS, VALUE_DEFAULT_EXTRAS);
final HttpGet get = new HttpGet(uri.build().toString());
final PhotoList photos = new PhotoList();
try {
executeRequest(get, new ResponseHandler() {
public void handleResponse(InputStream in) throws IOException {
parseResponse(in, new ResponseParser() {
public void parseResponse(XmlPullParser parser)
throws XmlPullParserException, IOException {
parsePhotos(parser, photos);
}
});
}
});
} catch (IOException e) {
android.util.Log.e(LOG_TAG, "Could not find photos for user: " + user);
}
return photos;
}
/**
* Retrieves the geographical location of the specified photo. If the photo
* has no geodata associated with it, this method returns null.
*
* @param photo The photo to get the location of.
*
* @return The geo location of the photo, or null if the photo has no geodata
* or the photo cannot be found.
*
* @see com.google.android.photostream.Flickr.Location
*/
Location getLocation(Flickr.Photo photo) {
final Uri.Builder uri = buildGetMethod(API_PEOPLE_GET_LOCATION);
uri.appendQueryParameter(PARAM_PHOTO_ID, photo.mId);
final HttpGet get = new HttpGet(uri.build().toString());
final Location location = new Location(0.0f, 0.0f);
try {
executeRequest(get, new ResponseHandler() {
public void handleResponse(InputStream in) throws IOException {
parseResponse(in, new ResponseParser() {
public void parseResponse(XmlPullParser parser)
throws XmlPullParserException, IOException {
parsePhotoLocation(parser, location);
}
});
}
});
return location;
} catch (IOException e) {
android.util.Log.e(LOG_TAG, "Could not find location for photo: " + photo);
}
return null;
}
/**
* Checks the specified user's feed to see if any updated occured after the
* specified date.
*
* @param user The user whose feed must be checked.
* @param reference The date after which to check for updates.
*
* @return True if any update occured after the reference date, false otherwise.
*/
boolean hasUpdates(User user, final Calendar reference) {
final Uri.Builder uri = new Uri.Builder();
uri.path(API_FEED_URL);
uri.appendQueryParameter(PARAM_FEED_ID, user.getId());
uri.appendQueryParameter(PARAM_FEED_FORMAT, VALUE_DEFAULT_FORMAT);
final HttpGet get = new HttpGet(uri.build().toString());
final boolean[] updated = new boolean[1];
try {
executeRequest(get, new ResponseHandler() {
public void handleResponse(InputStream in) throws IOException {
parseFeedResponse(in, new ResponseParser() {
public void parseResponse(XmlPullParser parser)
throws XmlPullParserException, IOException {
updated[0] = parseUpdated(parser, reference);
}
});
}
});
} catch (IOException e) {
android.util.Log.e(LOG_TAG, "Could not find feed for user: " + user);
}
return updated[0];
}
/**
* Downloads the specified photo at the specified size in the specified destination.
*
* @param photo The photo to download.
* @param size The size of the photo to download.
* @param destination The output stream in which to write the downloaded photo.
*
* @throws IOException If any network exception occurs during the download.
*/
void downloadPhoto(Photo photo, PhotoSize size, OutputStream destination) throws IOException {
final BufferedOutputStream out = new BufferedOutputStream(destination, IO_BUFFER_SIZE);
final String url = photo.getUrl(size);
final HttpGet get = new HttpGet(url);
HttpEntity entity = null;
try {
final HttpResponse response = mClient.execute(get);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
entity = response.getEntity();
entity.writeTo(out);
out.flush();
}
} finally {
if (entity != null) {
entity.consumeContent();
}
}
}
private boolean parseUpdated(XmlPullParser parser, Calendar reference) throws IOException,
XmlPullParserException {
int type;
String name;
final int depth = parser.getDepth();
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
name = parser.getName();
if (RESPONSE_TAG_UPDATED.equals(name)) {
if (parser.next() == XmlPullParser.TEXT) {
final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
final String text = parser.getText().replace('T', ' ').replace('Z', ' ');
final Calendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(format.parse(text).getTime());
return calendar.after(reference);
} catch (ParseException e) {
// Ignore
}
}
}
}
return false;
}
private void parsePhotos(XmlPullParser parser, PhotoList photos)
throws XmlPullParserException, IOException {
int type;
String name;
SimpleDateFormat parseFormat = null;
SimpleDateFormat outputFormat = null;
final int depth = parser.getDepth();
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
name = parser.getName();
if (RESPONSE_TAG_PHOTOS.equals(name)) {
photos.mPage = Integer.parseInt(parser.getAttributeValue(null, RESPONSE_ATTR_PAGE));
photos.mPageCount = Integer.parseInt(parser.getAttributeValue(null,
RESPONSE_ATTR_PAGES));
photos.mPhotos = new ArrayList<Photo>();
} else if (RESPONSE_TAG_PHOTO.equals(name)) {
final Photo photo = new Photo();
photo.mId = parser.getAttributeValue(null, RESPONSE_ATTR_ID);
photo.mSecret = parser.getAttributeValue(null, RESPONSE_ATTR_SECRET);
photo.mServer = parser.getAttributeValue(null, RESPONSE_ATTR_SERVER);
photo.mFarm = parser.getAttributeValue(null, RESPONSE_ATTR_FARM);
photo.mTitle = parser.getAttributeValue(null, RESPONSE_ATTR_TITLE);
photo.mDate = parser.getAttributeValue(null, RESPONSE_ATTR_DATE_TAKEN);
if (parseFormat == null) {
parseFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
outputFormat = new SimpleDateFormat("MMMM d, yyyy");
}
try {
photo.mDate = outputFormat.format(parseFormat.parse(photo.mDate));
} catch (ParseException e) {
android.util.Log.w(LOG_TAG, "Could not parse photo date", e);
}
photos.add(photo);
}
}
}
private void parsePhotoLocation(XmlPullParser parser, Location location)
throws XmlPullParserException, IOException {
int type;
String name;
final int depth = parser.getDepth();
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
name = parser.getName();
if (RESPONSE_TAG_LOCATION.equals(name)) {
try {
location.mLatitude = Float.parseFloat(parser.getAttributeValue(null,
RESPONSE_ATTR_LATITUDE));
location.mLongitude = Float.parseFloat(parser.getAttributeValue(null,
RESPONSE_ATTR_LONGITUDE));
} catch (NumberFormatException e) {
throw new XmlPullParserException("Could not parse lat/lon", parser, e);
}
}
}
}
private void parseUser(XmlPullParser parser, String[] userId)
throws XmlPullParserException, IOException {
int type;
String name;
final int depth = parser.getDepth();
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
name = parser.getName();
if (RESPONSE_TAG_USER.equals(name)) {
userId[0] = parser.getAttributeValue(null, RESPONSE_ATTR_NSID);
}
}
}
private void parseUserInfo(XmlPullParser parser, UserInfo info)
throws XmlPullParserException, IOException {
int type;
String name;
final int depth = parser.getDepth();
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
name = parser.getName();
if (RESPONSE_TAG_PERSON.equals(name)) {
info.mIsPro = "1".equals(parser.getAttributeValue(null, RESPONSE_ATTR_ISPRO));
info.mIconServer = parser.getAttributeValue(null, RESPONSE_ATTR_ICONSERVER);
info.mIconFarm = parser.getAttributeValue(null, RESPONSE_ATTR_ICONFARM);
} else if (RESPONSE_TAG_USERNAME.equals(name)) {
if (parser.next() == XmlPullParser.TEXT) {
info.mUserName = parser.getText();
}
} else if (RESPONSE_TAG_REALNAME.equals(name)) {
if (parser.next() == XmlPullParser.TEXT) {
info.mRealName = parser.getText();
}
} else if (RESPONSE_TAG_LOCATION.equals(name)) {
if (parser.next() == XmlPullParser.TEXT) {
info.mLocation = parser.getText();
}
} else if (RESPONSE_TAG_PHOTOSURL.equals(name)) {
if (parser.next() == XmlPullParser.TEXT) {
info.mPhotosUrl = parser.getText();
}
} else if (RESPONSE_TAG_PROFILEURL.equals(name)) {
if (parser.next() == XmlPullParser.TEXT) {
info.mProfileUrl = parser.getText();
}
} else if (RESPONSE_TAG_MOBILEURL.equals(name)) {
if (parser.next() == XmlPullParser.TEXT) {
info.mMobileUrl = parser.getText();
}
}
}
}
/**
* Parses a valid Flickr XML response from the specified input stream. When the Flickr
* response contains the OK tag, the response is sent to the specified response parser.
*
* @param in The input stream containing the response sent by Flickr.
* @param responseParser The parser to use when the response is valid.
*
* @throws IOException
*/
private void parseResponse(InputStream in, ResponseParser responseParser) throws IOException {
final XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(new InputStreamReader(in));
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
if (type != XmlPullParser.START_TAG) {
throw new InflateException(parser.getPositionDescription()
+ ": No start tag found!");
}
String name = parser.getName();
if (RESPONSE_TAG_RSP.equals(name)) {
final String value = parser.getAttributeValue(null, RESPONSE_ATTR_STAT);
if (!RESPONSE_STATUS_OK.equals(value)) {
throw new IOException("Wrong status: " + value);
}
}
responseParser.parseResponse(parser);
} catch (XmlPullParserException e) {
final IOException ioe = new IOException("Could not parser the response");
ioe.initCause(e);
throw ioe;
}
}
/**
* Parses a valid Flickr Atom feed response from the specified input stream.
*
* @param in The input stream containing the response sent by Flickr.
* @param responseParser The parser to use when the response is valid.
*
* @throws IOException
*/
private void parseFeedResponse(InputStream in, ResponseParser responseParser)
throws IOException {
final XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(new InputStreamReader(in));
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
if (type != XmlPullParser.START_TAG) {
throw new InflateException(parser.getPositionDescription()
+ ": No start tag found!");
}
String name = parser.getName();
if (RESPONSE_TAG_FEED.equals(name)) {
responseParser.parseResponse(parser);
} else {
throw new IOException("Wrong start tag: " + name);
}
} catch (XmlPullParserException e) {
final IOException ioe = new IOException("Could not parser the response");
ioe.initCause(e);
throw ioe;
}
}
/**
* Executes an HTTP request on Flickr's web service. If the response is ok, the content
* is sent to the specified response handler.
*
* @param get The GET request to executed.
* @param handler The handler which will parse the response.
*
* @throws IOException
*/
private void executeRequest(HttpGet get, ResponseHandler handler) throws IOException {
HttpEntity entity = null;
HttpHost host = new HttpHost(API_REST_HOST, 80, "http");
try {
final HttpResponse response = mClient.execute(host, get);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
entity = response.getEntity();
final InputStream in = entity.getContent();
handler.handleResponse(in);
}
} finally {
if (entity != null) {
entity.consumeContent();
}
}
}
/**
* Builds an HTTP GET request for the specified Flickr API method. The returned request
* contains the web service path, the query parameter for the API KEY and the query
* parameter for the specified method.
*
* @param method The Flickr API method to invoke.
*
* @return A Uri.Builder containing the GET path, the API key and the method already
* encoded.
*/
private static Uri.Builder buildGetMethod(String method) {
final Uri.Builder builder = new Uri.Builder();
builder.path(API_REST_URL).appendQueryParameter(PARAM_API_KEY, API_KEY);
builder.appendQueryParameter(PARAM_METHOD, method);
return builder;
}
/**
* Copy the content of the input stream into the output stream, using a temporary
* byte array buffer whose size is defined by {@link #IO_BUFFER_SIZE}.
*
* @param in The input stream to copy from.
* @param out The output stream to copy to.
*
* @throws IOException If any error occurs during the copy.
*/
private static void copy(InputStream in, OutputStream out) throws IOException {
byte[] b = new byte[IO_BUFFER_SIZE];
int read;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
}
/**
* Closes the specified stream.
*
* @param stream The stream to close.
*/
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
android.util.Log.e(Flickr.LOG_TAG, "Could not close stream", e);
}
}
}
/**
* Response handler used with
* {@link Flickr#executeRequest(org.apache.http.client.methods.HttpGet,
* com.google.android.photostream.Flickr.ResponseHandler)}. The handler is invoked when
* a response is sent by the server. The response is made available as an input stream.
*/
private static interface ResponseHandler {
/**
* Processes the responses sent by the HTTP server following a GET request.
*
* @param in The stream containing the server's response.
*
* @throws IOException
*/
public void handleResponse(InputStream in) throws IOException;
}
/**
* Response parser used with {@link Flickr#parseResponse(java.io.InputStream,
* com.google.android.photostream.Flickr.ResponseParser)}. When Flickr returns a valid
* response, this parser is invoked to process the XML response.
*/
private static interface ResponseParser {
/**
* Processes the XML response sent by the Flickr web service after a successful
* request.
*
* @param parser The parser containing the XML responses.
*
* @throws XmlPullParserException
* @throws IOException
*/
public void parseResponse(XmlPullParser parser) throws XmlPullParserException, IOException;
}
}
| Java |
/*
* Copyright (C) 2008 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.google.android.photostream;
import android.os.*;
import android.os.Process;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.CancellationException;
import java.util.concurrent.atomic.AtomicInteger;
/**
* <p>UserTask enables proper and easy use of the UI thread. This class allows to
* perform background operations and publish results on the UI thread without
* having to manipulate threads and/or handlers.</p>
*
* <p>A user task is defined by a computation that runs on a background thread and
* whose result is published on the UI thread. A user task is defined by 3 generic
* types, called <code>Params</code>, <code>Progress</code> and <code>Result</code>,
* and 4 steps, called <code>begin</code>, <code>doInBackground</code>,
* <code>processProgress<code> and <code>end</code>.</p>
*
* <h2>Usage</h2>
* <p>UserTask must be subclassed to be used. The subclass will override at least
* one method ({@link #doInBackground(Object[])}), and most often will override a
* second one ({@link #onPostExecute(Object)}.)</p>
*
* <p>Here is an example of subclassing:</p>
* <pre>
* private class DownloadFilesTask extends UserTask<URL, Integer, Long> {
* public File doInBackground(URL... urls) {
* int count = urls.length;
* long totalSize = 0;
* for (int i = 0; i < count; i++) {
* totalSize += Downloader.downloadFile(urls[i]);
* publishProgress((int) ((i / (float) count) * 100));
* }
* }
*
* public void onProgressUpdate(Integer... progress) {
* setProgressPercent(progress[0]);
* }
*
* public void onPostExecute(Long result) {
* showDialog("Downloaded " + result + " bytes");
* }
* }
* </pre>
*
* <p>Once created, a task is executed very simply:</p>
* <pre>
* new DownloadFilesTask().execute(new URL[] { ... });
* </pre>
*
* <h2>User task's generic types</h2>
* <p>The three types used by a user task are the following:</p>
* <ol>
* <li><code>Params</code>, the type of the parameters sent to the task upon
* execution.</li>
* <li><code>Progress</code>, the type of the progress units published during
* the background computation.</li>
* <li><code>Result</code>, the type of the result of the background
* computation.</li>
* </ol>
* <p>Not all types are always used by a user task. To mark a type as unused,
* simply use the type {@link Void}:</p>
* <pre>
* private class MyTask extends UserTask<Void, Void, Void) { ... }
* </pre>
*
* <h2>The 4 steps</h2>
* <p>When a user task is executed, the task goes through 4 steps:</p>
* <ol>
* <li>{@link #onPreExecute()}, invoked on the UI thread immediately after the task
* is executed. This step is normally used to setup the task, for instance by
* showing a progress bar in the user interface.</li>
* <li>{@link #doInBackground(Object[])}, invoked on the background thread
* immediately after {@link # onPreExecute ()} finishes executing. This step is used
* to perform background computation that can take a long time. The parameters
* of the user task are passed to this step. The result of the computation must
* be returned by this step and will be passed back to the last step. This step
* can also use {@link #publishProgress(Object[])} to publish one or more units
* of progress. These values are published on the UI thread, in the
* {@link #onProgressUpdate(Object[])} step.</li>
* <li>{@link # onProgressUpdate (Object[])}, invoked on the UI thread after a
* call to {@link #publishProgress(Object[])}. The timing of the execution is
* undefined. This method is used to display any form of progress in the user
* interface while the background computation is still executing. For instance,
* it can be used to animate a progress bar or show logs in a text field.</li>
* <li>{@link # onPostExecute (Object)}, invoked on the UI thread after the background
* computation finishes. The result of the background computation is passed to
* this step as a parameter.</li>
* </ol>
*
* <h2>Threading rules</h2>
* <p>There are a few threading rules that must be followed for this class to
* work properly:</p>
* <ul>
* <li>The task instance must be created on the UI thread.</li>
* <li>{@link #execute(Object[])} must be invoked on the UI thread.</li>
* <li>Do not call {@link # onPreExecute ()}, {@link # onPostExecute (Object)},
* {@link #doInBackground(Object[])}, {@link # onProgressUpdate (Object[])}
* manually.</li>
* <li>The task can be executed only once (an exception will be thrown if
* a second execution is attempted.)</li>
* </ul>
*/
public abstract class UserTask<Params, Progress, Result> {
private static final String LOG_TAG = "UserTask";
private static final int CORE_POOL_SIZE = 1;
private static final int MAXIMUM_POOL_SIZE = 10;
private static final int KEEP_ALIVE = 10;
private static final BlockingQueue<Runnable> sWorkQueue =
new LinkedBlockingQueue<Runnable>(MAXIMUM_POOL_SIZE);
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "UserTask #" + mCount.getAndIncrement());
}
};
private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,
MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory);
private static final int MESSAGE_POST_RESULT = 0x1;
private static final int MESSAGE_POST_PROGRESS = 0x2;
private static final int MESSAGE_POST_CANCEL = 0x3;
private static final InternalHandler sHandler = new InternalHandler();
private final WorkerRunnable<Params, Result> mWorker;
private final FutureTask<Result> mFuture;
private volatile Status mStatus = Status.PENDING;
/**
* Indicates the current status of the task. Each status will be set only once
* during the lifetime of a task.
*/
public enum Status {
/**
* Indicates that the task has not been executed yet.
*/
PENDING,
/**
* Indicates that the task is running.
*/
RUNNING,
/**
* Indicates that {@link UserTask#onPostExecute(Object)} has finished.
*/
FINISHED,
}
/**
* Creates a new user task. This constructor must be invoked on the UI thread.
*/
public UserTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
return doInBackground(mParams);
}
};
mFuture = new FutureTask<Result>(mWorker) {
@Override
protected void done() {
Message message;
Result result = null;
try {
result = get();
} catch (InterruptedException e) {
android.util.Log.w(LOG_TAG, e);
} catch (ExecutionException e) {
throw new RuntimeException("An error occured while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
message = sHandler.obtainMessage(MESSAGE_POST_CANCEL,
new UserTaskResult<Result>(UserTask.this, (Result[]) null));
message.sendToTarget();
return;
} catch (Throwable t) {
throw new RuntimeException("An error occured while executing "
+ "doInBackground()", t);
}
message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
new UserTaskResult<Result>(UserTask.this, result));
message.sendToTarget();
}
};
}
/**
* Returns the current status of this task.
*
* @return The current status.
*/
public final Status getStatus() {
return mStatus;
}
/**
* Override this method to perform a computation on a background thread. The
* specified parameters are the parameters passed to {@link #execute(Object[])}
* by the caller of this task.
*
* This method can call {@link #publishProgress(Object[])} to publish updates
* on the UI thread.
*
* @param params The parameters of the task.
*
* @return A result, defined by the subclass of this task.
*
* @see #onPreExecute()
* @see #onPostExecute(Object)
* @see #publishProgress(Object[])
*/
public abstract Result doInBackground(Params... params);
/**
* Runs on the UI thread before {@link #doInBackground(Object[])}.
*
* @see #onPostExecute(Object)
* @see #doInBackground(Object[])
*/
public void onPreExecute() {
}
/**
* Runs on the UI thread after {@link #doInBackground(Object[])}. The
* specified result is the value returned by {@link #doInBackground(Object[])}
* or null if the task was cancelled or an exception occured.
*
* @param result The result of the operation computed by {@link #doInBackground(Object[])}.
*
* @see #onPreExecute()
* @see #doInBackground(Object[])
*/
@SuppressWarnings({"UnusedDeclaration"})
public void onPostExecute(Result result) {
}
/**
* Runs on the UI thread after {@link #publishProgress(Object[])} is invoked.
* The specified values are the values passed to {@link #publishProgress(Object[])}.
*
* @param values The values indicating progress.
*
* @see #publishProgress(Object[])
* @see #doInBackground(Object[])
*/
@SuppressWarnings({"UnusedDeclaration"})
public void onProgressUpdate(Progress... values) {
}
/**
* Runs on the UI thread after {@link #cancel(boolean)} is invoked.
*
* @see #cancel(boolean)
* @see #isCancelled()
*/
public void onCancelled() {
}
/**
* Returns <tt>true</tt> if this task was cancelled before it completed
* normally.
*
* @return <tt>true</tt> if task was cancelled before it completed
*
* @see #cancel(boolean)
*/
public final boolean isCancelled() {
return mFuture.isCancelled();
}
/**
* Attempts to cancel execution of this task. This attempt will
* fail if the task has already completed, already been cancelled,
* or could not be cancelled for some other reason. If successful,
* and this task has not started when <tt>cancel</tt> is called,
* this task should never run. If the task has already started,
* then the <tt>mayInterruptIfRunning</tt> parameter determines
* whether the thread executing this task should be interrupted in
* an attempt to stop the task.
*
* @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
* task should be interrupted; otherwise, in-progress tasks are allowed
* to complete.
*
* @return <tt>false</tt> if the task could not be cancelled,
* typically because it has already completed normally;
* <tt>true</tt> otherwise
*
* @see #isCancelled()
* @see #onCancelled()
*/
public final boolean cancel(boolean mayInterruptIfRunning) {
return mFuture.cancel(mayInterruptIfRunning);
}
/**
* Waits if necessary for the computation to complete, and then
* retrieves its result.
*
* @return The computed result.
*
* @throws CancellationException If the computation was cancelled.
* @throws ExecutionException If the computation threw an exception.
* @throws InterruptedException If the current thread was interrupted
* while waiting.
*/
public final Result get() throws InterruptedException, ExecutionException {
return mFuture.get();
}
/**
* Waits if necessary for at most the given time for the computation
* to complete, and then retrieves its result.
*
* @param timeout Time to wait before cancelling the operation.
* @param unit The time unit for the timeout.
*
* @return The computed result.
*
* @throws CancellationException If the computation was cancelled.
* @throws ExecutionException If the computation threw an exception.
* @throws InterruptedException If the current thread was interrupted
* while waiting.
* @throws TimeoutException If the wait timed out.
*/
public final Result get(long timeout, TimeUnit unit) throws InterruptedException,
ExecutionException, TimeoutException {
return mFuture.get(timeout, unit);
}
/**
* Executes the task with the specified parameters. The task returns
* itself (this) so that the caller can keep a reference to it.
*
* This method must be invoked on the UI thread.
*
* @param params The parameters of the task.
*
* @return This instance of UserTask.
*
* @throws IllegalStateException If {@link #getStatus()} returns either
* {@link UserTask.Status#RUNNING} or {@link UserTask.Status#FINISHED}.
*/
public final UserTask<Params, Progress, Result> execute(Params... params) {
if (mStatus != Status.PENDING) {
switch (mStatus) {
case RUNNING:
throw new IllegalStateException("Cannot execute task:"
+ " the task is already running.");
case FINISHED:
throw new IllegalStateException("Cannot execute task:"
+ " the task has already been executed "
+ "(a task can be executed only once)");
}
}
mStatus = Status.RUNNING;
onPreExecute();
mWorker.mParams = params;
sExecutor.execute(mFuture);
return this;
}
/**
* This method can be invoked from {@link #doInBackground(Object[])} to
* publish updates on the UI thread while the background computation is
* still running. Each call to this method will trigger the execution of
* {@link #onProgressUpdate(Object[])} on the UI thread.
*
* @param values The progress values to update the UI with.
*
* @see # onProgressUpdate (Object[])
* @see #doInBackground(Object[])
*/
protected final void publishProgress(Progress... values) {
sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
new UserTaskResult<Progress>(this, values)).sendToTarget();
}
private void finish(Result result) {
onPostExecute(result);
mStatus = Status.FINISHED;
}
private static class InternalHandler extends Handler {
@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
@Override
public void handleMessage(Message msg) {
UserTaskResult result = (UserTaskResult) msg.obj;
switch (msg.what) {
case MESSAGE_POST_RESULT:
// There is only one result
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
case MESSAGE_POST_CANCEL:
result.mTask.onCancelled();
break;
}
}
}
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
@SuppressWarnings({"RawUseOfParameterizedType"})
private static class UserTaskResult<Data> {
final UserTask mTask;
final Data[] mData;
UserTaskResult(UserTask task, Data... data) {
mTask = task;
mData = data;
}
}
}
| Java |
/*
* Copyright (C) 2008 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.google.android.photostream;
final class Preferences {
static final String NAME = "Photostream";
static final String KEY_ALARM_SCHEDULED = "photostream.scheduled";
static final String KEY_ENABLE_NOTIFICATIONS = "photostream.enable-notifications";
static final String KEY_VIBRATE = "photostream.vibrate";
static final String KEY_RINGTONE = "photostream.ringtone";
Preferences() {
}
}
| Java |
/*
* Copyright (C) 2008 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.google.android.photostream;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import java.util.Random;
/**
* This class contains various utilities to manipulate Bitmaps. The methods of this class,
* although static, are not thread safe and cannot be invoked by several threads at the
* same time. Synchronization is required by the caller.
*/
final class ImageUtilities {
private static final float PHOTO_BORDER_WIDTH = 3.0f;
private static final int PHOTO_BORDER_COLOR = 0xffffffff;
private static final float ROTATION_ANGLE_MIN = 2.5f;
private static final float ROTATION_ANGLE_EXTRA = 5.5f;
private static final Random sRandom = new Random();
private static final Paint sPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
private static final Paint sStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
static {
sStrokePaint.setStrokeWidth(PHOTO_BORDER_WIDTH);
sStrokePaint.setStyle(Paint.Style.STROKE);
sStrokePaint.setColor(PHOTO_BORDER_COLOR);
}
/**
* Rotate specified Bitmap by a random angle. The angle is either negative or positive,
* and ranges, in degrees, from 2.5 to 8. After rotation a frame is overlaid on top
* of the rotated image.
*
* This method is not thread safe.
*
* @param bitmap The Bitmap to rotate and apply a frame onto.
*
* @return A new Bitmap whose dimension are different from the original bitmap.
*/
static Bitmap rotateAndFrame(Bitmap bitmap) {
final boolean positive = sRandom.nextFloat() >= 0.5f;
final float angle = (ROTATION_ANGLE_MIN + sRandom.nextFloat() * ROTATION_ANGLE_EXTRA) *
(positive ? 1.0f : -1.0f);
final double radAngle = Math.toRadians(angle);
final int bitmapWidth = bitmap.getWidth();
final int bitmapHeight = bitmap.getHeight();
final double cosAngle = Math.abs(Math.cos(radAngle));
final double sinAngle = Math.abs(Math.sin(radAngle));
final int strokedWidth = (int) (bitmapWidth + 2 * PHOTO_BORDER_WIDTH);
final int strokedHeight = (int) (bitmapHeight + 2 * PHOTO_BORDER_WIDTH);
final int width = (int) (strokedHeight * sinAngle + strokedWidth * cosAngle);
final int height = (int) (strokedWidth * sinAngle + strokedHeight * cosAngle);
final float x = (width - bitmapWidth) / 2.0f;
final float y = (height - bitmapHeight) / 2.0f;
final Bitmap decored = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(decored);
canvas.rotate(angle, width / 2.0f, height / 2.0f);
canvas.drawBitmap(bitmap, x, y, sPaint);
canvas.drawRect(x, y, x + bitmapWidth, y + bitmapHeight, sStrokePaint);
return decored;
}
/**
* Scales the specified Bitmap to fit within the specified dimensions. After scaling,
* a frame is overlaid on top of the scaled image.
*
* This method is not thread safe.
*
* @param bitmap The Bitmap to scale to fit the specified dimensions and to apply
* a frame onto.
* @param width The maximum width of the new Bitmap.
* @param height The maximum height of the new Bitmap.
*
* @return A scaled version of the original bitmap, whose dimension are less than or
* equal to the specified width and height.
*/
static Bitmap scaleAndFrame(Bitmap bitmap, int width, int height) {
final int bitmapWidth = bitmap.getWidth();
final int bitmapHeight = bitmap.getHeight();
final float scale = Math.min((float) width / (float) bitmapWidth,
(float) height / (float) bitmapHeight);
final int scaledWidth = (int) (bitmapWidth * scale);
final int scaledHeight = (int) (bitmapHeight * scale);
final Bitmap decored = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, true);
final Canvas canvas = new Canvas(decored);
final int offset = (int) (PHOTO_BORDER_WIDTH / 2);
sStrokePaint.setAntiAlias(false);
canvas.drawRect(offset, offset, scaledWidth - offset - 1,
scaledHeight - offset - 1, sStrokePaint);
sStrokePaint.setAntiAlias(true);
return decored;
}
}
| Java |
/*
* Copyright (C) 2008 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.google.android.photostream;
import android.graphics.drawable.Drawable;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.ColorFilter;
class FastBitmapDrawable extends Drawable {
private Bitmap mBitmap;
FastBitmapDrawable(Bitmap b) {
mBitmap = b;
}
@Override
public void draw(Canvas canvas) {
canvas.drawBitmap(mBitmap, 0.0f, 0.0f, null);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
@Override
public void setAlpha(int alpha) {
}
@Override
public void setColorFilter(ColorFilter cf) {
}
@Override
public int getIntrinsicWidth() {
return mBitmap.getWidth();
}
@Override
public int getIntrinsicHeight() {
return mBitmap.getHeight();
}
@Override
public int getMinimumWidth() {
return mBitmap.getWidth();
}
@Override
public int getMinimumHeight() {
return mBitmap.getHeight();
}
public Bitmap getBitmap() {
return mBitmap;
}
} | Java |
package com.besttone.app;
import android.content.ContentValues;
import android.content.SearchRecentSuggestionsProvider;
import android.database.Cursor;
import android.net.Uri;
public class SuggestionProvider extends SearchRecentSuggestionsProvider {
public static final String AUTHORITY = "com.besttone.app.114SuggestionProvider";
public static final String[] COLUMNS;
public static final int MODE = DATABASE_MODE_QUERIES;
private static String sDatabaseName = "suggestions.db";
private static int totalRecord;
private final int MAXCOUNT = 20;
static {
String[] arrayOfString = new String[4];
arrayOfString[0] = "_id";
arrayOfString[1] = "display1";
arrayOfString[2] = "query";
arrayOfString[3] = "date";
COLUMNS = arrayOfString;
}
public SuggestionProvider() {
//super(contex, AUTHORITY, MODE);
setupSuggestions(AUTHORITY, MODE);
}
private Object[] columnValuesOfWord(int paramInt, String paramString1,
String paramString2) {
Object[] arrayOfObject = new Object[4];
arrayOfObject[0] = Integer.valueOf(paramInt);
arrayOfObject[1] = paramString1;
arrayOfObject[2] = paramString2;
arrayOfObject[3] = paramString1;
return arrayOfObject;
}
public Uri insert(Uri uri, ContentValues values) {
String selection = "query=?";
String[] selectionArgs = new String[1];
selectionArgs[0] = "没有搜索记录";
super.delete(uri, selection, selectionArgs);
Cursor localCursor = super.query(uri, COLUMNS, null, null, null);
if (localCursor!=null && localCursor.getCount() == 0) {
ContentValues localContentValues = new ContentValues();
localContentValues.put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[0],
Integer.valueOf(2));
localContentValues.put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[1],
Long.valueOf(System.currentTimeMillis()));
localContentValues.put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[2],
"清空搜索记录");
localContentValues.put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[3],
"清空搜索记录");
super.insert(uri, localContentValues);
}
values.put("date", Long.valueOf(System.currentTimeMillis()));
Uri localUri = super.insert(uri, values);
return localUri;
}
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Cursor localCursor = super.query(uri, projection, selection, selectionArgs, sortOrder);
Object localObject;
if (selectionArgs == null || selectionArgs.length == 0)
if (localCursor.getCount() == 0) {
ContentValues localContentValues = new ContentValues();
localContentValues
.put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[0],
Integer.valueOf(1));
localContentValues
.put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[1],
Long.valueOf(System.currentTimeMillis()));
localContentValues
.put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[2],
"没有搜索记录");
localContentValues
.put(android.provider.SearchRecentSuggestions.QUERIES_PROJECTION_1LINE[3],
"没有搜索记录");
super.insert(uri, localContentValues);
}
localCursor = super.query(uri, projection, selection, selectionArgs, sortOrder);
totalRecord = localCursor.getCount();
if (totalRecord > 20)
truncateHistory(uri, -20 + totalRecord);
return localCursor;
}
protected void truncateHistory(Uri paramUri, int paramInt) {
if (paramInt < 0)
throw new IllegalArgumentException();
String str = null;
if (paramInt > 0)
try {
str = "_id IN (SELECT _id FROM suggestions ORDER BY date ASC LIMIT "
+ String.valueOf(paramInt) + " OFFSET 1)";
delete(paramUri, str, null);
return;
} catch (RuntimeException localRuntimeException) {
}
}
} | Java |
package com.besttone.http;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.MarshalBase64;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParser;
import com.besttone.search.Client;
import com.besttone.search.ServerListener;
import com.besttone.search.model.ChResultInfo;
import com.besttone.search.model.OrgInfo;
import com.besttone.search.model.RequestInfo;
import com.besttone.search.util.Constants;
import com.besttone.search.util.SharedUtils;
import com.besttone.search.util.XmlHelper;
import android.util.Log;
import android.util.Xml;
public class WebServiceHelper {
private static final String TAG = "WebServiceHelper";
//命名空间
private static final String serviceNameSpace="http://ws.besttone.com/";
//调用方法(获得支持的城市)
//private static final String methodName="SearchChInfo";
private static final String methodName="searchChNewInfo";
private ChResultInfo resultInfo;
private int i = 0;
private List<Map<String, Object>> list;
private ArrayList <String> resultAsociateCountList = new ArrayList<String>();
public ArrayList <String> getResultAsociateCountList()
{
return resultAsociateCountList;
}
public static interface WebServiceListener {
public void onWebServiceSuccess();
public void onWebServiceFailed();
}
public void setmListener(WebServiceListener mListener) {
this.mListener = mListener;
}
private WebServiceListener mListener;
public List<Map<String, Object>> searchChInfo(RequestInfo rqInfo){
Long t1 = System.currentTimeMillis();
list = new LinkedList<Map<String, Object>>();
//返回的查询结果
String result =null;
//实例化SoapObject对象
SoapObject request=new SoapObject(serviceNameSpace, methodName);
//假设方法有参数的话,设置调用方法参数
String rqXml = XmlHelper.getRequestXml(rqInfo);
request.addProperty("xml", rqXml);
request.addProperty("name",Constants.chName);
request.addProperty("key",Constants.chKey);
//设置SOAP请求信息(参数部分为SOAP协议版本号,与你要调用的webService中版本号一致)
//获得序列化的Envelope
SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER10);
//设置是否调用的是dotNet开发的
envelope.dotNet = false;
envelope.bodyOut=request;
envelope.setOutputSoapObject(request);
//注册Envelope
(new MarshalBase64()).register(envelope);
//构建传输对象,并指明WSDL文档URL
//Android传输对象
HttpTransportSE transport=new HttpTransportSE(Constants.serviceURL);
transport.debug=true;
//调用WebService(其中参数为1:命名空间+方法名称,2:Envelope对象):
String soapAction = serviceNameSpace+methodName;
try {
transport.call(soapAction, envelope);
//解析返回数据
Object resultObj = envelope.getResponse();
result = resultObj.toString();
parseChInfo(result);
} catch (Exception e) {
e.printStackTrace();
Log.v(TAG, "获取XML出错");
}
Long t2 = System.currentTimeMillis();
Log.v(TAG, "获取查号信息耗时"+(t2-t1)+"毫秒");
return list;
}
public void parseChInfo(String xmlString) {
Map<String, Object> map = new HashMap<String, Object>();
InputStream inputStream=null;
//获得XmlPullParser解析器
XmlPullParser xmlParser = Xml.newPullParser();
try {
//得到文件流,并设置编码方式
xmlParser.setInput(new StringReader(xmlString));
//获得解析到的事件类别,这里有开始文档,结束文档,开始标签,结束标签,文本等等事件。
int evtType=xmlParser.getEventType();
List<OrgInfo> orgList = null;
OrgInfo info = null;
String propertyName = null;
String propertyValue = null;
//一直循环,直到文档结束
while(evtType!=XmlPullParser.END_DOCUMENT){
String tag = xmlParser.getName();
switch(evtType){
case XmlPullParser.START_TAG:
//如果是river标签开始,则说明需要实例化对象了
if (tag.equalsIgnoreCase("SearchResult")) {
resultInfo = new ChResultInfo();
break;
}
if (tag.equalsIgnoreCase("BDCDataSource")) {
resultInfo.setSource(xmlParser.nextText());
break;
}
if (tag.equalsIgnoreCase("BDCSearchflag")) {
resultInfo.setSearchFlag(xmlParser.nextText());
break;
}
if (tag.equalsIgnoreCase("ResultCount")) {
String cnt = xmlParser.nextText();
break;
}
if (tag.equalsIgnoreCase("ResultTime")) {
String time = xmlParser.nextText();
break;
}
if (tag.equalsIgnoreCase("SingleResult")) {
map = new HashMap<String, Object>();
break;
}
if (tag.equalsIgnoreCase("propertyName")) {
propertyName = xmlParser.nextText();
break;
}
if (tag.equalsIgnoreCase("propertyValue")) {
propertyValue = xmlParser.nextText();
if(propertyName!=null && "产品序列号".equals(propertyName)) {
// if(propertyValue!=null && !Constants.SPACE.equals(propertyValue)){
// info.setChId(Integer.valueOf(propertyValue));
// }
if(propertyValue==null || Constants.SPACE.equals(propertyValue)) {
propertyValue = Constants.SPACE;
}
map.put("chId", propertyValue);
}
if(propertyName!=null && "公司名称".equals(propertyName)) {
if(propertyValue==null || Constants.SPACE.equals(propertyValue)) {
propertyValue = Constants.SPACE;
}
map.put("name", propertyValue);
}
if(propertyName!=null && "首查电话".equals(propertyName)) {
if(propertyValue==null || Constants.SPACE.equals(propertyValue)) {
propertyValue = Constants.SPACE;
}
map.put("tel", propertyValue);
}
if(propertyName!=null && "地址".equals(propertyName)) {
if(propertyValue==null || Constants.SPACE.equals(propertyValue)) {
propertyValue = Constants.SPACE;
}
map.put("addr", propertyValue);
}
if(propertyName!=null && "ORG_ID".equals(propertyName)) {
map.put("orgId", propertyValue);
}
if(propertyName!=null && "所属城市".equals(propertyName)) {
map.put("city", Constants.getCity(propertyValue));
}
if(propertyName!=null && "Region_Cede".equals(propertyName)) {
map.put("regionCode", propertyValue);
}
if(propertyName!=null && "IS_DC".equals(propertyName)) {
map.put("isDc", propertyValue);
}
if(propertyName!=null && "IS_DF".equals(propertyName)) {
map.put("isDf", propertyValue);
}
if(propertyName!=null && "QYMP".equals(propertyName)) {
map.put("isQymp", propertyValue);
}
propertyName = null;
propertyValue = null;
}
break;
case XmlPullParser.END_TAG:
//如果遇到river标签结束,则把river对象添加进集合中
if (tag.equalsIgnoreCase("SingleResult")) {
if(map.get("addr")==null) {
map.put("addr", Constants.SPACE);
}
if(map.get("tel")==null) {
map.put("tel", Constants.SPACE);
}
list.add(map);
}
break;
default:break;
}
//如果xml没有结束,则导航到下一个river节点
evtType=xmlParser.next();
}
} catch (Exception e) {
e.printStackTrace();
Log.v(TAG, "xml解析出错"+e.getMessage());
}
}
public void sendRequest(final ServerListener listener, final RequestInfo rqInfo) {
Client.getThreadPoolForRequest().execute(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(1000);
} catch (Exception e) {
}
list = searchChInfo(rqInfo);
listener.serverDataArrived(list, false);
}
});
}
public ArrayList<String> getAssociateList(String key,String regionCode) {
Long t1 = System.currentTimeMillis();
ArrayList<String> resultAssociateList = new ArrayList<String>();
// new ArrayList<String>();
//返回的查询结果
String result =null;
//实例化SoapObject对象
SoapObject request=new SoapObject(serviceNameSpace, Constants.associate_method);
//假设方法有参数的话,设置调用方法参数
StringBuilder sb = new StringBuilder("");
if (key != null && regionCode != null)
{
sb.append("<ChKeyInpara>");
sb.append("<content><![CDATA[" + key + "]]></content>");
sb.append("<regionCode><![CDATA[" + regionCode + "]]></regionCode>");
Log.d("regionCode",regionCode);
sb.append("<imsi><![CDATA[" + SharedUtils.getCurrentPhoneImsi(Client.getContext()) + "]]></imsi>");
sb.append("<deviceid><![CDATA[" + SharedUtils.getCurrentPhoneDeviceId(Client.getContext())
+ "]]></deviceid>");
sb.append("<pageSize><![CDATA[" + "10" + "]]></pageSize>");
sb.append("</ChKeyInpara>");
}
request.addProperty("xml", sb.toString());
request.addProperty("name",Constants.chName);
request.addProperty("key",Constants.chKey);
//设置SOAP请求信息(参数部分为SOAP协议版本号,与你要调用的webService中版本号一致)
//获得序列化的Envelope
SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER10);
//设置是否调用的是dotNet开发的
envelope.dotNet = false;
envelope.bodyOut=request;
envelope.setOutputSoapObject(request);
//注册Envelope
(new MarshalBase64()).register(envelope);
//构建传输对象,并指明WSDL文档URL
//Android传输对象
HttpTransportSE transport=new HttpTransportSE(Constants.serviceURL);
transport.debug=true;
//调用WebService(其中参数为1:命名空间+方法名称,2:Envelope对象):
String soapAction = serviceNameSpace+Constants.associate_method;
try {
transport.call(soapAction, envelope);
//解析返回数据
Object resultObj = envelope.getResponse();
result = resultObj.toString();
resultAssociateList = parseKeywordInfo(result);
} catch (Exception e) {
e.printStackTrace();
Log.v(TAG, "关键词联想获取出错");
}
Long t2 = System.currentTimeMillis();
Log.v(TAG, "关键词联想获取耗时"+(t2-t1)+"毫秒");
// if(mListener!=null)
// mListener.onWebServiceSuccess();
return resultAssociateList;
}
public ArrayList<String> parseKeywordInfo(String xmlString) {
Map<String, Object> map = new HashMap<String, Object>();
ArrayList<String> resultList = new ArrayList<String>();
InputStream inputStream=null;
//获得XmlPullParser解析器
XmlPullParser xmlParser = Xml.newPullParser();
try{
//得到文件流,并设置编码方式
xmlParser.setInput(new StringReader(xmlString));
Log.d("xml",xmlString);
//获得解析到的事件类别,这里有开始文档,结束文档,开始标签,结束标签,文本等等事件。
int evtType=xmlParser.getEventType();
// 一直循环,直到文档结束
while (evtType != XmlPullParser.END_DOCUMENT) {
String tag = xmlParser.getName();
switch (evtType) {
case XmlPullParser.START_TAG:
// 如果是river标签开始,则说明需要实例化对象了
if (tag.equalsIgnoreCase("ChKeyResult")) {
map = new HashMap<String, Object>();
break;
}
if (tag.equalsIgnoreCase("resultNum")) {
String resultNum = xmlParser.nextText();
map.put("resultNum", resultNum);
break;
}
if (tag.equalsIgnoreCase("result")) {
String result = xmlParser.nextText();
map.put("result", result);
break;
}
if (tag.equalsIgnoreCase("searchTime")) {
String searchTime = xmlParser.nextText();
map.put("searchTime", searchTime);
break;
}
if (tag.equalsIgnoreCase("ChKeyList")) {
break;
}
if (tag.equalsIgnoreCase("searchKey")) {
String searchKey = xmlParser.nextText();
resultList.add(searchKey);
Log.v("resultlist",searchKey);
break;
}
if (tag.equalsIgnoreCase("zqCount")) {
String zqCount = xmlParser.nextText();
resultAsociateCountList.add(zqCount);
Log.v("resultAsociateCountList",zqCount);
break;
}
break;
case XmlPullParser.END_TAG:
// 如果遇到river标签结束,则把river对象添加进集合中
if (tag.equalsIgnoreCase("ChKeyResult")) {
map.put("resultList", resultList);
}
break;
default:
break;
}
// 如果xml没有结束,则导航到下一个river节点
evtType = xmlParser.next();
}
} catch (Exception e) {
e.printStackTrace();
Log.v(TAG, "xml解析出错"+e.getMessage());
}
return resultList;
}
}
| Java |
package com.besttone.http;
import com.besttone.search.Client;
public class UpdateRequest extends WebServiceHelper
{
public static interface UpdateListener
{
public void onUpdateAvaiable(String msg, String url);
public void onUpdateMust(String msg, String url);
public void onUpdateNoNeed(String msg);
public void onUpdateError(short code, Exception e);
}
private String latestVersionCode = "";
private String url = "";
private String versionInfo = "";
private UpdateListener mListener = null;
public void setListener(UpdateListener mListener)
{
this.mListener = mListener;
}
public void checkUpdate()
{
Client.getThreadPoolForRequest().execute(new Runnable()
{
@Override
public void run()
{
// TODO Auto-generated method stub
getUpdateInfo();
Client.postRunnable(new Runnable()
{
@Override
public void run()
{
// TODO Auto-generated method stub
if ( !Client.getVersion(Client.getContext()) .equals( latestVersionCode ) )
{
mListener.onUpdateAvaiable(versionInfo, "");
}
else
{
mListener.onUpdateNoNeed("");
}
}
});
}
});
}
private void getUpdateInfo()
{
this.latestVersionCode = "0.2.9";
this.url = "http://droidapps.googlecode.com/files/MiniFetion-2.8.4.apk";
this.versionInfo="更新信息:";
}
}
| Java |
package com.besttone.search;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.besttone.adapter.AreaAdapter;
import com.besttone.adapter.CateAdapter;
import com.besttone.adapter.SortAdapter;
import com.besttone.http.WebServiceHelper;
import com.besttone.search.model.District;
import com.besttone.search.model.RequestInfo;
import com.besttone.search.util.Constants;
import com.besttone.search.util.SharedUtils;
import com.besttone.widget.PoiListItem;
import com.besttone.search.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;
public class SearchResultActivity extends Activity implements ServerListener,
OnClickListener {
private Context mContext;
private List<Map<String, Object>> filterData;
private View loadingView;
private View addShopView;
private ListView list;
private boolean isEnd = false;
PoiResultAdapter resultAdapter = null;
ListAdapter areaAdapter = null;
CateAdapter cateAdapter = null;
private ImageButton btn_back;
private Button mSearchBtn;
private Button mAreaBtn;
private String[] mAreaArray = null;
private List<District> localDistrictList = null;
private String[] mChannelArray = null;
private int mAreaIndex = 0;
private Button mChannelBtn;
public PopupWindow mPopupWindow;
private ListView popListView;
private String keyword;
private RequestInfo rqInfo;
private WebServiceHelper serviceHelper;
private boolean isLoadingRemoved = false;
private boolean isLoadingEnd = false;
Handler handler = new Handler() {
public void handleMessage(Message paramMessage) {
if (paramMessage.what == 1) {
loadingView.setVisibility(View.GONE);
} else if (paramMessage.what == 2) {
list.removeFooterView(loadingView);
isLoadingRemoved = true;
} else if (paramMessage.what == 3) {
list.addFooterView(loadingView);
loadingView.setVisibility(View.VISIBLE);
isLoadingRemoved = false;
} else if (paramMessage.what == 4) {
loadingView.setVisibility(View.VISIBLE);
} else if (paramMessage.what == 5) {
list.removeFooterView(loadingView);
isLoadingRemoved = true;
if(!isLoadingEnd)
addShopView();
}
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.search_result);
mContext = this.getApplicationContext();
init();
}
private ImageButton.OnClickListener backListner = new ImageButton.OnClickListener() {
public void onClick(View v) {
finish();
}
};
private Button.OnClickListener searchHistroyListner = new Button.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(SearchResultActivity.this, SearchActivity.class);
finish();
startActivity(intent);
}
};
private AdapterView.OnItemClickListener mOnClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
// Intent intent = new Intent();
// ListView listView = (ListView)parent;
// HashMap<String, String> map = (HashMap<String, String>) listView.getItemAtPosition(position);
// intent.setClass(ResultActivity.this, DetailActivity.class);
// if(map.get("id")==null || "".equals(map.get("id"))) {
// intent.putExtra("id", "2029602847-421506714");
// } else {
// intent.putExtra("id", map.get("id"));
// }
// startActivity(intent);
// ResultActivity.this.finish();
//显示数据详情
//Toast.makeText(SearchResultActivity.this, "正在开发中,敬请期待...", Toast.LENGTH_SHORT).show();
}
};
public class PoiResultAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public PoiResultAdapter(Context context) {
this.mInflater = LayoutInflater.from(context);
}
public int getCount() {
return filterData.size();
}
public Object getItem(int position) {
return filterData.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
}
convertView = mInflater.inflate(R.layout.search_result_item, null);
// convertView.findViewById(R.id.name).setSelected(true);
// convertView.findViewById(R.id.addr).setSelected(true);
PoiListItem item = (PoiListItem) convertView;
Map map = filterData.get(position);
item.setPoiData(map.get("name").toString(), map.get("tel")
.toString(), map.get("addr").toString(),(map
.get("city")==null?null:(map
.get("city")).toString()) );
if (position == filterData.size() - 1 && !isEnd) {
loadingView.setVisibility(View.VISIBLE);
//下拉获取数据
int size = filterData.size();
int page = 1 + size/Constants.PAGE_SIZE;
int currentPage =Integer.valueOf(rqInfo.getPage());
if(size==currentPage*Constants.PAGE_SIZE) {
rqInfo.setPage(Constants.SPACE + page);
serviceHelper.sendRequest(SearchResultActivity.this, rqInfo);
} else {
//Toast.makeText(ResultActivity.this, "没有更多的数据", Toast.LENGTH_SHORT).show();
Message localMessage = new Message();
localMessage.what = 5;
handler.sendMessage(localMessage);
}
}
return convertView;
}
}
public void addShopView() {
isLoadingEnd = true;
addShopView = getLayoutInflater().inflate(R.layout.search_result_empty, null, false);
list.addFooterView(addShopView);
addShopView.setVisibility(View.VISIBLE);
}
public void serverDataArrived(List list, boolean isEnd) {
this.isEnd = isEnd;
Iterator iter = list.iterator();
while (iter.hasNext()) {
filterData.add((Map<String, Object>) iter.next());
}
Message localMessage = new Message();
if (!isEnd) {
localMessage.what = 1;
} else {
localMessage.what = 2;
}
if(list!=null && list.size()==0){
localMessage.what = 5;
}
this.handler.sendMessage(localMessage);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.area: {
showDialogPopup(R.id.area);
break;
}
case R.id.channel: {
showDialogPopup(R.id.channel);
// if (mPopupWindow != null && mPopupWindow.isShowing()) {
// mPopupWindow.dismiss();
// } else {
// createPopWindow(v);
// }
break;
}
}
}
protected void showDialogPopup(int viewId) {
AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
switch (viewId) {
case R.id.area: {
if (areaAdapter == null) {
areaAdapter = new AreaAdapter(this, mAreaArray);
}
localBuilder.setAdapter(areaAdapter, new areaPopupListener(
areaAdapter));
break;
}
case R.id.channel: {
if (cateAdapter == null) {
cateAdapter = new CateAdapter(this, mChannelArray);
}
localBuilder.setAdapter(cateAdapter, new channelPopupListener(
cateAdapter));
break;
}
}
AlertDialog localAlertDialog = localBuilder.create();
localAlertDialog.show();
}
class areaPopupListener implements DialogInterface.OnClickListener {
AreaAdapter mAdapter;
public areaPopupListener(ListAdapter adapter) {
mAdapter = (AreaAdapter) adapter;
}
public void onClick(DialogInterface dialog, int which) {
((AreaAdapter) mAdapter).setTypeIndex(which);
final String cityName = ((AreaAdapter) mAdapter).getSelect();
mAreaBtn.setText(cityName);
filterData.clear();
filterData = new ArrayList<Map<String, Object>>();
resultAdapter.notifyDataSetChanged();
if (isLoadingRemoved) {
list.addFooterView(loadingView);
loadingView.setVisibility(View.VISIBLE);
isLoadingRemoved = false;
} else {
loadingView.setVisibility(View.VISIBLE);
}
if(isLoadingEnd){
list.removeFooterView(addShopView);
isLoadingEnd = false;
}
//获取数据
String simplifyCode = null;
if("全部区域".equals(cityName)) {
simplifyCode = SharedUtils.getCurrentSimplifyCode(mContext);
} else {
simplifyCode = ((District)(localDistrictList.get(which-1))).getDistrictCode();
// simplifyCode = Constants.getSimplifyCodeByName(mContext, cityName);
}
// Log.d("getdis",simplifyCode);
rqInfo.setRegion(simplifyCode);
String tradeName = mChannelBtn.getText().toString();
if(!"全部行业".equals(tradeName)) {
rqInfo.setContent(keyword + "/n|" + tradeName + "/i");
} else {
rqInfo.setContent(keyword+"/n");
}
rqInfo.setPage("1");
rqInfo.setPageSize(Constants.SPACE + Constants.PAGE_SIZE);
serviceHelper = new WebServiceHelper();
serviceHelper.sendRequest(SearchResultActivity.this, rqInfo);
}
}
class channelPopupListener implements DialogInterface.OnClickListener {
CateAdapter cAdapter;
public channelPopupListener(CateAdapter adapter) {
cAdapter = (CateAdapter) adapter;
}
public void onClick(DialogInterface dialog, int which) {
((CateAdapter) cAdapter).setTypeIndex(which);
final String tradeName = ((CateAdapter) cAdapter).getSelect();
mChannelBtn.setText(tradeName);
filterData.clear();
filterData = new ArrayList<Map<String, Object>>();
resultAdapter.notifyDataSetChanged();
if (isLoadingRemoved) {
list.addFooterView(loadingView);
loadingView.setVisibility(View.VISIBLE);
isLoadingRemoved = false;
} else {
loadingView.setVisibility(View.VISIBLE);
}
if(isLoadingEnd){
list.removeFooterView(addShopView);
isLoadingEnd = false;
}
//获取数据
String simplifyCode = null;
String cityName = mAreaBtn.getText().toString();
if("全部区域".equals(cityName)) {
simplifyCode = SharedUtils.getCurrentSimplifyCode(mContext);
} else {
simplifyCode = Constants.getSimplifyCodeByName(mContext, cityName);
}
if(!"全部行业".equals(tradeName)) {
rqInfo.setContent(keyword + "/n|" + tradeName + "/i");
} else {
rqInfo.setContent(keyword+"/n");
}
rqInfo.setRegion(simplifyCode);
rqInfo.setPage("1");
rqInfo.setPageSize(Constants.SPACE + Constants.PAGE_SIZE);
serviceHelper = new WebServiceHelper();
serviceHelper.sendRequest(SearchResultActivity.this, rqInfo);
}
}
private void init()
{
filterData = PoiResultData.getData();
list = (ListView) findViewById(R.id.resultlist);
list.setFastScrollEnabled(true);
resultAdapter = new PoiResultAdapter(this);
btn_back = (ImageButton) findViewById(R.id.left_title_button);
btn_back.setOnClickListener(backListner);
rqInfo = new RequestInfo();
Bundle bundle = this.getIntent().getExtras();
rqInfo.setRegion(SharedUtils.getCurrentSimplifyCode(this));
rqInfo.setDeviceid(SharedUtils.getCurrentPhoneDeviceId(this));
rqInfo.setImsi(SharedUtils.getCurrentPhoneImsi(this));
rqInfo.setMobile(SharedUtils.getCurrentPhoneNo(this));
rqInfo.setPage("1");
rqInfo.setPageSize(Constants.SPACE + Constants.PAGE_SIZE);
keyword = bundle.getString("keyword");
rqInfo.setContent(keyword+"/n");
serviceHelper = new WebServiceHelper();
serviceHelper.sendRequest(this, rqInfo);
mSearchBtn = ((Button)findViewById(R.id.start_search));
mSearchBtn.setText(bundle.getString("keyword"));
mSearchBtn.setOnClickListener(searchHistroyListner);
loadingView = LayoutInflater.from(this).inflate(R.layout.listfooter,
null);
list.addFooterView(loadingView);
list.setAdapter(resultAdapter);
list.setOnItemClickListener(mOnClickListener);
list.setOnItemLongClickListener(mOnLongClickListener);
mAreaBtn = ((Button)findViewById(R.id.area));
mChannelBtn = ((Button)findViewById(R.id.channel));
mAreaBtn.setOnClickListener(this);
mChannelBtn.setOnClickListener(this);
initHomeView();
}
private void initHomeView() {
localDistrictList = Constants.getDistrictList(this, SharedUtils.getCurrentCityCode(this));
mAreaArray = Constants.getDistrictArray(this, SharedUtils.getCurrentCityCode(this));
if ((mAreaArray == null) || (this.mAreaArray.length == 0)) {
mAreaBtn.setText("全部区域");
mAreaBtn.setEnabled(false);
}
while (true) {
mChannelArray = getResources().getStringArray(R.array.trade_name_items);
mAreaBtn.setText(this.mAreaArray[this.mAreaIndex]);
mAreaBtn.setEnabled(true);
return;
}
}
private void createPopWindow(View parent) {
// LayoutInflater lay = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// View view = lay.inflate(R.layout.popup_window, null );
//
// mPopupWindow = new PopupWindow(view, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
//
// //初始化listview,加载数据
// popListView = (ListView) findViewById(R.id.pop_list);
//// if (sortAdapter == null) {
//// sortAdapter = new SortAdapter(this, mSortArray);
//// }
//// popListView.setAdapter(sortAdapter);
//
//
// //设置整个popupwindow的样式
// mPopupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.right_filter_bg));
//
// mPopupWindow.setFocusable(true );
// mPopupWindow.setTouchable(true);
// mPopupWindow.setOutsideTouchable(true);
// mPopupWindow.update();
// mPopupWindow.showAsDropDown(parent, 10, 10);
View contentView = LayoutInflater.from(getApplicationContext())
.inflate(R.layout.popup_window, null);
mPopupWindow = new PopupWindow(contentView, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
mPopupWindow.setContentView(contentView);
//设置整个popupwindow的样式
mPopupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.right_filter_bg));
String[] name = openDir();
ListView listView = (ListView) contentView.findViewById(R.id.pop_list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, name);
listView.setAdapter(adapter);
mPopupWindow.setFocusable(true );
mPopupWindow.setTouchable(true);
mPopupWindow.setOutsideTouchable(true);
mPopupWindow.update();
mPopupWindow.showAsDropDown(parent, 10, 10);
}
private String[] openDir() {
String[] name;
String rootPath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
File file = new File(rootPath);
File[] files = file.listFiles();
name = new String[files.length];
for (int i = 0; i < files.length; i++) {
name[i] = files[i].getName();
System.out.println(name[i]);
}
return name;
}
private AdapterView.OnItemLongClickListener mOnLongClickListener = new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
ListView listView = (ListView)parent;
HashMap<String, String> map = (HashMap<String, String>) listView.getItemAtPosition(position);
final String name = map.get("name");
final String tel = map.get("tel");
final String addr = map.get("addr");
String[] array = new String[2];
array[0] = "呼叫 " + tel;
array[1] = "添加至联系人";
new AlertDialog.Builder(SearchResultActivity.this)
.setTitle(name)
.setItems(array,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
if(which == 0) {
Intent myIntentDial = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tel));
startActivity(myIntentDial);
}
if(which == 1){
String rwContactId = getContactId(name);
ContentResolver resolver = mContext.getContentResolver();
ContentValues values = new ContentValues();
//联系人中是否存在,若存在则更新
if(rwContactId!=null && !"".equals(rwContactId)){
Toast.makeText(SearchResultActivity.this, "商家已存在", Toast.LENGTH_SHORT).show();
// String whereClause = ContactsContract.RawContacts.Data.RAW_CONTACT_ID + "= ? AND " + ContactsContract.Data.MIMETYPE + "=?";
//
// values.clear();
// values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
// values.put(StructuredName.DISPLAY_NAME, name);
// resolver.update(Data.CONTENT_URI, values, whereClause, new String[]{rwContactId, StructuredName.CONTENT_ITEM_TYPE });
//
// values.clear();
// values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
// values.put(Phone.NUMBER, tel);
// if(isMobilePhone(tel)){
// values.put(Phone.TYPE, Phone.TYPE_MOBILE);
// values.put(Phone.LABEL, Phone.TYPE_WORK_MOBILE);
// } else {
// values.put(Phone.TYPE, Phone.TYPE_WORK);
// values.put(Phone.LABEL, Phone.TYPE_WORK);
// }
// resolver.update(Data.CONTENT_URI, values, whereClause, new String[]{rwContactId, Phone.CONTENT_ITEM_TYPE});
//
// values.clear();
// values.put(Data.MIMETYPE, StructuredPostal.CONTENT_ITEM_TYPE);
// values.put(StructuredPostal.TYPE, StructuredPostal.TYPE_WORK);
// values.put(StructuredPostal.LABEL, StructuredPostal.TYPE_WORK);
// values.put(StructuredPostal.STREET, addr);
// resolver.update(Data.CONTENT_URI, values, whereClause, new String[]{rwContactId, StructuredPostal.CONTENT_ITEM_TYPE});
//
// Toast.makeText(SearchResultActivity.this, "联系人更新成功", Toast.LENGTH_SHORT).show();
} else {
Uri rawContactUri = resolver.insert(
RawContacts.CONTENT_URI, values);
long rawContactId = ContentUris.parseId(rawContactUri);
values.clear();
values.put(Data.RAW_CONTACT_ID, rawContactId);
values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
values.put(StructuredName.DISPLAY_NAME, name);
resolver.insert(Data.CONTENT_URI, values);
values.clear();
values.put(Data.RAW_CONTACT_ID, rawContactId);
values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
values.put(Phone.NUMBER, tel);
if(isMobilePhone(tel)){
values.put(Phone.TYPE, Phone.TYPE_MOBILE);
values.put(Phone.LABEL, Phone.TYPE_WORK_MOBILE);
} else {
values.put(Phone.TYPE, Phone.TYPE_WORK);
values.put(Phone.LABEL, Phone.TYPE_WORK);
}
resolver.insert(Data.CONTENT_URI, values);
values.clear();
values.put(Data.RAW_CONTACT_ID, rawContactId);
values.put(Data.MIMETYPE, StructuredPostal.CONTENT_ITEM_TYPE);
values.put(StructuredPostal.TYPE, StructuredPostal.TYPE_WORK);
values.put(StructuredPostal.LABEL, StructuredPostal.TYPE_WORK);
values.put(StructuredPostal.STREET, addr);
resolver.insert(Data.CONTENT_URI, values);
Toast.makeText(SearchResultActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
}
}
}
})
.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
return true;
}
};
public boolean isMobilePhone(String tel){
boolean flag = false;
if(tel!=null && tel.length()==11){
String reg = "^(13[0-9]|15[012356789]|18[0236789]|14[57])[0-9]{8}$";
flag = tel.matches(reg);
}
return flag;
}
/*
* 根据电话号码取得联系人姓名
*/
public void getPeople() {
String[] projection = { ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER};
// 将自己添加到 msPeers 中
Cursor cursor = this.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, // Which columns to return.
ContactsContract.CommonDataKinds.Phone.NUMBER + " = '021-65291718'", // WHERE clause.
null, // WHERE clause value substitution
null); // Sort order.
if( cursor == null ) {
return;
}
System.out.println(cursor.getCount());
for( int i = 0; i < cursor.getCount(); i++ )
{
cursor.moveToPosition(i);
// 取得联系人名字
int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
String name = cursor.getString(nameFieldColumnIndex);
System.out.println("联系人姓名:" + name);
Toast.makeText(SearchResultActivity.this, "联系人姓名:" + name, Toast.LENGTH_SHORT).show();
}
}
/*
* 根据联系人姓名取得ID
*/
public String getContactId(String name) {
String rawContactId = null;
String[] projection = { ContactsContract.RawContacts.Data.RAW_CONTACT_ID };
// 将自己添加到 msPeers 中
Cursor cursor = this.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, // Which columns to return.
ContactsContract.PhoneLookup.DISPLAY_NAME + " = '"+ name +"'", // WHERE clause.
null, // WHERE clause value substitution
null); // Sort order.
if( cursor == null ) {
return null;
} else if(cursor.getCount()>0){
cursor.moveToFirst();
// 取得联系人ID
int idFieldColumnIndex = cursor.getColumnIndex(ContactsContract.RawContacts.Data.RAW_CONTACT_ID);
rawContactId = cursor.getString(idFieldColumnIndex);
return rawContactId;
}
return null;
}
} | Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.