code
stringlengths 1
2.01M
| repo_name
stringlengths 3
62
| path
stringlengths 1
267
| language
stringclasses 231
values | license
stringclasses 13
values | size
int64 1
2.01M
|
|---|---|---|---|---|---|
<?php
require_once 'Zend/Config/Xml.php';
class XMLParserPlugin {
/**
* Parsea una seccion de un archivo xml
*
* @param Xml file $xmlfile
* @param section $option
* @return parsed section from xml file
*/
public static function parse($xmlfile, $section) {
// Parseo XML
$parsed = new Zend_Config_Xml($xmlfile, $section);
return $parsed;
}
}
|
0admin
|
trunk/plugin/XMLParserPlugin.php
|
PHP
|
oos
| 389
|
<?php
//set_include_path('.:/php/includes:/home/diegolaprida/domains/simesev.com.ar/public_html/admin/core:/usr/lib/php:/usr/local/lib/php');
require_once 'Zend/Session/Namespace.php';
class SessionPlugin {
/**
* Retorna la sessionVar del namespace
*/
public static function getSessionValue($sessionVar, $namespace) {
$session = new Zend_Session_Namespace($namespace);
if (isset($session->$sessionVar)) {
return $session->$sessionVar;
} else {
return null;
}
}
/**
* Setea una session var en un namespace
*/
public static function setSessionValue($value, $sessionVar, $namespace) {
$session = new Zend_Session_Namespace($namespace);
$session->$sessionVar = $value;
}
/**
* Setea el expiration time para un namespace
*/
public static function setExpirationSeconds($namespace, $time) {
$session = new Zend_Session_Namespace($namespace);
if (isset($session)) {
$session->setExpirationSeconds($time);
}
}
}
|
0admin
|
trunk/plugin/SessionPlugin.php
|
PHP
|
oos
| 1,004
|
<?php
class AppConfigPlugin {
/**
* Retorna el objeto Menu con sus propiedades seteadas
*/
public static function getMenuItems($rol = null) {
require('conf/configuration.php');
// si el rol es "administrador" retornar todos los menu items
if ($rol == "0" || $rol == null) {
return $menuItems;
}
// sino, filtrar solo los menu permitidos
$accessMenuItems = array();
foreach ($menuItems as $menuItem) {
//echo "<br/>rol usuario: " . $rol;
//echo "<br/>rol pagina: " . $menuItem[rol];
if (strpos($rol, $menuItem[rol]) !== false)
$accessMenuItems[] = $menuItem;
}
return $accessMenuItems;
}
/**
* Retorna el objeto Manage con sus propiedades seteadas
*/
public static function getManageItems() {
require('conf/configuration.php');
return $manageItems;
}
/**
* Retorna app info
*/
public static function getAppInfo() {
require('conf/configuration.php');
return $appInfo;
}
public static function search($array, $script, &$breadcrumb, &$found) {
for($i = 0; $i <= count($array) && !$found; $i++) {
$item = $array[$i];
if ($item[script] == $script) {
$breadcrumb[] = array("name" => $item[name], "script" => $item[script], "image" => $item[image]);
$found = true;
} else {
if (($item[sons] != null) && (count($item[sons]) > 0)) {
$breadcrumb[] = array("name" => $item[name], "script" => $item[script]);
$found = AppConfigPlugin::search($item[sons], $script, $breadcrumb, $found);
if (!$found)
array_pop($breadcrumb);
}
}
}
return $found;
}
/**
* Retorna page tree
*/
public static function getBreadcrumb($script) {
require('conf/configuration.php');
$found = false;
$breadcrumb = array();
$exist = AppConfigPlugin::search($pageTree, $script, $breadcrumb, $found);
return $breadcrumb;
}
public static function sons($array, $script, &$sons, &$found) {
for($i = 0; $i <= count($array) && !$found; $i++) {
$item = $array[$i];
if ($item[script] == $script) {
$sons = $item[sons];
$found = true;
} else {
if (($item[sons] != null) && (count($item[sons]) > 0)) {
//$breadcrumb[] = array("name" => $item[name], "script" => $item[script]);
$found = AppConfigPlugin::sons($item[sons], $script, $sons, $found);
/*if (!$found)
array_pop($breadcrumb);*/
}
}
}
return $found;
}
/**
* Retorna page tree
*/
public static function getSons($script) {
require('conf/configuration.php');
$found = false;
$sons = array();
$exist = AppConfigPlugin::sons($pageTree, $script, $sons, $found);
return $sons;
}
/**
* Retorna los iconos img
*/
public static function getIconsImg() {
require('conf/configuration.php');
return $iconsImg;
}
/**
* Retorna la cantidad de items para mostrar en cada pagina
*/
public static function getTotalItemsPerPage() {
require('conf/configuration.php');
return $totalItemsPerPage;
}
/**
* Retorna el nombre del script php actual (licencias.php)
*/
public static function getCurrentScript() {
$file = $_SERVER["SCRIPT_NAME"];
$break = explode('/', $file);
return $break[count($break) - 1];
}
/**
* Retorna la url con los parametros de GET incluido (ej. licencias.php?action=add)
*/
function curPageURL() {
$url = $_SERVER["REQUEST_URI"];
$break = explode('/', $url);
$break = $break[count($break) - 1];
$break = explode('&', $break);
return $break[0];
}
}
|
0admin
|
trunk/plugin/AppConfigPlugin.php
|
PHP
|
oos
| 3,638
|
<?php
/**
* thumbnail.inc.php
*
* @author Ian Selby (ian@gen-x-design.com)
* @copyright Copyright 2006
* @version 1.1 (PHP5)
*
*/
/**
* PHP class for dynamically resizing, cropping, and rotating images for thumbnail purposes and either displaying them on-the-fly or saving them.
*
*/
class Thumbnail {
/**
* Error message to display, if any
*
* @var string
*/
private $errmsg;
/**
* Whether or not there is an error
*
* @var boolean
*/
private $error;
/**
* Format of the image file
*
* @var string
*/
private $format;
/**
* File name and path of the image file
*
* @var string
*/
private $fileName;
/**
* Image meta data if any is available (jpeg/tiff) via the exif library
*
* @var array
*/
public $imageMeta;
/**
* Current dimensions of working image
*
* @var array
*/
private $currentDimensions;
/**
* New dimensions of working image
*
* @var array
*/
private $newDimensions;
/**
* Image resource for newly manipulated image
*
* @var resource
*/
private $newImage;
/**
* Image resource for image before previous manipulation
*
* @var resource
*/
private $oldImage;
/**
* Image resource for image being currently manipulated
*
* @var resource
*/
private $workingImage;
/**
* Percentage to resize image by
*
* @var int
*/
private $percent;
/**
* Maximum width of image during resize
*
* @var int
*/
private $maxWidth;
/**
* Maximum height of image during resize
*
* @var int
*/
private $maxHeight;
/**
* Class constructor
*
* @param string $fileName
* @return Thumbnail
*/
public function __construct($fileName) {
//make sure the GD library is installed
if(!function_exists("gd_info")) {
echo 'You do not have the GD Library installed. This class requires the GD library to function properly.' . "\n";
echo 'visit http://us2.php.net/manual/en/ref.image.php for more information';
exit;
}
//initialize variables
$this->errmsg = '';
$this->error = false;
$this->currentDimensions = array();
$this->newDimensions = array();
$this->fileName = $fileName;
$this->imageMeta = array();
$this->percent = 100;
$this->maxWidth = 0;
$this->maxHeight = 0;
//check to see if file exists
if(!file_exists($this->fileName)) {
$this->errmsg = 'File not found';
$this->error = true;
}
//check to see if file is readable
elseif(!is_readable($this->fileName)) {
$this->errmsg = 'File is not readable';
$this->error = true;
}
//if there are no errors, determine the file format
if($this->error == false) {
//check if gif
if(stristr(strtolower($this->fileName),'.gif')) $this->format = 'GIF';
//check if jpg
elseif(stristr(strtolower($this->fileName),'.jpg') || stristr(strtolower($this->fileName),'.jpeg')) $this->format = 'JPG';
//check if png
elseif(stristr(strtolower($this->fileName),'.png')) $this->format = 'PNG';
//unknown file format
else {
$this->errmsg = 'Unknown file format';
$this->error = true;
}
}
//initialize resources if no errors
if($this->error == false) {
switch($this->format) {
case 'GIF':
$this->oldImage = ImageCreateFromGif($this->fileName);
break;
case 'JPG':
$this->oldImage = ImageCreateFromJpeg($this->fileName);
break;
case 'PNG':
$this->oldImage = ImageCreateFromPng($this->fileName);
break;
}
$size = GetImageSize($this->fileName);
$this->currentDimensions = array('width'=>$size[0],'height'=>$size[1]);
$this->newImage = $this->oldImage;
$this->gatherImageMeta();
}
if($this->error == true) {
$this->showErrorImage();
break;
}
}
/**
* Class destructor
*
*/
public function __destruct() {
if(is_resource($this->newImage)) @ImageDestroy($this->newImage);
if(is_resource($this->oldImage)) @ImageDestroy($this->oldImage);
if(is_resource($this->workingImage)) @ImageDestroy($this->workingImage);
}
/**
* Returns the current width of the image
*
* @return int
*/
private function getCurrentWidth() {
return $this->currentDimensions['width'];
}
/**
* Returns the current height of the image
*
* @return int
*/
private function getCurrentHeight() {
return $this->currentDimensions['height'];
}
/**
* Calculates new image width
*
* @param int $width
* @param int $height
* @return array
*/
private function calcWidth($width,$height) {
$newWp = (100 * $this->maxWidth) / $width;
$newHeight = ($height * $newWp) / 100;
return array('newWidth'=>intval($this->maxWidth),'newHeight'=>intval($newHeight));
}
/**
* Calculates new image height
*
* @param int $width
* @param int $height
* @return array
*/
private function calcHeight($width,$height) {
$newHp = (100 * $this->maxHeight) / $height;
$newWidth = ($width * $newHp) / 100;
return array('newWidth'=>intval($newWidth),'newHeight'=>intval($this->maxHeight));
}
/**
* Calculates new image size based on percentage
*
* @param int $width
* @param int $height
* @return array
*/
private function calcPercent($width,$height) {
$newWidth = ($width * $this->percent) / 100;
$newHeight = ($height * $this->percent) / 100;
return array('newWidth'=>intval($newWidth),'newHeight'=>intval($newHeight));
}
/**
* Calculates new image size based on width and height, while constraining to maxWidth and maxHeight
*
* @param int $width
* @param int $height
*/
private function calcImageSize($width,$height) {
$newSize = array('newWidth'=>$width,'newHeight'=>$height);
if($this->maxWidth > 0) {
$newSize = $this->calcWidth($width,$height);
if($this->maxHeight > 0 && $newSize['newHeight'] > $this->maxHeight) {
$newSize = $this->calcHeight($newSize['newWidth'],$newSize['newHeight']);
}
//$this->newDimensions = $newSize;
}
if($this->maxHeight > 0) {
$newSize = $this->calcHeight($width,$height);
if($this->maxWidth > 0 && $newSize['newWidth'] > $this->maxWidth) {
$newSize = $this->calcWidth($newSize['newWidth'],$newSize['newHeight']);
}
//$this->newDimensions = $newSize;
}
$this->newDimensions = $newSize;
}
/**
* Calculates new image size based percentage
*
* @param int $width
* @param int $height
*/
private function calcImageSizePercent($width,$height) {
if($this->percent > 0) {
$this->newDimensions = $this->calcPercent($width,$height);
}
}
/**
* Displays error image
*
*/
private function showErrorImage() {
header('Content-type: image/png');
$errImg = ImageCreate(220,25);
$bgColor = imagecolorallocate($errImg,0,0,0);
$fgColor1 = imagecolorallocate($errImg,255,255,255);
$fgColor2 = imagecolorallocate($errImg,255,0,0);
imagestring($errImg,3,6,6,'Error:',$fgColor2);
imagestring($errImg,3,55,6,$this->errmsg,$fgColor1);
imagepng($errImg);
imagedestroy($errImg);
}
/**
* Resizes image to maxWidth x maxHeight
*
* @param int $maxWidth
* @param int $maxHeight
*/
public function resize($maxWidth = 0, $maxHeight = 0) {
$this->maxWidth = $maxWidth;
$this->maxHeight = $maxHeight;
$this->calcImageSize($this->currentDimensions['width'],$this->currentDimensions['height']);
if(function_exists("ImageCreateTrueColor")) {
$this->workingImage = ImageCreateTrueColor($this->newDimensions['newWidth'],$this->newDimensions['newHeight']);
}
else {
$this->workingImage = ImageCreate($this->newDimensions['newWidth'],$this->newDimensions['newHeight']);
}
ImageCopyResampled(
$this->workingImage,
$this->oldImage,
0,
0,
0,
0,
$this->newDimensions['newWidth'],
$this->newDimensions['newHeight'],
$this->currentDimensions['width'],
$this->currentDimensions['height']
);
$this->oldImage = $this->workingImage;
$this->newImage = $this->workingImage;
$this->currentDimensions['width'] = $this->newDimensions['newWidth'];
$this->currentDimensions['height'] = $this->newDimensions['newHeight'];
}
/**
* Resizes the image by $percent percent
*
* @param int $percent
*/
public function resizePercent($percent = 0) {
$this->percent = $percent;
$this->calcImageSizePercent($this->currentDimensions['width'],$this->currentDimensions['height']);
if(function_exists("ImageCreateTrueColor")) {
$this->workingImage = ImageCreateTrueColor($this->newDimensions['newWidth'],$this->newDimensions['newHeight']);
}
else {
$this->workingImage = ImageCreate($this->newDimensions['newWidth'],$this->newDimensions['newHeight']);
}
ImageCopyResampled(
$this->workingImage,
$this->oldImage,
0,
0,
0,
0,
$this->newDimensions['newWidth'],
$this->newDimensions['newHeight'],
$this->currentDimensions['width'],
$this->currentDimensions['height']
);
$this->oldImage = $this->workingImage;
$this->newImage = $this->workingImage;
$this->currentDimensions['width'] = $this->newDimensions['newWidth'];
$this->currentDimensions['height'] = $this->newDimensions['newHeight'];
}
/**
* Crops the image from calculated center in a square of $cropSize pixels
*
* @param int $cropSize
*/
public function cropFromCenter($cropSize) {
if($cropSize > $this->currentDimensions['width']) $cropSize = $this->currentDimensions['width'];
if($cropSize > $this->currentDimensions['height']) $cropSize = $this->currentDimensions['height'];
$cropX = intval(($this->currentDimensions['width'] - $cropSize) / 2);
$cropY = intval(($this->currentDimensions['height'] - $cropSize) / 2);
if(function_exists("ImageCreateTrueColor")) {
$this->workingImage = ImageCreateTrueColor($cropSize,$cropSize);
}
else {
$this->workingImage = ImageCreate($cropSize,$cropSize);
}
imagecopyresampled(
$this->workingImage,
$this->oldImage,
0,
0,
$cropX,
$cropY,
$cropSize,
$cropSize,
$cropSize,
$cropSize
);
$this->oldImage = $this->workingImage;
$this->newImage = $this->workingImage;
$this->currentDimensions['width'] = $cropSize;
$this->currentDimensions['height'] = $cropSize;
}
/**
* Advanced cropping function that crops an image using $startX and $startY as the upper-left hand corner.
*
* @param int $startX
* @param int $startY
* @param int $width
* @param int $height
*/
public function crop($startX,$startY,$width,$height) {
//make sure the cropped area is not greater than the size of the image
if($width > $this->currentDimensions['width']) $width = $this->currentDimensions['width'];
if($height > $this->currentDimensions['height']) $height = $this->currentDimensions['height'];
//make sure not starting outside the image
if(($startX + $width) > $this->currentDimensions['width']) $startX = ($this->currentDimensions['width'] - $width);
if(($startY + $height) > $this->currentDimensions['height']) $startY = ($this->currentDimensions['height'] - $height);
if($startX < 0) $startX = 0;
if($startY < 0) $startY = 0;
if(function_exists("ImageCreateTrueColor")) {
$this->workingImage = ImageCreateTrueColor($width,$height);
}
else {
$this->workingImage = ImageCreate($width,$height);
}
imagecopyresampled(
$this->workingImage,
$this->oldImage,
0,
0,
$startX,
$startY,
$width,
$height,
$width,
$height
);
$this->oldImage = $this->workingImage;
$this->newImage = $this->workingImage;
$this->currentDimensions['width'] = $width;
$this->currentDimensions['height'] = $height;
}
/**
* Outputs the image to the screen, or saves to $name if supplied. Quality of JPEG images can be controlled with the $quality variable
*
* @param int $quality
* @param string $name
*/
public function show($quality=100,$name = '') {
switch($this->format) {
case 'GIF':
if($name != '') {
ImageGif($this->newImage,$name);
}
else {
header('Content-type: image/gif');
ImageGif($this->newImage);
}
break;
case 'JPG':
if($name != '') {
ImageJpeg($this->newImage,$name,$quality);
}
else {
header('Content-type: image/jpeg');
ImageJpeg($this->newImage,'',$quality);
}
break;
case 'PNG':
if($name != '') {
ImagePng($this->newImage,$name);
}
else {
header('Content-type: image/png');
ImagePng($this->newImage);
}
break;
}
}
/**
* Saves image as $name (can include file path), with quality of # percent if file is a jpeg
*
* @param string $name
* @param int $quality
*/
public function save($name,$quality=100) {
$this->show($quality,$name);
}
/**
* Creates Apple-style reflection under image, optionally adding a border to main image
*
* @param int $percent
* @param int $reflection
* @param int $white
* @param bool $border
* @param string $borderColor
*/
public function createReflection($percent,$reflection,$white,$border = true,$borderColor = '#a4a4a4') {
$width = $this->currentDimensions['width'];
$height = $this->currentDimensions['height'];
$reflectionHeight = intval($height * ($reflection / 100));
$newHeight = $height + $reflectionHeight;
$reflectedPart = $height * ($percent / 100);
$this->workingImage = ImageCreateTrueColor($width,$newHeight);
ImageAlphaBlending($this->workingImage,true);
$colorToPaint = ImageColorAllocateAlpha($this->workingImage,255,255,255,0);
ImageFilledRectangle($this->workingImage,0,0,$width,$newHeight,$colorToPaint);
imagecopyresampled(
$this->workingImage,
$this->newImage,
0,
0,
0,
$reflectedPart,
$width,
$reflectionHeight,
$width,
($height - $reflectedPart));
$this->imageFlipVertical();
imagecopy($this->workingImage,$this->newImage,0,0,0,0,$width,$height);
imagealphablending($this->workingImage,true);
for($i=0;$i<$reflectionHeight;$i++) {
$colorToPaint = imagecolorallocatealpha($this->workingImage,255,255,255,($i/$reflectionHeight*-1+1)*$white);
imagefilledrectangle($this->workingImage,0,$height+$i,$width,$height+$i,$colorToPaint);
}
if($border == true) {
$rgb = $this->hex2rgb($borderColor,false);
$colorToPaint = imagecolorallocate($this->workingImage,$rgb[0],$rgb[1],$rgb[2]);
imageline($this->workingImage,0,0,$width,0,$colorToPaint); //top line
imageline($this->workingImage,0,$height,$width,$height,$colorToPaint); //bottom line
imageline($this->workingImage,0,0,0,$height,$colorToPaint); //left line
imageline($this->workingImage,$width-1,0,$width-1,$height,$colorToPaint); //right line
}
$this->oldImage = $this->workingImage;
$this->newImage = $this->workingImage;
$this->currentDimensions['width'] = $width;
$this->currentDimensions['height'] = $newHeight;
}
/**
* Inverts working image, used by reflection function
*
*/
private function imageFlipVertical() {
$x_i = imagesx($this->workingImage);
$y_i = imagesy($this->workingImage);
for($x = 0; $x < $x_i; $x++) {
for($y = 0; $y < $y_i; $y++) {
imagecopy($this->workingImage,$this->workingImage,$x,$y_i - $y - 1, $x, $y, 1, 1);
}
}
}
/**
* Converts hexidecimal color value to rgb values and returns as array/string
*
* @param string $hex
* @param bool $asString
* @return array|string
*/
private function hex2rgb($hex, $asString = false) {
// strip off any leading #
if (0 === strpos($hex, '#')) {
$hex = substr($hex, 1);
} else if (0 === strpos($hex, '&H')) {
$hex = substr($hex, 2);
}
// break into hex 3-tuple
$cutpoint = ceil(strlen($hex) / 2)-1;
$rgb = explode(':', wordwrap($hex, $cutpoint, ':', $cutpoint), 3);
// convert each tuple to decimal
$rgb[0] = (isset($rgb[0]) ? hexdec($rgb[0]) : 0);
$rgb[1] = (isset($rgb[1]) ? hexdec($rgb[1]) : 0);
$rgb[2] = (isset($rgb[2]) ? hexdec($rgb[2]) : 0);
return ($asString ? "{$rgb[0]} {$rgb[1]} {$rgb[2]}" : $rgb);
}
/**
* Reads selected exif meta data from jpg images and populates $this->imageMeta with appropriate values if found
*
*/
private function gatherImageMeta() {
//only attempt to retrieve info if exif exists
if(function_exists("exif_read_data") && $this->format == 'JPG') {
$imageData = exif_read_data($this->fileName);
if(isset($imageData['Make']))
$this->imageMeta['make'] = ucwords(strtolower($imageData['Make']));
if(isset($imageData['Model']))
$this->imageMeta['model'] = $imageData['Model'];
if(isset($imageData['COMPUTED']['ApertureFNumber'])) {
$this->imageMeta['aperture'] = $imageData['COMPUTED']['ApertureFNumber'];
$this->imageMeta['aperture'] = str_replace('/','',$this->imageMeta['aperture']);
}
if(isset($imageData['ExposureTime'])) {
$exposure = explode('/',$imageData['ExposureTime']);
$exposure = round($exposure[1]/$exposure[0],-1);
$this->imageMeta['exposure'] = '1/' . $exposure . ' second';
}
if(isset($imageData['Flash'])) {
if($imageData['Flash'] > 0) {
$this->imageMeta['flash'] = 'Yes';
}
else {
$this->imageMeta['flash'] = 'No';
}
}
if(isset($imageData['FocalLength'])) {
$focus = explode('/',$imageData['FocalLength']);
$this->imageMeta['focalLength'] = round($focus[0]/$focus[1],2) . ' mm';
}
if(isset($imageData['DateTime'])) {
$date = $imageData['DateTime'];
$date = explode(' ',$date);
$date = str_replace(':','-',$date[0]) . ' ' . $date[1];
$this->imageMeta['dateTaken'] = date('m/d/Y g:i A',strtotime($date));
}
}
}
/**
* Rotates image either 90 degrees clockwise or counter-clockwise
*
* @param string $direction
*/
public function rotateImage($direction = 'CW') {
if($direction == 'CW') {
$this->workingImage = imagerotate($this->workingImage,-90,0);
}
else {
$this->workingImage = imagerotate($this->workingImage,90,0);
}
$newWidth = $this->currentDimensions['height'];
$newHeight = $this->currentDimensions['width'];
$this->oldImage = $this->workingImage;
$this->newImage = $this->workingImage;
$this->currentDimensions['width'] = $newWidth;
$this->currentDimensions['height'] = $newHeight;
}
}
?>
|
0admin
|
trunk/plugin/ThumbnailPlugin.php
|
PHP
|
oos
| 21,158
|
<?php
class Utils {
// Dada una fecha en php la retorna con formato mysql
public static function getDateForDB($fecha) {
if ($fecha == "")
return "";
$numeros = explode("-",$fecha);
return trim($numeros[2])."-".trim($numeros[1])."-".trim($numeros[0]);
}
public static function getDateForView($fecha) {
if ($fecha == "")
return "";
$numeros = explode("-",$fecha);
return trim($numeros[2])."-".trim($numeros[1])."-".trim($numeros[0]);
}
public static function removeBlanks($texto) {
return str_replace(' ','',$texto);
}
}
?>
|
0admin
|
trunk/plugin/UtilsPlugin.php
|
PHP
|
oos
| 587
|
<?php
include_once('plugin/LoginPlugin.php');
// Valida que exista el usuario
if (!LoginPlugin::isLogged()) {
include_once('coreapi/SmartyManager.php');
$smarty = SmartyManager::getSmarty();
$smarty->display('login.tpl');
}
|
0admin
|
trunk/include/validsession.php
|
PHP
|
oos
| 237
|
<?php
// Include
include_once('plugin/SmartyPlugin.php');
include_once('plugin/LoginPlugin.php');
include_once('plugin/AppConfigPlugin.php');
include_once('plugin/SecurityAccessPlugin.php');
include_once('plugin/CommonPlugin.php');
// Para establecer locale en espanol (evita problemas como el formateo de la fecha de Smarty)
setlocale (LC_TIME,"spanish");
// Chequea si el usuario ya esta logueado
if (!LoginPlugin::isLogged()) {
header( 'Location: index.php' );
exit;
}
// Current script
$currentScript = AppConfigPlugin::getCurrentScript();
//error_reporting(0);
$currentUrl = AppConfigPlugin::curPageURL();
// Ejecucion
$username = LoginPlugin::getUsername();
$rol = LoginPlugin::getRol();
$clubRol = LoginPlugin::getClub();
$menuItems = AppConfigPlugin::getMenuItems($rol);
$manageItems = AppConfigPlugin::getManageItems();
$appInfo = AppConfigPlugin::getAppInfo();
$iconsImg = AppConfigPlugin::getIconsImg();
// Mensaje
$message = CommonPlugin::getMessage();
CommonPlugin::setMessage("");
// Creacion de Smarty
$smarty = SmartyPlugin::getSmarty();
$smarty->assign('menuItems', $menuItems);
$smarty->assign('manageItems', $manageItems);
$smarty->assign('appInfo', $appInfo);
$smarty->assign('iconsImg', $iconsImg);
$smarty->assign('username', $username);
$smarty->assign('rol', $rol);
$smarty->assign('message', $message);
// Sons
$sons = AppConfigPlugin::getSons(basename($_SERVER['PHP_SELF']));
$smarty->assign('sons', $sons);
$smarty->assign('currentScript', $currentScript);
$menuItems = AppConfigPlugin::getMenuItems(null);
if (!SecurityAccessPlugin::hasAccess($menuItems, $currentUrl, $manageItems, $rol)) {
$smarty->display('noaccess.tpl');
exit();
}
|
0admin
|
trunk/include/header.php
|
PHP
|
oos
| 1,744
|
<?php
require_once('include/header.php');
require_once('dao/FactoryDAO.php');
require_once('plugin/UtilsPlugin.php');
require_once('vo/ContenidoVO.php');
require_once('search/ContenidoSearchCriteria.php');
class ContenidoLogic {
var $_POST;
var $contenidoDAO;
function ContenidoLogic($post){
$this->$_POST = $post;
$this->contenidoDAO = FactoryDAO::getDao('ContenidoDAO');
}
function save($post) {
$vo = new ContenidoVO();
$vo->setId($post['id']);
$vo->setTitulo($post['titulo']);
$vo->setTexto($post['texto']);
$vo->setDescripcion($post['descripcion']);
$vo->setImagen($post['imagen']);
$vo->setBorrado($post['borrado']);
if ( isset($post['id']) && $post['id'] != "" ) {
return $this->contenidoDAO->update($vo);
}
else{
return $this->contenidoDAO->insert($vo);
}
}
function delete($id) {
return $this->contenidoDAO->delete($id);
}
function get($id) {
return $this->contenidoDAO->get($id);
}
function find($contenidoSearchCriteria) {
return $this->contenidoDAO->find($contenidoSearchCriteria);
}
function count($contenidoSearchCriteria) {
return $this->contenidoDAO->count($contenidoSearchCriteria);
}
}//end class
|
0admin
|
trunk/logic/ContenidoLogic.php
|
PHP
|
oos
| 1,234
|
<?php
require_once('include/header.php');
require_once('plugin/UtilsPlugin.php');
require_once('dao/FactoryDAO.php');
require_once('vo/ImagenesVO.php');
require_once('search/ImagenesSearchCriteria.php');
/**
* Business logic directly reflects the use cases. The business logic deals with VOs,
* modifies them according to the business requirements and uses DAOs to access the persistence layer.
* The business logic classes should provide means to retrieve information about errors that occurred.
*
* @author dintech
*
*/
Class ImagenesLogic {
var $_POST;
var $ImagenesDAO;
var $noticiaDAO;
/**
* Constructor
* @param POST array $_POST
*/
function ImagenesLogic($post){
$this->$_POST = $post;
$this->ImagenesDAO = FactoryDAO::getDao('ImagenesDAO');
// *** Reemplazar por el DAO de la tabla que se quiera instanciar ***
$this->noticiasDAO = FactoryDAO::getDao('NoticiasDAO');
}
/**
* Guarda una imagen en la DB y
* copia la imagen (y su thumbnail) al directorio /images/$_POST[t]
* @param POST array $_POST
* @param FILES array $files
*/
function save($post, $files){
// Genero el nombre del archivo = <idauto>_<nroimagen>.<extension>
require_once 'plugin/FileUtilityPlugin.php';
$extension = FileUtilityPlugin::getExtension($files['imgfile']['name']);
// Genero nuevo nombre unico para la imagen
srand(time());
$randomCode = rand(1,10000);
$newFileName = $post['iditem'] . '_' . $randomCode . "." . $extension;
$imagesVO = new ImagenesVO();
$imagesVO->setAlt($post['alt']);
$imagesVO->setDate(Utils::getDateForDB(date("d-m-Y")));
$imagesVO->setDescription($post['descripcion']);
$imagesVO->setFilename($newFileName);
$imagesVO->setHeight($post['height']);
$imagesVO->setId(null);
$imagesVO->setIditem($post['iditem']);
$imagesVO->setOrder($post['order']);
$imagesVO->setSize($files['imgfile']['size']);
$imagesVO->setTable($post['t']);
$imagesVO->setWidth($post['width']);
$result = $this->ImagenesDAO->save($imagesVO);
// obtengo ID de la imagen recien agregada
$newImageId = $this->ImagenesDAO->getLastInsertId();
// *** Reemplazar por el DAO de la tabla que se quiera instanciar ***
// incremento el imagecount de la noticia
$imageSearchCriteria = new ImagenesSearchCriteria();
$imageSearchCriteria->setIditem($post['iditem']);
$imageSearchCriteria->setTable($post['t']);
$images = $this->find($imageSearchCriteria);
$this->ImagenesDAO->updateImageinfo($post['t'], $post['iditem'], (count($images) == 1) ? $newImageId : null, 1);
if ($result != "error"){
$error = false;
// genero nombre de path y thumbnailPath
$path = "images/".$post['t']."/". $newFileName;
$thumbnailPath = "images/".$post['t']."/small/". $newFileName;
// copia archivo al server
if(move_uploaded_file($files['imgfile']['tmp_name'], $path)) {
;
} else{
$error = true;
}
copy($files['uploadedfile']['tmp_name'], $path);
// genera thumbnail y lo copia en el path /small
require_once 'plugin/ThumbnailPlugin.php';
$thumb = new Thumbnail($path);
$thumb->resize(960);
$thumb->save($path, 100);
$thumb = new Thumbnail($path);
$thumb->resize(250);
$thumb->save($thumbnailPath, 100);
if ($error)
return "error";
else
return "ok";
}
else
return $result;
return;
}
/**
* Actualiza la informacion de una imagen (descripcion y default - en un futuro)
* @param POST array $post
*/
function update($post){
$imagesVO = new ImagenesVO();
$imagesVO->setDescription($post['descripcion']);
$imagesVO->setId($post['id']);
$result = $this->ImagenesDAO->save($imagesVO);
if ($post['defaultimage'] == 1)
$this->ImagenesDAO->updateImageinfo($post['t'], $post['iditem'], $post['id'], 0);
return $result;
}
/**
* Elimina una imagen de la DB y tambien fisicamente el archivo
* de la imagen y su thumbnail
* @param POST array $post
*/
function delete($post){
// chequear si imagesid (FK) es igual a la que se quiere eliminar
$noticia = $this->noticiasDAO->get($post['iditem']);
$newImageId = null;
$replaceImageId = false;
if ($noticia[imagesid] == $post[id] && $noticia[imagecount] > 1) {
$replaceImageId = true;
// obtener otra imagen para seleccionar como la nueva imagesid (FK)
$imageSearchCriteria = new ImagenesSearchCriteria();
$imageSearchCriteria->setIditem($post['iditem']);
$images = $this->find($imageSearchCriteria);
foreach ($images as $image) {
if ($image[id] != $post[id]) {
$newImageId = $image[id];
break;
}
}
}
// elimino fisicamente la imagen y su thumbnail
$imagen = $this->ImagenesDAO->get($post[id]);
$path = "images/".$imagen[tablename]."/". $imagen[filename];
$thumbnailPath = "images/".$imagen[tablename]."/small/". $imagen[filename];
unlink($path);
unlink($thumbnailPath);
// *** Reemplazar por el DAO de la tabla que se quiera instanciar ***
// decremento en uno el imagecount de iditem
$this->ImagenesDAO->updateImageinfo($post['t'], $post['iditem'], ($replaceImageId) ? $newImageId : null, -1);
// elimino la imagen de la DB
return $this->ImagenesDAO->delete($post[id]);
}
/**
* Devuelve una imagen a partir de su ID
* @param ID $id
*/
function get($id){
return $this->ImagenesDAO->get($id);
}
/**
* Retorna todas las imagen que hagan matching
* con el criterio definido en $imageSearchCriterio
* @param ImageSearchCriteria $imageSearchCriteria
*/
function find($imageSearchCriteria){
return $this->ImagenesDAO->find($imageSearchCriteria);
}
/**
* Retorna la cantidad de imagenes que hacen matching
* con el criterio definido en $imageSearchCriteria
* @param ImageSearchCriteria $imageSearchCriteria
*/
function count($imageSearchCriteria){
return $this->ImagenesDAO->count($imageSearchCriteria);
}
/**
* Retorna la entidad (cualquier tabla que use el modulo de imagenes)
* @return Entidad
*/
function getEntidad($table, $iditem) {
return $this->ImagenesDAO->getEntidad($table, $iditem);
}
}
?>
|
0admin
|
trunk/logic/ImagenesLogic.php
|
PHP
|
oos
| 6,348
|
<?php
require_once('include/header.php');
require_once('dao/FactoryDAO.php');
require_once('plugin/UtilsPlugin.php');
require_once('vo/ClientesVO.php');
require_once('search/ClientesSearchCriteria.php');
class ClientesLogic {
var $_POST;
var $clientesDAO;
function ClientesLogic($post){
$this->$_POST = $post;
$this->clientesDAO = FactoryDAO::getDao('ClientesDAO');
}
function save($post) {
$vo = new ClientesVO();
$vo->setId($post['id']);
$vo->setNombre($post['nombre']);
$vo->setMail($post['mail']);
$vo->setTelefono($post['telefono']);
$vo->setCiudad($post['ciudad']);
$vo->setActive($post['active']);
$vo->setFecha($post['fecha']);
$vo->setBorrado($post['borrado']);
if ( isset($post['id']) && $post['id'] != "" ) {
return $this->clientesDAO->update($vo);
}
else{
return $this->clientesDAO->insert($vo);
}
}
function delete($id) {
return $this->clientesDAO->delete($id);
}
function get($id) {
return $this->clientesDAO->get($id);
}
function find($clientesSearchCriteria) {
return $this->clientesDAO->find($clientesSearchCriteria);
}
function count($clientesSearchCriteria) {
return $this->clientesDAO->count($clientesSearchCriteria);
}
}//end class
|
0admin
|
trunk/logic/ClientesLogic.php
|
PHP
|
oos
| 1,274
|
<?php
require_once('include/header.php');
require_once('dao/FactoryDAO.php');
require_once('plugin/UtilsPlugin.php');
require_once('vo/NoticiasVO.php');
require_once('search/NoticiasSearchCriteria.php');
class NoticiasLogic {
var $_POST;
var $noticiasDAO;
function NoticiasLogic($post){
$this->$_POST = $post;
$this->noticiasDAO = FactoryDAO::getDao('NoticiasDAO');
}
function save($post) {
$vo = new NoticiasVO();
$vo->setId($post['id']);
$vo->setTitulo($post['titulo']);
$vo->setTags($post['tags']);
$vo->setResumen($post['resumen']);
$vo->setContenido($post['contenido']);
$vo->setFecha(Utils::getDateForDB($post['fecha']));
$vo->setCategoria($post['categoria']);
$vo->setSeccion($post['seccion']);
$vo->setOrden($post['orden']);
$vo->setVisitas($post['visitas']);
$vo->setActivo($post['activo']);
$vo->setBorrado($post['borrado']);
if ( isset($post['id']) && $post['id'] != "" ) {
return $this->noticiasDAO->update($vo);
}
else{
return $this->noticiasDAO->insert($vo);
}
}
function delete($id) {
return $this->noticiasDAO->delete($id);
}
function get($id) {
return $this->noticiasDAO->get($id);
}
function find($noticiasSearchCriteria) {
return $this->noticiasDAO->find($noticiasSearchCriteria);
}
function count($noticiasSearchCriteria) {
return $this->noticiasDAO->count($noticiasSearchCriteria);
}
function activar($id) {
return $this->noticiasDAO->activar($id);
}
function desactivar($id) {
return $this->noticiasDAO->desactivar($id);
}
}//end class
?>
|
0admin
|
trunk/logic/NoticiasLogic.php
|
PHP
|
oos
| 1,614
|
<?php
require_once('include/header.php');
require_once('dao/FactoryDAO.php');
require_once('plugin/UtilsPlugin.php');
require_once('vo/ContactoVO.php');
require_once('search/ContactoSearchCriteria.php');
class ContactoLogic {
var $_POST;
var $contactoDAO;
function ContactoLogic($post){
$this->$_POST = $post;
$this->contactoDAO = FactoryDAO::getDao('ContactoDAO');
}
function save($post) {
$vo = new ContactoVO();
$vo->setId($post['id']);
$vo->setEmpresa($post['empresa']);
$vo->setNombre($post['nombre']);
$vo->setDireccion($post['direccion']);
$vo->setTelefono($post['telefono']);
$vo->setCelular($post['celular']);
$vo->setMail($post['mail']);
$vo->setWeb($post['web']);
$vo->setBorrado($post['borrado']);
if ( isset($post['id']) && $post['id'] != "" ) {
return $this->contactoDAO->update($vo);
}
else{
return $this->contactoDAO->insert($vo);
}
}
function delete($id) {
return $this->contactoDAO->delete($id);
}
function get($id) {
return $this->contactoDAO->get($id);
}
function find($contactoSearchCriteria) {
return $this->contactoDAO->find($contactoSearchCriteria);
}
function count($contactoSearchCriteria) {
return $this->contactoDAO->count($contactoSearchCriteria);
}
}//end class
|
0admin
|
trunk/logic/ContactoLogic.php
|
PHP
|
oos
| 1,320
|
<?php
require_once('include/header.php');
require_once('dao/FactoryDAO.php');
require_once('vo/UsuarioVO.php');
require_once('search/UsuarioSearchCriteria.php');
/**
* Business logic directly reflects the use cases. The business logic deals with VOs,
* modifies them according to the business requirements and uses DAOs to access the persistence layer.
* The business logic classes should provide means to retrieve information about errors that occurred.
*
* @author dintech
*
*/
Class UsuariosLogic {
var $_POST;
var $usuarioDAO;
function UsuariosLogic($post){
$this->$_POST = $post;
$this->usuarioDAO = FactoryDAO::getDao('UsuarioDAO');
}
function save($post){
$usuarioVO = new UsuarioVO();
$usuarioVO->setId($post['id']);
$usuarioVO->setUsername($post['username']);
$passw = $post['passw'];
// solo setear passw si existe (ej. agregar nuevo usuario)
if (($passw != null) && ($passw != ""))
$usuarioVO->setPassw(md5($post['passw']));
$usuarioVO->setRol($post['rol'].'_'.$post['club']);
if ( isset($$post['id']) && $post['id'] != "" )
return $this->usuarioDAO->update($usuarioVO);
else
return $this->usuarioDAO->save($usuarioVO);
}
function delete($id){
return $this->usuarioDAO->delete($id);
}
function get($id){
return $this->usuarioDAO->get($id);
}
function getByUsername($username){
return $this->usuarioDAO->getByUsername($username);
}
function find($usuarioSearchCriteria){
return $this->usuarioDAO->find($usuarioSearchCriteria);
}
function count($usuarioSearchCriteria){
return $this->usuarioDAO->count($usuarioSearchCriteria);
}
function changePassword($username, $_POST) {
$usuarioDAO = $this->usuarioDAO->getByUsername($username);
if ($usuarioDAO[passw] == md5($_POST['password'])) {
$usuarioVO = new UsuarioVO();
$usuarioVO->setId($usuarioDAO[id]);
$usuarioVO->setUsername($usuarioDAO[username]);
$usuarioVO->setPassw(md5($_POST['newpassword']));
$usuarioVO->setRol($usuarioDAO[rol]);
return $this->usuarioDAO->save($usuarioVO);
}
else
return "passw_not_match";
}
}
?>
|
0admin
|
trunk/logic/UsuariosLogic.php
|
PHP
|
oos
| 2,187
|
<?php
require_once('include/header.php');
require_once('dao/FactoryDAO.php');
require_once('plugin/UtilsPlugin.php');
require_once('vo/AvisosVO.php');
require_once('search/AvisosSearchCriteria.php');
class AvisosLogic {
var $_POST;
var $avisosDAO;
function AvisosLogic($post){
$this->$_POST = $post;
$this->avisosDAO = FactoryDAO::getDao('AvisosDAO');
}
function save($post) {
$vo = new AvisosVO();
$vo->setId($post['id']);
$vo->setFechatexto($post['fechatexto']);
$vo->setFecha(Utils::getDateForDB($post['fecha']));
$vo->setDescripcion($post['descripcion']);
if ( isset($post['id']) && $post['id'] != "" ) {
return $this->avisosDAO->update($vo);
}
else{
return $this->avisosDAO->insert($vo);
}
}
function delete($id) {
return $this->avisosDAO->delete($id);
}
function get($id) {
return $this->avisosDAO->get($id);
}
function find($avisosSearchCriteria) {
return $this->avisosDAO->find($avisosSearchCriteria);
}
function count($avisosSearchCriteria) {
return $this->avisosDAO->count($avisosSearchCriteria);
}
}//end class
|
0admin
|
trunk/logic/AvisosLogic.php
|
PHP
|
oos
| 1,133
|
<?php
require_once('include/header.php');
require_once('vo/ContactoVO.php');
require_once('search/ContactoSearchCriteria.php');
require_once('logic/ContactoLogic.php');
require('conf/configuration.php');
$logic = new ContactoLogic($_POST);
// Ordenamiento
if($_GET[order] == "asc")
$order= "desc";
else if($_GET[order] == "desc")
$order= "asc";
else
$order= "desc";
if (!isset($_GET["orderby"]))
$orderby = "Id";
else
$orderby = $_GET["orderby"];
$smarty->assign("orderby", $orderby);
$smarty->assign("order", $order);
// Seteo el searchcriteria para mostrar la tabla con todos los resultados segun el filtro. (sin paginacion)
$contactoSearchCriteria = new ContactoSearchCriteria();
$contactoSearchCriteria->setOrderby($orderby);
$contactoSearchCriteria->setOrder($order);
//$contactoSearchCriteria->setSearch($_GET["search"]);
$contactoSearchCriteria->setInicio(1);
$contactoSearchCriteria->setFin(null);
// Controller
$action = $_GET["action"];
if ($action == null){
$action = $_POST["action"];
}
switch ($action){
case "save":
$result = $logic->save($_POST);
if ($result == "error")
$smarty->assign("error", "Ha ocurrido un error al guardar los cambios del Registro de Contacto");
else
$smarty->assign("message", "El Registro de Contactoha sido actualizado");
break;
case "add":
$smarty->assign("detailPage","contactoForm.tpl");
$smarty->display("admin_generic.tpl");
exit;break;
case "update":
$id = $_GET["id"];
if ($id != null){
$contacto = $logic->get($id);
$smarty->assign("contacto", $contacto);
}
$smarty->assign("detailPage","contactoForm.tpl");
$smarty->display("admin_generic.tpl");
exit;break;
case "detail":
$id = $_GET["id"];
if ($id != null){
$contacto = $logic->get($id);
$smarty->assign("contacto", $contacto);
}
$smarty->assign("detailPage","contactoDetail.tpl");
$smarty->display("admin_generic.tpl");
exit;
break;
case "delete":
$result = $logic->delete($_POST["id"]);
if ($result == "error")
$smarty->assign("error", "Ha ocurrido un error al eliminar el Registro de ");
else
$smarty->assign("message", "Se ha eliminado el Registro de ");
break;
}
// Paginador
$cantidad = $logic->count($contactoSearchCriteria);
$totalItemsPerPage=10;
if (isset($_GET["entradas"]))
$totalItemsPerPage=$_GET["entradas"];
$totalPages = ceil($cantidad / $totalItemsPerPage);
$smarty->assign("totalPages", $totalPages);
$smarty->assign("totalItemsPerPage", $totalItemsPerPage);
$page = $_GET[page];
if (!$page) {
$start = 0;
$page = 1;
$smarty->assign("page", $page);
}
else
$start = ($page - 1) * $totalItemsPerPage;
$smarty->assign("page", $page);
// Obtengo solo los registros de la pagina actual.
$contactoSearchCriteria->setInicio($start);
$contactoSearchCriteria->setOrderby($orderby);
$contactoSearchCriteria->setOrder($order);
$contactoSearchCriteria->setFin($totalItemsPerPage);
$contacto = $logic->find($contactoSearchCriteria);
$smarty->assign("allParams", CommonPlugin::getParamsAsString($_GET));
$smarty->assign("cantidad", $cantidad);
$contacto = $logic->get(1);
$smarty->assign("contacto", $contacto);
$smarty->assign("detailPage", "contactoForm.tpl");
$smarty->display("admin_generic.tpl");
?>
|
0admin
|
trunk/contacto.php
|
PHP
|
oos
| 3,357
|
<?php
/**
* When a page is called, the page controller is run before any output is made.
* The controller's job is to transform the HTTP request into business objects,
* then call the approriate logic and prepare the objects used to display the response.
*
* The page logic performs the following steps:
* 1. The cmd request parameter is evaluated.
* 2. Based on the action other request parameters are evaluated.
* 3. Value Objects (or a form object for more complex tasks) are created from the parameters.
* 4. The objects are validated and the result is stored in an error array.
* 5. The business logic is called with the Value Objects.
* 6. Return status (error codes) from the business logic is evaluated.
* 7. A redirect to another page is executed if necessary.
* 8. All data needed to display the page is collected and made available to the page as variables of the controller. Do not use global variables.
*
* * @author dintech
*
*/
require_once('include/header.php');
require_once('plugin/CommonPlugin.php');
require_once('logic/UsuariosLogic.php');
require('conf/configuration.php');
$logic = new UsuariosLogic($_POST);
$action = $_GET['action'];
if ($action == null){
$action = $_POST['action'];
}
switch ($action){
case "changepassword":
if ($_POST['sendform']=="1"){
// TODO Diego, esta logica esta bien aca? o debe ir en el Logic?
// Chequea passwords
if ($_POST['newpassword'] != $_POST['repeatnewpassword']) {
$smarty->assign('error', "Error: La nueva contraseña debe coincidir");
break;
}
if (trim($_POST['newpassword']) == "") {
$smarty->assign('error', "Error: La nueva contraseña no puede estar vacia");
break;
}
$username = LoginPlugin::getUsername();
$result = $logic->changePassword($username, $_POST);
if ($result == "passw_not_match") {
$smarty->assign('error', "Error: La contraseña no coincide con la actual");
break;
} else {
$smarty->assign('message', "Su nueva contraseña ha sido guardada correctamente");
break;
}
//$result = $logic->save($_POST);
//$success = UsersDBPlugin::changePassword($username, $_POST[actualpassword], $_POST[newpassword]);
//echo $username;
}
break;
}
$smarty->display('myaccount.tpl');
?>
|
0admin
|
trunk/myaccount.php
|
PHP
|
oos
| 2,398
|
<?php
// Include
include_once('plugin/LoginPlugin.php');
include_once('plugin/SmartyPlugin.php');
include_once('plugin/AppConfigPlugin.php');
include_once('plugin/CommonPlugin.php');
// Ejecutar la accion
if (isset($_GET[action])) {
require_once($_GET[action].".php");
}
// Chequea si el usuario ya esta logueado
if (LoginPlugin::isLogged()) {
header( 'Location: contenido.php' );
exit;
}
// Ejecucion
$smarty = SmartyPlugin::getSmarty();
$appInfo = AppConfigPlugin::getAppInfo();
$message = CommonPlugin::getMessage();
CommonPlugin::setMessage("");
// Smarty call
$smarty->assign('message', $message);
$smarty->assign('appInfo', $appInfo);
$smarty->display('admin_login.tpl');
|
0admin
|
trunk/index.php
|
PHP
|
oos
| 719
|
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];
}
}
}
|
061304011116lyj-lyj
|
src/com/hlidskialf/android/hardware/ShakeListener.java
|
Java
|
asf20
| 2,826
|
/***
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()!");
}
}
|
061304011116lyj-lyj
|
src/com/commonsware/cwac/sacklist/SackOfViewsAdapter.java
|
Java
|
asf20
| 4,702
|
/***
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();
}
}
}
|
061304011116lyj-lyj
|
src/com/commonsware/cwac/merge/MergeAdapter.java
|
Java
|
asf20
| 8,691
|
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.List;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.hardware.SensorManager;
import android.util.Log;
import android.widget.RemoteViews;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.service.TwitterService;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.util.TextHelper;
import com.ch_linghu.fanfoudroid.R;
public class FanfouWidgetSmall extends AppWidgetProvider {
public final String TAG = "FanfouWidgetSmall";
public final String NEXTACTION = "com.ch_linghu.fanfoudroid.FanfouWidgetSmall.NEXT";
public final String PREACTION = "com.ch_linghu.fanfoudroid.FanfouWidgetSmall.PREV";
private static List<Tweet> tweets;
private SensorManager sensorManager;
private static int position = 0;
class CacheCallback implements ImageLoaderCallback {
private RemoteViews updateViews;
CacheCallback(RemoteViews updateViews) {
this.updateViews = updateViews;
}
@Override
public void refresh(String url, Bitmap bitmap) {
// updateViews.setImageViewBitmap(R.id.small_status_image, bitmap);
}
}
@Override
public void onUpdate(Context context, AppWidgetManager appwidgetmanager,
int[] appWidgetIds) {
Log.d(TAG, "onUpdate");
TwitterService.setWidgetStatus(true);
// if (!isRunning(context, WidgetService.class.getName())) {
// Intent i = new Intent(context, WidgetService.class);
// context.startService(i);
// }
update(context);
}
private void update(Context context) {
fetchMessages();
position = 0;
refreshView(context, NEXTACTION);
}
private TwitterDatabase getDb() {
return TwitterApplication.mDb;
}
public String getUserId() {
return TwitterApplication.getMyselfId(false);
}
private void fetchMessages() {
if (tweets == null) {
tweets = new ArrayList<Tweet>();
} else {
tweets.clear();
}
Cursor cursor = getDb().fetchAllTweets(getUserId(),
StatusTable.TYPE_HOME);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Tweet tweet = StatusTable.parseCursor(cursor);
tweets.add(tweet);
} while (cursor.moveToNext());
}
}
Log.d(TAG, "Tweets size " + tweets.size());
}
private void refreshView(Context context) {
ComponentName fanfouWidget = new ComponentName(context,
FanfouWidgetSmall.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(fanfouWidget, buildLogin(context));
}
private RemoteViews buildLogin(Context context) {
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_small_initial_layout);
// updateViews.setTextViewText(R.id.small_status_text,
// TextHelper.getSimpleTweetText("请登录"));
// updateViews.setTextViewText(R.id.small_status_screen_name, "");
// updateViews.setTextViewText(R.id.small_tweet_source, "");
// updateViews.setTextViewText(R.id.small_tweet_created_at, "");
return updateViews;
}
private void refreshView(Context context, String action) {
// 某些情况下,tweets会为null
if (tweets == null) {
fetchMessages();
}
// 防止引发IndexOutOfBoundsException
if (tweets.size() != 0) {
if (action.equals(NEXTACTION)) {
--position;
} else if (action.equals(PREACTION)) {
++position;
}
// Log.d(TAG, "Tweets size =" + tweets.size());
if (position >= tweets.size() || position < 0) {
position = 0;
}
// Log.d(TAG, "position=" + position);
ComponentName fanfouWidget = new ComponentName(context,
FanfouWidgetSmall.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(fanfouWidget, buildUpdate(context));
}
}
public RemoteViews buildUpdate(Context context) {
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_small_initial_layout);
Tweet t = tweets.get(position);
Log.d(TAG, "tweet=" + t);
// updateViews.setTextViewText(R.id.small_status_screen_name, t.screenName);
// updateViews.setTextViewText(R.id.small_status_text,
// TextHelper.getSimpleTweetText(t.text));
//
// updateViews.setTextViewText(R.id.small_tweet_source,
// context.getString(R.string.tweet_source_prefix) + t.source);
// updateViews.setTextViewText(R.id.small_tweet_created_at,
// DateTimeHelper.getRelativeDate(t.createdAt));
//
// updateViews.setImageViewBitmap(R.id.small_status_image,
// TwitterApplication.mImageLoader.get(t.profileImageUrl,
// new CacheCallback(updateViews)));
// Intent inext = new Intent(context, FanfouWidgetSmall.class);
// inext.setAction(NEXTACTION);
// PendingIntent pinext = PendingIntent.getBroadcast(context, 0, inext,
// PendingIntent.FLAG_UPDATE_CURRENT);
// updateViews.setOnClickPendingIntent(R.id.small_btn_next, pinext);
// Intent ipre = new Intent(context, FanfouWidgetSmall.class);
// ipre.setAction(PREACTION);
// PendingIntent pipre = PendingIntent.getBroadcast(context, 0, ipre,
// PendingIntent.FLAG_UPDATE_CURRENT);
// updateViews.setOnClickPendingIntent(R.id.small_btn_pre, pipre);
Intent write = WriteActivity.createNewTweetIntent("");
PendingIntent piwrite = PendingIntent.getActivity(context, 0, write,
PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.small_write_message, piwrite);
Intent home = TwitterActivity.createIntent(context);
PendingIntent pihome = PendingIntent.getActivity(context, 0, home,
PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.small_logo_image, pihome);
Intent status = StatusActivity.createIntent(t);
PendingIntent pistatus = PendingIntent.getActivity(context, 0, status,
PendingIntent.FLAG_UPDATE_CURRENT);
// updateViews.setOnClickPendingIntent(R.id.small_main_body, pistatus);
return updateViews;
}
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "OnReceive");
// FIXME: NullPointerException
Log.i(TAG, context.getApplicationContext().toString());
if (!TwitterApplication.mApi.isLoggedIn()) {
refreshView(context);
} else {
super.onReceive(context, intent);
String action = intent.getAction();
if (NEXTACTION.equals(action) || PREACTION.equals(action)) {
refreshView(context, intent.getAction());
} else if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
update(context);
}
}
}
/**
*
* @param c
* @param serviceName
* @return
*/
@Deprecated
public boolean isRunning(Context c, String serviceName) {
ActivityManager myAM = (ActivityManager) c
.getSystemService(Context.ACTIVITY_SERVICE);
ArrayList<RunningServiceInfo> runningServices = (ArrayList<RunningServiceInfo>) myAM
.getRunningServices(40);
// 获取最多40个当前正在运行的服务,放进ArrList里,以现在手机的处理能力,要是超过40个服务,估计已经卡死,所以不用考虑超过40个该怎么办
int servicesSize = runningServices.size();
for (int i = 0; i < servicesSize; i++)// 循环枚举对比
{
if (runningServices.get(i).service.getClassName().toString()
.equals(serviceName)) {
return true;
}
}
return false;
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
Log.d(TAG, "onDeleted");
}
@Override
public void onEnabled(Context context) {
Log.d(TAG, "onEnabled");
TwitterService.setWidgetStatus(true);
}
@Override
public void onDisabled(Context context) {
Log.d(TAG, "onDisabled");
TwitterService.setWidgetStatus(false);
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/FanfouWidgetSmall.java
|
Java
|
asf20
| 8,339
|
package com.ch_linghu.fanfoudroid;
import java.text.MessageFormat;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.db.UserInfoTable;
import com.ch_linghu.fanfoudroid.fanfou.User;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.R;
/**
*
* @author Dino 2011-02-26
*/
// public class ProfileActivity extends WithHeaderActivity {
public class ProfileActivity extends BaseActivity {
private static final String TAG = "ProfileActivity";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.PROFILE";
private static final String STATUS_COUNT = "status_count";
private static final String EXTRA_USER = "user";
private static final String FANFOUROOT = "http://fanfou.com/";
private static final String USER_ID = "userid";
private static final String USER_NAME = "userName";
private GenericTask profileInfoTask;// 获取用户信息
private GenericTask setFollowingTask;
private GenericTask cancelFollowingTask;
private String userId;
private String userName;
private String myself;
private User profileInfo;// 用户信息
private ImageView profileImageView;// 头像
private TextView profileName;// 名称
private TextView profileScreenName;// 昵称
private TextView userLocation;// 地址
private TextView userUrl;// url
private TextView userInfo;// 自述
private TextView friendsCount;// 好友
private TextView followersCount;// 收听
private TextView statusCount;// 消息
private TextView favouritesCount;// 收藏
private TextView isFollowingText;// 是否关注
private Button followingBtn;// 收听/取消关注按钮
private Button sendMentionBtn;// 发送留言按钮
private Button sendDmBtn;// 发送私信按钮
private ProgressDialog dialog; // 请稍候
private RelativeLayout friendsLayout;
private LinearLayout followersLayout;
private LinearLayout statusesLayout;
private LinearLayout favouritesLayout;
private NavBar mNavBar;
private Feedback mFeedback;
private TwitterDatabase db;
public static Intent createIntent(String userId) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.putExtra(USER_ID, userId);
return intent;
}
private ImageLoaderCallback callback = new ImageLoaderCallback() {
@Override
public void refresh(String url, Bitmap bitmap) {
profileImageView.setImageBitmap(bitmap);
}
};
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "OnCreate start");
if (super._onCreate(savedInstanceState)) {
setContentView(R.layout.profile);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
myself = TwitterApplication.getMyselfId(false);
if (extras != null) {
this.userId = extras.getString(USER_ID);
this.userName = extras.getString(USER_NAME);
} else {
this.userId = myself;
this.userName = TwitterApplication.getMyselfName(false);
}
Uri data = intent.getData();
if (data != null) {
userId = data.getLastPathSegment();
}
// 初始化控件
initControls();
Log.d(TAG, "the userid is " + userId);
db = this.getDb();
draw();
return true;
} else {
return false;
}
}
private void initControls() {
mNavBar = new NavBar(NavBar.HEADER_STYLE_HOME, this);
mNavBar.setHeaderTitle("");
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
sendMentionBtn = (Button) findViewById(R.id.sendmetion_btn);
sendDmBtn = (Button) findViewById(R.id.senddm_btn);
profileImageView = (ImageView) findViewById(R.id.profileimage);
profileName = (TextView) findViewById(R.id.profilename);
profileScreenName = (TextView) findViewById(R.id.profilescreenname);
userLocation = (TextView) findViewById(R.id.user_location);
userUrl = (TextView) findViewById(R.id.user_url);
userInfo = (TextView) findViewById(R.id.tweet_user_info);
friendsCount = (TextView) findViewById(R.id.friends_count);
followersCount = (TextView) findViewById(R.id.followers_count);
TextView friendsCountTitle = (TextView) findViewById(R.id.friends_count_title);
TextView followersCountTitle = (TextView) findViewById(R.id.followers_count_title);
String who;
if (userId.equals(myself)) {
who = "我";
} else {
who = "ta";
}
friendsCountTitle.setText(MessageFormat.format(
getString(R.string.profile_friends_count_title), who));
followersCountTitle.setText(MessageFormat.format(
getString(R.string.profile_followers_count_title), who));
statusCount = (TextView) findViewById(R.id.statuses_count);
favouritesCount = (TextView) findViewById(R.id.favourites_count);
friendsLayout = (RelativeLayout) findViewById(R.id.friendsLayout);
followersLayout = (LinearLayout) findViewById(R.id.followersLayout);
statusesLayout = (LinearLayout) findViewById(R.id.statusesLayout);
favouritesLayout = (LinearLayout) findViewById(R.id.favouritesLayout);
isFollowingText = (TextView) findViewById(R.id.isfollowing_text);
followingBtn = (Button) findViewById(R.id.following_btn);
// 为按钮面板添加事件
friendsLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 在没有得到profileInfo时,不允许点击事件生效
if (profileInfo == null) {
return;
}
String showName;
if (!TextUtils.isEmpty(profileInfo.getScreenName())) {
showName = profileInfo.getScreenName();
} else {
showName = profileInfo.getName();
}
Intent intent = FollowingActivity
.createIntent(userId, showName);
intent.setClass(ProfileActivity.this, FollowingActivity.class);
startActivity(intent);
}
});
followersLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 在没有得到profileInfo时,不允许点击事件生效
if (profileInfo == null) {
return;
}
String showName;
if (!TextUtils.isEmpty(profileInfo.getScreenName())) {
showName = profileInfo.getScreenName();
} else {
showName = profileInfo.getName();
}
Intent intent = FollowersActivity
.createIntent(userId, showName);
intent.setClass(ProfileActivity.this, FollowersActivity.class);
startActivity(intent);
}
});
statusesLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 在没有得到profileInfo时,不允许点击事件生效
if (profileInfo == null) {
return;
}
String showName;
if (!TextUtils.isEmpty(profileInfo.getScreenName())) {
showName = profileInfo.getScreenName();
} else {
showName = profileInfo.getName();
}
Intent intent = UserTimelineActivity.createIntent(
profileInfo.getId(), showName);
launchActivity(intent);
}
});
favouritesLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 在没有得到profileInfo时,不允许点击事件生效
if (profileInfo == null) {
return;
}
Intent intent = FavoritesActivity.createIntent(userId,
profileInfo.getName());
intent.setClass(ProfileActivity.this, FavoritesActivity.class);
startActivity(intent);
}
});
// 刷新
View.OnClickListener refreshListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
doGetProfileInfo();
}
};
mNavBar.getRefreshButton().setOnClickListener(refreshListener);
}
private void draw() {
Log.d(TAG, "draw");
bindProfileInfo();
// doGetProfileInfo();
}
@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.");
}
/**
* 从数据库获取,如果数据库不存在则创建
*/
private void bindProfileInfo() {
dialog = ProgressDialog.show(ProfileActivity.this, "请稍候", "正在加载信息...");
if (null != db && db.existsUser(userId)) {
Cursor cursor = db.getUserInfoById(userId);
profileInfo = User.parseUser(cursor);
cursor.close();
if (profileInfo == null) {
Log.w(TAG, "cannot get userinfo from userinfotable the id is"
+ userId);
}
bindControl();
if (dialog != null) {
dialog.dismiss();
}
} else {
doGetProfileInfo();
}
}
private void doGetProfileInfo() {
mFeedback.start("");
if (profileInfoTask != null
&& profileInfoTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
profileInfoTask = new GetProfileTask();
profileInfoTask.setListener(profileInfoTaskListener);
TaskParams params = new TaskParams();
profileInfoTask.execute(params);
}
}
private void bindControl() {
if (profileInfo.getId().equals(myself)) {
sendMentionBtn.setVisibility(View.GONE);
sendDmBtn.setVisibility(View.GONE);
} else {
// 发送留言
sendMentionBtn.setVisibility(View.VISIBLE);
sendMentionBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = WriteActivity.createNewTweetIntent(String
.format("@%s ", profileInfo.getScreenName()));
startActivity(intent);
}
});
// 发送私信
sendDmBtn.setVisibility(View.VISIBLE);
sendDmBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = WriteDmActivity.createIntent(profileInfo
.getId());
startActivity(intent);
}
});
}
if (userId.equals(myself)) {
mNavBar.setHeaderTitle("我"
+ getString(R.string.cmenu_user_profile_prefix));
} else {
mNavBar.setHeaderTitle(profileInfo.getScreenName()
+ getString(R.string.cmenu_user_profile_prefix));
}
profileImageView.setImageBitmap(TwitterApplication.mImageLoader.get(
profileInfo.getProfileImageURL().toString(), callback));
profileName.setText(profileInfo.getId());
profileScreenName.setText(profileInfo.getScreenName());
if (profileInfo.getId().equals(myself)) {
isFollowingText.setText(R.string.profile_isyou);
followingBtn.setVisibility(View.GONE);
} else if (profileInfo.isFollowing()) {
isFollowingText.setText(R.string.profile_isfollowing);
followingBtn.setVisibility(View.VISIBLE);
followingBtn.setText(R.string.user_label_unfollow);
followingBtn.setOnClickListener(cancelFollowingListener);
followingBtn.setCompoundDrawablesWithIntrinsicBounds(getResources()
.getDrawable(R.drawable.ic_unfollow), null, null, null);
} else {
isFollowingText.setText(R.string.profile_notfollowing);
followingBtn.setVisibility(View.VISIBLE);
followingBtn.setText(R.string.user_label_follow);
followingBtn.setOnClickListener(setfollowingListener);
followingBtn.setCompoundDrawablesWithIntrinsicBounds(getResources()
.getDrawable(R.drawable.ic_follow), null, null, null);
}
String location = profileInfo.getLocation();
if (location == null || location.length() == 0) {
location = getResources().getString(R.string.profile_location_null);
}
userLocation.setText(location);
if (profileInfo.getURL() != null) {
userUrl.setText(profileInfo.getURL().toString());
} else {
userUrl.setText(FANFOUROOT + profileInfo.getId());
}
String description = profileInfo.getDescription();
if (description == null || description.length() == 0) {
description = getResources().getString(
R.string.profile_description_null);
}
userInfo.setText(description);
friendsCount.setText(String.valueOf(profileInfo.getFriendsCount()));
followersCount.setText(String.valueOf(profileInfo.getFollowersCount()));
statusCount.setText(String.valueOf(profileInfo.getStatusesCount()));
favouritesCount
.setText(String.valueOf(profileInfo.getFavouritesCount()));
}
private TaskListener profileInfoTaskListener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
// 加载成功
if (result == TaskResult.OK) {
mFeedback.success("");
// 绑定控件
bindControl();
if (dialog != null) {
dialog.dismiss();
}
}
}
@Override
public String getName() {
return "GetProfileInfo";
}
};
/**
* 更新数据库中的用户
*
* @return
*/
private boolean updateUser() {
ContentValues v = new ContentValues();
v.put(BaseColumns._ID, profileInfo.getName());
v.put(UserInfoTable.FIELD_USER_NAME, profileInfo.getName());
v.put(UserInfoTable.FIELD_USER_SCREEN_NAME, profileInfo.getScreenName());
v.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, profileInfo
.getProfileImageURL().toString());
v.put(UserInfoTable.FIELD_LOCALTION, profileInfo.getLocation());
v.put(UserInfoTable.FIELD_DESCRIPTION, profileInfo.getDescription());
v.put(UserInfoTable.FIELD_PROTECTED, profileInfo.isProtected());
v.put(UserInfoTable.FIELD_FOLLOWERS_COUNT,
profileInfo.getFollowersCount());
v.put(UserInfoTable.FIELD_LAST_STATUS, profileInfo.getStatusSource());
v.put(UserInfoTable.FIELD_FRIENDS_COUNT, profileInfo.getFriendsCount());
v.put(UserInfoTable.FIELD_FAVORITES_COUNT,
profileInfo.getFavouritesCount());
v.put(UserInfoTable.FIELD_STATUSES_COUNT,
profileInfo.getStatusesCount());
v.put(UserInfoTable.FIELD_FOLLOWING, profileInfo.isFollowing());
if (profileInfo.getURL() != null) {
v.put(UserInfoTable.FIELD_URL, profileInfo.getURL().toString());
}
return db.updateUser(profileInfo.getId(), v);
}
/**
* 获取用户信息task
*
* @author Dino
*
*/
private class GetProfileTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
Log.v(TAG, "get profile task");
try {
profileInfo = getApi().showUser(userId);
mFeedback.update(80);
if (profileInfo != null) {
if (null != db && !db.existsUser(userId)) {
com.ch_linghu.fanfoudroid.data.User userinfodb = profileInfo
.parseUser();
db.createUserInfo(userinfodb);
} else {
// 更新用户
updateUser();
}
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage());
return TaskResult.FAILED;
}
mFeedback.update(99);
return TaskResult.OK;
}
}
/**
* 设置关注监听
*/
private OnClickListener setfollowingListener = new OnClickListener() {
@Override
public void onClick(View v) {
Builder diaBuilder = new AlertDialog.Builder(ProfileActivity.this)
.setTitle("关注提示").setMessage("确实要添加关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (setFollowingTask != null
&& setFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
setFollowingTask = new SetFollowingTask();
setFollowingTask
.setListener(setFollowingTaskLinstener);
TaskParams params = new TaskParams();
setFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
};
/*
* 取消关注监听
*/
private OnClickListener cancelFollowingListener = new OnClickListener() {
@Override
public void onClick(View v) {
Builder diaBuilder = new AlertDialog.Builder(ProfileActivity.this)
.setTitle("关注提示").setMessage("确实要取消关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (cancelFollowingTask != null
&& cancelFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
cancelFollowingTask = new CancelFollowingTask();
cancelFollowingTask
.setListener(cancelFollowingTaskLinstener);
TaskParams params = new TaskParams();
cancelFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
};
/**
* 设置关注
*
* @author Dino
*
*/
private class SetFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
getApi().createFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener setFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
followingBtn.setText("取消关注");
isFollowingText.setText(getResources().getString(
R.string.profile_isfollowing));
followingBtn.setOnClickListener(cancelFollowingListener);
Toast.makeText(getBaseContext(), "关注成功", Toast.LENGTH_SHORT)
.show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(getBaseContext(), "关注失败", Toast.LENGTH_SHORT)
.show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
/**
* 取消关注
*
* @author Dino
*
*/
private class CancelFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
getApi().destroyFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener cancelFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
followingBtn.setText("添加关注");
isFollowingText.setText(getResources().getString(
R.string.profile_notfollowing));
followingBtn.setOnClickListener(setfollowingListener);
Toast.makeText(getBaseContext(), "取消关注成功", Toast.LENGTH_SHORT)
.show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(getBaseContext(), "取消关注失败", Toast.LENGTH_SHORT)
.show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/ProfileActivity.java
|
Java
|
asf20
| 20,034
|
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.fanfou.Query;
import com.ch_linghu.fanfoudroid.fanfou.QueryResult;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.TwitterListBaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback;
import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter;
import com.ch_linghu.fanfoudroid.ui.module.TweetArrayAdapter;
import com.ch_linghu.fanfoudroid.R;
import com.markupartist.android.widget.PullToRefreshListView;
import com.markupartist.android.widget.PullToRefreshListView.OnRefreshListener;
public class SearchResultActivity extends TwitterListBaseActivity {
private static final String TAG = "SearchActivity";
// Views.
private PullToRefreshListView mTweetList;
private View mListFooter;
private ProgressBar loadMoreGIF;
// State.
private String mSearchQuery;
private ArrayList<Tweet> mTweets;
private TweetArrayAdapter mAdapter;
private int mNextPage = 1;
private String mLastId = null;
private boolean mIsGetMore = false;
private static class State {
State(SearchResultActivity activity) {
mTweets = activity.mTweets;
mNextPage = activity.mNextPage;
mLastId = activity.mLastId;
}
public ArrayList<Tweet> mTweets;
public int mNextPage;
public String mLastId;
}
// Tasks.
private GenericTask mSearchTask;
private TaskListener mSearchTaskListener = new TaskAdapter() {
@Override
public void onPreExecute(GenericTask task) {
if (mIsGetMore){
loadMoreGIF.setVisibility(View.VISIBLE);
}
if (mNextPage == 1) {
updateProgress(getString(R.string.page_status_refreshing));
} else {
updateProgress(getString(R.string.page_status_refreshing));
}
mTweetList.prepareForRefresh();
}
@Override
public void onProgressUpdate(GenericTask task, Object param) {
draw();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
loadMoreGIF.setVisibility(View.GONE);
mTweetList.onRefreshComplete();
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
draw();
if (!mIsGetMore){
mTweetList.setSelection(1);
}
} else {
// Do nothing.
}
updateProgress("");
}
@Override
public String getName() {
return "SearchTask";
}
};
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState)) {
Intent intent = getIntent();
// Assume it's SEARCH.
// String action = intent.getAction();
mSearchQuery = intent.getStringExtra(SearchManager.QUERY);
if (TextUtils.isEmpty(mSearchQuery)) {
mSearchQuery = intent.getData().getLastPathSegment();
}
mNavbar.setHeaderTitle(mSearchQuery);
setTitle(mSearchQuery);
State state = (State) getLastNonConfigurationInstance();
if (state != null) {
mTweets = state.mTweets;
mNextPage = state.mNextPage;
mLastId = state.mLastId;
draw();
} else {
doSearch(false);
}
return true;
} else {
return false;
}
}
@Override
protected int getLayoutId() {
return R.layout.main;
}
@Override
protected void onResume() {
super.onResume();
checkIsLogedIn();
}
@Override
public Object onRetainNonConfigurationInstance() {
return createState();
}
private synchronized State createState() {
return new State(this);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mSearchTask != null
&& mSearchTask.getStatus() == GenericTask.Status.RUNNING) {
mSearchTask.cancel(true);
}
super.onDestroy();
}
// UI helpers.
private void updateProgress(String progress) {
mProgressText.setText(progress);
}
@Override
protected void draw() {
mAdapter.refresh(mTweets);
}
private void doSearch(boolean isGetMore) {
Log.d(TAG, "Attempting search.");
if (mSearchTask != null
&& mSearchTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mIsGetMore = isGetMore;
mSearchTask = new SearchTask();
mSearchTask.setFeedback(mFeedback);
mSearchTask.setListener(mSearchTaskListener);
mSearchTask.execute();
}
}
private class SearchTask extends GenericTask {
ArrayList<Tweet> mTweets = new ArrayList<Tweet>();
@Override
protected TaskResult _doInBackground(TaskParams... params) {
QueryResult result;
try {
Query query = new Query(mSearchQuery);
if (!TextUtils.isEmpty(mLastId)) {
query.setMaxId(mLastId);
}
result = getApi().search(query);// .search(mSearchQuery,
// mNextPage);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
List<com.ch_linghu.fanfoudroid.fanfou.Status> statuses = result
.getStatus();
HashSet<String> imageUrls = new HashSet<String>();
publishProgress(SimpleFeedback.calProgressBySize(40, 20, statuses));
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statuses) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Tweet tweet;
tweet = Tweet.create(status);
mLastId = tweet.id;
mTweets.add(tweet);
imageUrls.add(tweet.profileImageUrl);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
addTweets(mTweets);
// if (isCancelled()) {
// return TaskResult.CANCELLED;
// }
//
// publishProgress();
//
// // TODO: what if orientation change?
// ImageManager imageManager = getImageManager();
// MemoryImageCache imageCache = new MemoryImageCache();
//
// for (String imageUrl : imageUrls) {
// if (!Utils.isEmpty(imageUrl)) {
// // Fetch image to cache.
// try {
// Bitmap bitmap = imageManager.fetchImage(imageUrl);
// imageCache.put(imageUrl, bitmap);
// } catch (IOException e) {
// Log.e(TAG, e.getMessage(), e);
// }
// }
//
// if (isCancelled()) {
// return TaskResult.CANCELLED;
// }
// }
//
// addImages(imageCache);
return TaskResult.OK;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
public void doGetMore() {
if (!isLastPage()) {
doSearch(true);
}
}
public boolean isLastPage() {
return mNextPage == -1;
}
@Override
protected void adapterRefresh() {
mAdapter.refresh(mTweets);
}
private synchronized void addTweets(ArrayList<Tweet> tweets) {
if (tweets.size() == 0) {
mNextPage = -1;
return;
}
mTweets.addAll(tweets);
++mNextPage;
}
@Override
protected String getActivityTitle() {
return mSearchQuery;
}
@Override
protected Tweet getContextItemTweet(int position) {
if (position >= 1 && position <= mAdapter.getCount()) {
Tweet item = (Tweet) mAdapter.getItem(position - 1);
if (item == null) {
return null;
} else {
return item;
}
} else {
return null;
}
}
@Override
protected TweetAdapter getTweetAdapter() {
return mAdapter;
}
@Override
protected ListView getTweetList() {
return mTweetList;
}
@Override
protected void updateTweet(Tweet tweet) {
// TODO Simple and stupid implementation
for (Tweet t : mTweets) {
if (t.id.equals(tweet.id)) {
t.favorited = tweet.favorited;
break;
}
}
}
@Override
protected boolean useBasicMenu() {
return true;
}
@Override
protected void setupState() {
mTweets = new ArrayList<Tweet>();
mTweetList = (PullToRefreshListView) findViewById(R.id.tweet_list);
mAdapter = new TweetArrayAdapter(this);
mTweetList.setAdapter(mAdapter);
mTweetList.setOnRefreshListener(new OnRefreshListener(){
@Override
public void onRefresh(){
doRetrieve();
}
});
// Add Footer to ListView
mListFooter = View.inflate(this, R.layout.listview_footer, null);
mTweetList.addFooterView(mListFooter, null, true);
loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar);
}
@Override
public void doRetrieve() {
doSearch(false);
}
@Override
protected void specialItemClicked(int position) {
// 注意 mTweetAdapter.getCount 和 mTweetList.getCount的区别
// 前者仅包含数据的数量(不包括foot和head),后者包含foot和head
// 因此在同时存在foot和head的情况下,list.count = adapter.count + 2
if (position == 0) {
doRetrieve();
} else if (position == mTweetList.getCount() - 1) {
// 最后一个Item(footer)
doGetMore();
}
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/SearchResultActivity.java
|
Java
|
asf20
| 9,651
|
package com.ch_linghu.fanfoudroid.service;
public interface IService {
void startService();
void stopService();
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/service/IService.java
|
Java
|
asf20
| 118
|
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid.service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* This broadcast receiver is awoken after boot and registers the service that
* checks for new tweets.
*/
public class BootReceiver extends BroadcastReceiver {
private static final String TAG = "BootReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Twitta BootReceiver is receiving.");
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
TwitterService.schedule(context);
}
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/service/BootReceiver.java
|
Java
|
asf20
| 1,225
|
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid.service;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import com.ch_linghu.fanfoudroid.DmActivity;
import com.ch_linghu.fanfoudroid.FanfouWidget;
import com.ch_linghu.fanfoudroid.FanfouWidgetSmall;
import com.ch_linghu.fanfoudroid.MentionActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Dm;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.fanfou.Weibo;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class TwitterService extends Service {
private static final String TAG = "TwitterService";
private NotificationManager mNotificationManager;
private ArrayList<Tweet> mNewTweets;
private ArrayList<Tweet> mNewMentions;
private ArrayList<Dm> mNewDms;
private GenericTask mRetrieveTask;
public String getUserId() {
return TwitterApplication.getMyselfId(false);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// fetchMessages();
// handler.postDelayed(mTask, 10000);
Log.d(TAG, "Start Once");
return super.onStartCommand(intent, flags, startId);
}
private TaskListener mRetrieveTaskListener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
SharedPreferences preferences = TwitterApplication.mPref;
boolean needCheck = preferences.getBoolean(
Preferences.CHECK_UPDATES_KEY, false);
boolean timeline_only = preferences.getBoolean(
Preferences.TIMELINE_ONLY_KEY, false);
boolean replies_only = preferences.getBoolean(
Preferences.REPLIES_ONLY_KEY, true);
boolean dm_only = preferences.getBoolean(
Preferences.DM_ONLY_KEY, true);
if (needCheck) {
if (timeline_only) {
processNewTweets();
}
if (replies_only) {
processNewMentions();
}
if (dm_only) {
processNewDms();
}
}
}
// 原widget
try {
Intent intent = new Intent(TwitterService.this,
FanfouWidget.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
PendingIntent pi = PendingIntent.getBroadcast(
TwitterService.this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
pi.send();
} catch (CanceledException e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
// 小widget
// try {
// Intent intent = new Intent(TwitterService.this,
// FanfouWidgetSmall.class);
// intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
// PendingIntent pi = PendingIntent.getBroadcast(
// TwitterService.this, 0, intent,
// PendingIntent.FLAG_UPDATE_CURRENT);
// pi.send();
// } catch (CanceledException e) {
// Log.e(TAG, e.getMessage());
// e.printStackTrace();
// }
stopSelf();
}
@Override
public String getName() {
return "ServiceRetrieveTask";
}
};
private WakeLock mWakeLock;
@Override
public IBinder onBind(Intent intent) {
return null;
}
private TwitterDatabase getDb() {
return TwitterApplication.mDb;
}
private Weibo getApi() {
return TwitterApplication.mApi;
}
@Override
public void onCreate() {
Log.v(TAG, "Server Created");
super.onCreate();
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
mWakeLock.acquire();
boolean needCheck = TwitterApplication.mPref.getBoolean(
Preferences.CHECK_UPDATES_KEY, false);
boolean widgetIsEnabled = TwitterService.widgetIsEnabled;
Log.v(TAG, "Check Updates is " + needCheck + "/wg:" + widgetIsEnabled);
if (!needCheck && !widgetIsEnabled) {
Log.d(TAG, "Check update preference is false.");
stopSelf();
return;
}
if (!getApi().isLoggedIn()) {
Log.d(TAG, "Not logged in.");
stopSelf();
return;
}
schedule(TwitterService.this);
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNewTweets = new ArrayList<Tweet>();
mNewMentions = new ArrayList<Tweet>();
mNewDms = new ArrayList<Dm>();
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mRetrieveTask = new RetrieveTask();
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.execute((TaskParams[]) null);
}
}
private void processNewTweets() {
int count = mNewTweets.size();
if (count <= 0) {
return;
}
Tweet latestTweet = mNewTweets.get(0);
String title;
String text;
if (count == 1) {
title = latestTweet.screenName;
text = TextHelper.getSimpleTweetText(latestTweet.text);
} else {
title = getString(R.string.service_new_twitter_updates);
text = getString(R.string.service_x_new_tweets);
text = MessageFormat.format(text, count);
}
PendingIntent intent = PendingIntent.getActivity(this, 0,
TwitterActivity.createIntent(this), 0);
notify(intent, TWEET_NOTIFICATION_ID, R.drawable.notify_tweet,
TextHelper.getSimpleTweetText(latestTweet.text), title, text);
}
private void processNewMentions() {
int count = mNewMentions.size();
if (count <= 0) {
return;
}
Tweet latestTweet = mNewMentions.get(0);
String title;
String text;
if (count == 1) {
title = latestTweet.screenName;
text = TextHelper.getSimpleTweetText(latestTweet.text);
} else {
title = getString(R.string.service_new_mention_updates);
text = getString(R.string.service_x_new_mentions);
text = MessageFormat.format(text, count);
}
PendingIntent intent = PendingIntent.getActivity(this, 0,
MentionActivity.createIntent(this), 0);
notify(intent, MENTION_NOTIFICATION_ID, R.drawable.notify_mention,
TextHelper.getSimpleTweetText(latestTweet.text), title, text);
}
private static int TWEET_NOTIFICATION_ID = 0;
private static int DM_NOTIFICATION_ID = 1;
private static int MENTION_NOTIFICATION_ID = 2;
private void notify(PendingIntent intent, int notificationId,
int notifyIconId, String tickerText, String title, String text) {
Notification notification = new Notification(notifyIconId, tickerText,
System.currentTimeMillis());
notification.setLatestEventInfo(this, title, text, intent);
notification.flags = Notification.FLAG_AUTO_CANCEL
| Notification.FLAG_ONLY_ALERT_ONCE
| Notification.FLAG_SHOW_LIGHTS;
notification.ledARGB = 0xFF84E4FA;
notification.ledOnMS = 5000;
notification.ledOffMS = 5000;
String ringtoneUri = TwitterApplication.mPref.getString(
Preferences.RINGTONE_KEY, null);
if (ringtoneUri == null) {
notification.defaults |= Notification.DEFAULT_SOUND;
} else {
notification.sound = Uri.parse(ringtoneUri);
}
if (TwitterApplication.mPref.getBoolean(Preferences.VIBRATE_KEY, false)) {
notification.defaults |= Notification.DEFAULT_VIBRATE;
}
mNotificationManager.notify(notificationId, notification);
}
private void processNewDms() {
int count = mNewDms.size();
if (count <= 0) {
return;
}
Dm latest = mNewDms.get(0);
String title;
String text;
if (count == 1) {
title = latest.screenName;
text = TextHelper.getSimpleTweetText(latest.text);
} else {
title = getString(R.string.service_new_direct_message_updates);
text = getString(R.string.service_x_new_direct_messages);
text = MessageFormat.format(text, count);
}
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
DmActivity.createIntent(), 0);
notify(pendingIntent, DM_NOTIFICATION_ID, R.drawable.notify_dm,
TextHelper.getSimpleTweetText(latest.text), title, text);
}
@Override
public void onDestroy() {
Log.d(TAG, "Service Destroy.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
mRetrieveTask.cancel(true);
}
mWakeLock.release();
super.onDestroy();
}
public static void schedule(Context context) {
SharedPreferences preferences = TwitterApplication.mPref;
boolean needCheck = preferences.getBoolean(
Preferences.CHECK_UPDATES_KEY, false);
boolean widgetIsEnabled = TwitterService.widgetIsEnabled;
if (!needCheck && !widgetIsEnabled) {
Log.d(TAG, "Check update preference is false.");
return;
}
String intervalPref = preferences
.getString(
Preferences.CHECK_UPDATE_INTERVAL_KEY,
context.getString(R.string.pref_check_updates_interval_default));
int interval = Integer.parseInt(intervalPref);
// interval = 1; //for debug
Intent intent = new Intent(context, TwitterService.class);
PendingIntent pending = PendingIntent.getService(context, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
Calendar c = new GregorianCalendar();
c.add(Calendar.MINUTE, interval);
DateFormat df = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
Log.d(TAG, "Schedule, next run at " + df.format(c.getTime()));
AlarmManager alarm = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pending);
if (needCheck) {
alarm.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pending);
} else {
// only for widget
alarm.set(AlarmManager.RTC, c.getTimeInMillis(), pending);
}
}
public static void unschedule(Context context) {
Intent intent = new Intent(context, TwitterService.class);
PendingIntent pending = PendingIntent.getService(context, 0, intent, 0);
AlarmManager alarm = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Log.d(TAG, "Cancelling alarms.");
alarm.cancel(pending);
}
private static boolean widgetIsEnabled = false;
public static void setWidgetStatus(boolean isEnabled) {
widgetIsEnabled = isEnabled;
}
public static boolean isWidgetEnabled() {
return widgetIsEnabled;
}
private class RetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
SharedPreferences preferences = TwitterApplication.mPref;
boolean timeline_only = preferences.getBoolean(
Preferences.TIMELINE_ONLY_KEY, false);
boolean replies_only = preferences.getBoolean(
Preferences.REPLIES_ONLY_KEY, true);
boolean dm_only = preferences.getBoolean(Preferences.DM_ONLY_KEY,
true);
Log.d(TAG, "Widget Is Enabled? " + TwitterService.widgetIsEnabled);
if (timeline_only || TwitterService.widgetIsEnabled) {
String maxId = getDb()
.fetchMaxTweetId(TwitterApplication.getMyselfId(false),
StatusTable.TYPE_HOME);
Log.d(TAG, "Max id is:" + maxId);
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
try {
if (maxId != null) {
statusList = getApi().getFriendsTimeline(
new Paging(maxId));
} else {
statusList = getApi().getFriendsTimeline();
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Tweet tweet;
tweet = Tweet.create(status);
mNewTweets.add(tweet);
Log.d(TAG, mNewTweets.size() + " new tweets.");
int count = getDb().addNewTweetsAndCountUnread(mNewTweets,
TwitterApplication.getMyselfId(false),
StatusTable.TYPE_HOME);
if (count <= 0) {
return TaskResult.FAILED;
}
}
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
if (replies_only) {
String maxMentionId = getDb().fetchMaxTweetId(
TwitterApplication.getMyselfId(false),
StatusTable.TYPE_MENTION);
Log.d(TAG, "Max mention id is:" + maxMentionId);
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
try {
if (maxMentionId != null) {
statusList = getApi().getMentions(
new Paging(maxMentionId));
} else {
statusList = getApi().getMentions();
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
int unReadMentionsCount = 0;
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Tweet tweet = Tweet.create(status);
mNewMentions.add(tweet);
unReadMentionsCount = getDb().addNewTweetsAndCountUnread(
mNewMentions, TwitterApplication.getMyselfId(false),
StatusTable.TYPE_MENTION);
if (unReadMentionsCount <= 0) {
return TaskResult.FAILED;
}
}
Log.v(TAG, "Got mentions " + unReadMentionsCount + "/"
+ mNewMentions.size());
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
if (dm_only) {
String maxId = getDb().fetchMaxDmId(false);
Log.d(TAG, "Max DM id is:" + maxId);
List<com.ch_linghu.fanfoudroid.fanfou.DirectMessage> dmList;
try {
if (maxId != null) {
dmList = getApi().getDirectMessages(new Paging(maxId));
} else {
dmList = getApi().getDirectMessages();
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
for (com.ch_linghu.fanfoudroid.fanfou.DirectMessage directMessage : dmList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Dm dm;
dm = Dm.create(directMessage, false);
mNewDms.add(dm);
Log.d(TAG, mNewDms.size() + " new DMs.");
int count = 0;
TwitterDatabase db = getDb();
if (db.fetchDmCount() > 0) {
count = db.addNewDmsAndCountUnread(mNewDms);
} else {
Log.d(TAG, "No existing DMs. Don't notify.");
db.addDms(mNewDms, false);
}
if (count <= 0) {
return TaskResult.FAILED;
}
}
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
return TaskResult.OK;
}
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/service/TwitterService.java
|
Java
|
asf20
| 16,138
|
package com.ch_linghu.fanfoudroid.service;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;
import com.ch_linghu.fanfoudroid.FanfouWidget;
import com.ch_linghu.fanfoudroid.FanfouWidgetSmall;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
public class WidgetService extends Service {
protected static final String TAG = "WidgetService";
private int position = 0;
private List<Tweet> tweets;
private TwitterDatabase getDb() {
return TwitterApplication.mDb;
}
public String getUserId() {
return TwitterApplication.getMyselfId(false);
}
private void fetchMessages() {
if (tweets == null) {
tweets = new ArrayList<Tweet>();
} else {
tweets.clear();
}
Cursor cursor = getDb().fetchAllTweets(getUserId(),
StatusTable.TYPE_HOME);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Tweet tweet = StatusTable.parseCursor(cursor);
tweets.add(tweet);
} while (cursor.moveToNext());
}
}
}
public RemoteViews buildUpdate(Context context) {
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_initial_layout);
updateViews
.setTextViewText(R.id.status_text, tweets.get(position).text);
// updateViews.setOnClickPendingIntent(viewId, pendingIntent)
position++;
return updateViews;
}
private Handler handler = new Handler();
private Runnable mTask = new Runnable() {
@Override
public void run() {
Log.d(TAG, "tweets size=" + tweets.size() + " position="
+ position);
if (position >= tweets.size()) {
position = 0;
}
ComponentName fanfouWidget = new ComponentName(WidgetService.this,
FanfouWidget.class);
AppWidgetManager manager = AppWidgetManager
.getInstance(getBaseContext());
manager.updateAppWidget(fanfouWidget,
buildUpdate(WidgetService.this));
handler.postDelayed(mTask, 10000);
ComponentName fanfouWidgetSmall = new ComponentName(
WidgetService.this, FanfouWidgetSmall.class);
AppWidgetManager manager2 = AppWidgetManager
.getInstance(getBaseContext());
manager2.updateAppWidget(fanfouWidgetSmall,
buildUpdate(WidgetService.this));
handler.postDelayed(mTask, 10000);
}
};
public static void schedule(Context context) {
SharedPreferences preferences = TwitterApplication.mPref;
if (!preferences.getBoolean(Preferences.CHECK_UPDATES_KEY, false)) {
Log.d(TAG, "Check update preference is false.");
return;
}
String intervalPref = preferences
.getString(
Preferences.CHECK_UPDATE_INTERVAL_KEY,
context.getString(R.string.pref_check_updates_interval_default));
int interval = Integer.parseInt(intervalPref);
Intent intent = new Intent(context, WidgetService.class);
PendingIntent pending = PendingIntent.getService(context, 0, intent, 0);
Calendar c = new GregorianCalendar();
c.add(Calendar.MINUTE, interval);
DateFormat df = new SimpleDateFormat("h:mm a");
Log.d(TAG, "Scheduling alarm at " + df.format(c.getTime()));
AlarmManager alarm = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pending);
alarm.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pending);
}
/**
* @see android.app.Service#onBind(Intent)
*/
@Override
public IBinder onBind(Intent intent) {
// TODO Put your code here
return null;
}
/**
* @see android.app.Service#onCreate()
*/
@Override
public void onCreate() {
Log.d(TAG, "WidgetService onCreate");
schedule(WidgetService.this);
}
/**
* @see android.app.Service#onStart(Intent,int)
*/
@Override
public void onStart(Intent intent, int startId) {
Log.d(TAG, "WidgetService onStart");
fetchMessages();
handler.removeCallbacks(mTask);
handler.postDelayed(mTask, 10000);
}
@Override
public void onDestroy() {
Log.d(TAG, "WidgetService Stop ");
handler.removeCallbacks(mTask);// 当服务结束时,删除线程
super.onDestroy();
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/service/WidgetService.java
|
Java
|
asf20
| 4,879
|
package com.ch_linghu.fanfoudroid.service;
import java.util.List;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
/**
* Location Service
*
* AndroidManifest.xml <code>
* <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
* </code>
*
* TODO: 使用DDMS对模拟器GPS位置进行更新时, 会造成死机现象
*
*/
public class LocationService implements IService {
private static final String TAG = "LocationService";
private LocationManager mLocationManager;
private LocationListener mLocationListener = new MyLocationListener();
private String mLocationProvider;
private boolean running = false;
public LocationService(Context context) {
initLocationManager(context);
}
private void initLocationManager(Context context) {
// Acquire a reference to the system Location Manager
mLocationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
mLocationProvider = mLocationManager.getBestProvider(new Criteria(),
false);
}
public void startService() {
if (!running) {
Log.v(TAG, "START LOCATION SERVICE, PROVIDER:" + mLocationProvider);
running = true;
mLocationManager.requestLocationUpdates(mLocationProvider, 0, 0,
mLocationListener);
}
}
public void stopService() {
if (running) {
Log.v(TAG, "STOP LOCATION SERVICE");
running = false;
mLocationManager.removeUpdates(mLocationListener);
}
}
/**
* @return the last known location for the provider, or null
*/
public Location getLastKnownLocation() {
return mLocationManager.getLastKnownLocation(mLocationProvider);
}
private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.v(TAG, "LOCATION CHANGED TO: " + location.toString());
}
@Override
public void onProviderDisabled(String provider) {
Log.v(TAG, "PROVIDER DISABLED " + provider);
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
Log.v(TAG, "PROVIDER ENABLED " + provider);
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
Log.v(TAG, "STATUS CHANGED: " + provider + " " + status);
}
}
// Only for debug
public void logAllProviders() {
// List all providers:
List<String> providers = mLocationManager.getAllProviders();
Log.v(TAG, "LIST ALL PROVIDERS:");
for (String provider : providers) {
boolean isEnabled = mLocationManager.isProviderEnabled(provider);
Log.v(TAG, "Provider " + provider + ": " + isEnabled);
}
}
// only for debug
public static LocationService test(Context context) {
LocationService ls = new LocationService(context);
ls.startService();
ls.logAllProviders();
Location local = ls.getLastKnownLocation();
if (local != null) {
Log.v("LDS", ls.getLastKnownLocation().toString());
}
return ls;
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/service/LocationService.java
|
Java
|
asf20
| 3,207
|
package com.ch_linghu.fanfoudroid;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Intent;
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;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.R;
public class AboutActivity extends Activity {
//反馈信息
private String versionName = null;
private String deviceModel = null;
private String versionRelease = null;
private String feedback = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
deviceModel=android.os.Build.MODEL;
versionRelease=android.os.Build.VERSION.RELEASE;
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);
String versionString;
if (TwitterApplication.DEBUG){
version.setText(String.format("v %d(nightly)", pinfo.versionCode));
versionName = String.format("%d", pinfo.versionCode);
}else{
version.setText(String.format("v %s", pinfo.versionName));
versionName = pinfo.versionName;
}
// bind button click event
Button okBtn = (Button) findViewById(R.id.ok_btn);
okBtn.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
feedback = "@令狐虫 @三日坊主 @内存地址 @PhoenixG @忽然兔 "+"#安能饭否#"+" "+versionName+"/"+deviceModel+"/"+versionRelease+" ";
Button feedbackBtn = (Button) findViewById(R.id.feedback_btn);
feedbackBtn.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = WriteActivity.createNewTweetIntent(feedback);
startActivity(intent);
}
});
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/AboutActivity.java
|
Java
|
asf20
| 2,485
|
package com.ch_linghu.fanfoudroid.data;
import com.ch_linghu.fanfoudroid.fanfou.DirectMessage;
import com.ch_linghu.fanfoudroid.fanfou.User;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class Dm extends Message {
@SuppressWarnings("unused")
private static final String TAG = "Dm";
public boolean isSent;
public static Dm create(DirectMessage directMessage, boolean isSent) {
Dm dm = new Dm();
dm.id = directMessage.getId();
dm.text = directMessage.getText();
dm.createdAt = directMessage.getCreatedAt();
dm.isSent = isSent;
User user = dm.isSent ? directMessage.getRecipient() : directMessage
.getSender();
dm.screenName = TextHelper.getSimpleTweetText(user.getScreenName());
dm.userId = user.getId();
dm.profileImageUrl = user.getProfileImageURL().toString();
return dm;
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/data/Dm.java
|
Java
|
asf20
| 851
|
package com.ch_linghu.fanfoudroid.data;
import java.util.Date;
import android.os.Parcel;
import android.os.Parcelable;
public class User implements Parcelable {
public String id;
public String name;
public String screenName;
public String location;
public String description;
public String profileImageUrl;
public String url;
public boolean isProtected;
public int followersCount;
public String lastStatus;
public int friendsCount;
public int favoritesCount;
public int statusesCount;
public Date createdAt;
public boolean isFollowing;
// public boolean notifications;
// public utc_offset
public User() {
}
public static User create(com.ch_linghu.fanfoudroid.fanfou.User u) {
User user = new User();
user.id = u.getId();
user.name = u.getName();
user.screenName = u.getScreenName();
user.location = u.getLocation();
user.description = u.getDescription();
user.profileImageUrl = u.getProfileImageURL().toString();
if (u.getURL() != null) {
user.url = u.getURL().toString();
}
user.isProtected = u.isProtected();
user.followersCount = u.getFollowersCount();
user.lastStatus = u.getStatusText();
user.friendsCount = u.getFriendsCount();
user.favoritesCount = u.getFavouritesCount();
user.statusesCount = u.getStatusesCount();
user.createdAt = u.getCreatedAt();
user.isFollowing = u.isFollowing();
return user;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
boolean[] boolArray = new boolean[] { isProtected, isFollowing };
out.writeString(id);
out.writeString(name);
out.writeString(screenName);
out.writeString(location);
out.writeString(description);
out.writeString(profileImageUrl);
out.writeString(url);
out.writeBooleanArray(boolArray);
out.writeInt(friendsCount);
out.writeInt(followersCount);
out.writeInt(statusesCount);
}
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];
throw new UnsupportedOperationException();
}
};
public User(Parcel in) {
boolean[] boolArray = new boolean[] { isProtected, isFollowing };
id = in.readString();
name = in.readString();
screenName = in.readString();
location = in.readString();
description = in.readString();
profileImageUrl = in.readString();
url = in.readString();
in.readBooleanArray(boolArray);
friendsCount = in.readInt();
followersCount = in.readInt();
statusesCount = in.readInt();
isProtected = boolArray[0];
isFollowing = boolArray[1];
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/data/User.java
|
Java
|
asf20
| 2,793
|
/*
* 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.data;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class Tweet extends Message implements Parcelable {
private static final String TAG = "Tweet";
public com.ch_linghu.fanfoudroid.fanfou.User user;
public String source;
public String prevId;
private int statusType = -1; // @see StatusTable#TYPE_*
public void setStatusType(int type) {
statusType = type;
}
public int getStatusType() {
return statusType;
}
public Tweet() {
}
public static Tweet create(Status status) {
Tweet tweet = new Tweet();
tweet.id = status.getId();
// 转义符放到getSimpleTweetText里去处理,这里不做处理
tweet.text = status.getText();
tweet.createdAt = status.getCreatedAt();
tweet.favorited = status.isFavorited() ? "true" : "false";
tweet.truncated = status.isTruncated() ? "true" : "false";
tweet.inReplyToStatusId = status.getInReplyToStatusId();
tweet.inReplyToUserId = status.getInReplyToUserId();
tweet.inReplyToScreenName = status.getInReplyToScreenName();
tweet.screenName = TextHelper.getSimpleTweetText(status.getUser()
.getScreenName());
tweet.profileImageUrl = status.getUser().getProfileImageURL()
.toString();
tweet.userId = status.getUser().getId();
tweet.user = status.getUser();
tweet.thumbnail_pic = status.getThumbnail_pic();
tweet.bmiddle_pic = status.getBmiddle_pic();
tweet.original_pic = status.getOriginal_pic();
tweet.source = TextHelper.getSimpleTweetText(status.getSource());
return tweet;
}
public static Tweet createFromSearchApi(JSONObject jsonObject)
throws JSONException {
Tweet tweet = new Tweet();
tweet.id = jsonObject.getString("id") + "";
// 转义符放到getSimpleTweetText里去处理,这里不做处理
tweet.text = jsonObject.getString("text");
tweet.createdAt = DateTimeHelper.parseSearchApiDateTime(jsonObject
.getString("created_at"));
tweet.favorited = jsonObject.getString("favorited");
tweet.truncated = jsonObject.getString("truncated");
tweet.inReplyToStatusId = jsonObject.getString("in_reply_to_status_id");
tweet.inReplyToUserId = jsonObject.getString("in_reply_to_user_id");
tweet.inReplyToScreenName = jsonObject
.getString("in_reply_to_screen_name");
tweet.screenName = TextHelper.getSimpleTweetText(jsonObject
.getString("from_user"));
tweet.profileImageUrl = jsonObject.getString("profile_image_url");
tweet.userId = jsonObject.getString("from_user_id");
tweet.source = TextHelper.getSimpleTweetText(jsonObject
.getString("source"));
return tweet;
}
public static String buildMetaText(StringBuilder builder, Date createdAt,
String source, String replyTo) {
builder.setLength(0);
builder.append(DateTimeHelper.getRelativeDate(createdAt));
builder.append(" ");
builder.append(TwitterApplication.mContext
.getString(R.string.tweet_source_prefix));
builder.append(source);
if (!TextUtils.isEmpty(replyTo)) {
builder.append(" "
+ TwitterApplication.mContext
.getString(R.string.tweet_reply_to_prefix));
builder.append(replyTo);
builder.append(TwitterApplication.mContext
.getString(R.string.tweet_reply_to_suffix));
}
return builder.toString();
}
// For interface Parcelable
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeString(id);
out.writeString(text);
out.writeValue(createdAt); // Date
out.writeString(screenName);
out.writeString(favorited);
out.writeString(inReplyToStatusId);
out.writeString(inReplyToUserId);
out.writeString(inReplyToScreenName);
out.writeString(screenName);
out.writeString(profileImageUrl);
out.writeString(thumbnail_pic);
out.writeString(bmiddle_pic);
out.writeString(original_pic);
out.writeString(userId);
out.writeString(source);
}
public static final Parcelable.Creator<Tweet> CREATOR = new Parcelable.Creator<Tweet>() {
public Tweet createFromParcel(Parcel in) {
return new Tweet(in);
}
public Tweet[] newArray(int size) {
// return new Tweet[size];
throw new UnsupportedOperationException();
}
};
public Tweet(Parcel in) {
id = in.readString();
text = in.readString();
createdAt = (Date) in.readValue(Date.class.getClassLoader());
screenName = in.readString();
favorited = in.readString();
inReplyToStatusId = in.readString();
inReplyToUserId = in.readString();
inReplyToScreenName = in.readString();
screenName = in.readString();
profileImageUrl = in.readString();
thumbnail_pic = in.readString();
bmiddle_pic = in.readString();
original_pic = in.readString();
userId = in.readString();
source = in.readString();
}
@Override
public String toString() {
return "Tweet [source=" + source + ", id=" + id + ", screenName="
+ screenName + ", text=" + text + ", profileImageUrl="
+ profileImageUrl + ", createdAt=" + createdAt + ", userId="
+ userId + ", favorited=" + favorited + ", inReplyToStatusId="
+ inReplyToStatusId + ", inReplyToUserId=" + inReplyToUserId
+ ", inReplyToScreenName=" + inReplyToScreenName + "]";
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/data/Tweet.java
|
Java
|
asf20
| 6,268
|
package com.ch_linghu.fanfoudroid.data;
import java.util.Date;
public class Message {
public String id;
public String screenName;
public String text;
public String profileImageUrl;
public Date createdAt;
public String userId;
public String favorited;
public String truncated;
public String inReplyToStatusId;
public String inReplyToUserId;
public String inReplyToScreenName;
public String thumbnail_pic;
public String bmiddle_pic;
public String original_pic;
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/data/Message.java
|
Java
|
asf20
| 501
|
package com.ch_linghu.fanfoudroid.data;
import android.database.Cursor;
public interface BaseContent {
long insert();
int delete();
int update();
Cursor select();
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/data/BaseContent.java
|
Java
|
asf20
| 174
|
package com.ch_linghu.fanfoudroid.app;
import android.graphics.Bitmap;
import android.widget.ImageView;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
public class SimpleImageLoader {
public static void display(final ImageView imageView, String url) {
imageView.setTag(url);
imageView.setImageBitmap(TwitterApplication.mImageLoader.get(url,
createImageViewCallback(imageView, url)));
}
public static ImageLoaderCallback createImageViewCallback(
final ImageView imageView, String url) {
return new ImageLoaderCallback() {
@Override
public void refresh(String url, Bitmap bitmap) {
if (url.equals(imageView.getTag())) {
imageView.setImageBitmap(bitmap);
}
}
};
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/app/SimpleImageLoader.java
|
Java
|
asf20
| 789
|
package com.ch_linghu.fanfoudroid.app;
import java.lang.Thread.State;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.http.HttpException;
public class LazyImageLoader {
private static final String TAG = "ProfileImageCacheManager";
public static final int HANDLER_MESSAGE_ID = 1;
public static final String EXTRA_BITMAP = "extra_bitmap";
public static final String EXTRA_IMAGE_URL = "extra_image_url";
private ImageManager mImageManager = new ImageManager(
TwitterApplication.mContext);
private BlockingQueue<String> mUrlList = new ArrayBlockingQueue<String>(50);
private CallbackManager mCallbackManager = new CallbackManager();
private GetImageTask mTask = new GetImageTask();
/**
* 取图片, 可能直接从cache中返回, 或下载图片后返回
*
* @param url
* @param callback
* @return
*/
public Bitmap get(String url, ImageLoaderCallback callback) {
Bitmap bitmap = ImageCache.mDefaultBitmap;
if (mImageManager.isContains(url)) {
bitmap = mImageManager.get(url);
} else {
// bitmap不存在,启动Task进行下载
mCallbackManager.put(url, callback);
startDownloadThread(url);
}
return bitmap;
}
private void startDownloadThread(String url) {
if (url != null) {
addUrlToDownloadQueue(url);
}
// Start Thread
State state = mTask.getState();
if (Thread.State.NEW == state) {
mTask.start(); // first start
} else if (Thread.State.TERMINATED == state) {
mTask = new GetImageTask(); // restart
mTask.start();
}
}
private void addUrlToDownloadQueue(String url) {
if (!mUrlList.contains(url)) {
try {
mUrlList.put(url);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// Low-level interface to get ImageManager
public ImageManager getImageManager() {
return mImageManager;
}
private class GetImageTask extends Thread {
private volatile boolean mTaskTerminated = false;
private static final int TIMEOUT = 3 * 60;
private boolean isPermanent = true;
@Override
public void run() {
try {
while (!mTaskTerminated) {
String url;
if (isPermanent) {
url = mUrlList.take();
} else {
url = mUrlList.poll(TIMEOUT, TimeUnit.SECONDS); // waiting
if (null == url) {
break;
} // no more, shutdown
}
// Bitmap bitmap = ImageCache.mDefaultBitmap;
final Bitmap bitmap = mImageManager.safeGet(url);
// use handler to process callback
final Message m = handler.obtainMessage(HANDLER_MESSAGE_ID);
Bundle bundle = m.getData();
bundle.putString(EXTRA_IMAGE_URL, url);
bundle.putParcelable(EXTRA_BITMAP, bitmap);
handler.sendMessage(m);
}
} catch (HttpException ioe) {
Log.e(TAG, "Get Image failed, " + ioe.getMessage());
} catch (InterruptedException e) {
Log.w(TAG, e.getMessage());
} finally {
Log.v(TAG, "Get image task terminated.");
mTaskTerminated = true;
}
}
@SuppressWarnings("unused")
public boolean isPermanent() {
return isPermanent;
}
@SuppressWarnings("unused")
public void setPermanent(boolean isPermanent) {
this.isPermanent = isPermanent;
}
@SuppressWarnings("unused")
public void shutDown() throws InterruptedException {
mTaskTerminated = true;
}
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case HANDLER_MESSAGE_ID:
final Bundle bundle = msg.getData();
String url = bundle.getString(EXTRA_IMAGE_URL);
Bitmap bitmap = (Bitmap) (bundle.get(EXTRA_BITMAP));
// callback
mCallbackManager.call(url, bitmap);
break;
default:
// do nothing.
}
}
};
public interface ImageLoaderCallback {
void refresh(String url, Bitmap bitmap);
}
public static class CallbackManager {
private static final String TAG = "CallbackManager";
private ConcurrentHashMap<String, List<ImageLoaderCallback>> mCallbackMap;
public CallbackManager() {
mCallbackMap = new ConcurrentHashMap<String, List<ImageLoaderCallback>>();
}
public void put(String url, ImageLoaderCallback callback) {
Log.v(TAG, "url=" + url);
if (!mCallbackMap.containsKey(url)) {
Log.v(TAG, "url does not exist, add list to map");
mCallbackMap.put(url, new ArrayList<ImageLoaderCallback>());
// mCallbackMap.put(url, Collections.synchronizedList(new
// ArrayList<ImageLoaderCallback>()));
}
mCallbackMap.get(url).add(callback);
Log.v(TAG,
"Add callback to list, count(url)="
+ mCallbackMap.get(url).size());
}
public void call(String url, Bitmap bitmap) {
Log.v(TAG, "call url=" + url);
List<ImageLoaderCallback> callbackList = mCallbackMap.get(url);
if (callbackList == null) {
// FIXME: 有时会到达这里,原因我还没想明白
Log.e(TAG, "callbackList=null");
return;
}
for (ImageLoaderCallback callback : callbackList) {
if (callback != null) {
callback.refresh(url, bitmap);
}
}
callbackList.clear();
mCallbackMap.remove(url);
}
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/app/LazyImageLoader.java
|
Java
|
asf20
| 5,467
|
package com.ch_linghu.fanfoudroid.app;
import android.text.Spannable;
import android.text.method.LinkMovementMethod;
import android.text.method.MovementMethod;
import android.view.MotionEvent;
import android.widget.TextView;
public class TestMovementMethod extends LinkMovementMethod {
private double mY;
private boolean mIsMoving = false;
@Override
public boolean onTouchEvent(TextView widget, Spannable buffer,
MotionEvent event) {
/*
* int action = event.getAction();
*
* if (action == MotionEvent.ACTION_MOVE) { double deltaY = mY -
* event.getY(); mY = event.getY();
*
* Log.d("foo", deltaY + "");
*
* if (Math.abs(deltaY) > 1) { mIsMoving = true; } } else if (action ==
* MotionEvent.ACTION_DOWN) { mIsMoving = false; mY = event.getY(); }
* else if (action == MotionEvent.ACTION_UP) { boolean wasMoving =
* mIsMoving; mIsMoving = false;
*
* if (wasMoving) { return true; } }
*/
return super.onTouchEvent(widget, buffer, event);
}
public static MovementMethod getInstance() {
if (sInstance == null)
sInstance = new TestMovementMethod();
return sInstance;
}
private static TestMovementMethod sInstance;
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/app/TestMovementMethod.java
|
Java
|
asf20
| 1,229
|
/*
* 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.app;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* Manages retrieval and storage of icon images. Use the put method to download
* and store images. Use the get method to retrieve images from the manager.
*/
public class ImageManager implements ImageCache {
private static final String TAG = "ImageManager";
// 饭否目前最大宽度支持596px, 超过则同比缩小
// 最大高度为1192px, 超过从中截取
public static final int DEFAULT_COMPRESS_QUALITY = 90;
public static final int IMAGE_MAX_WIDTH = 596;
public static final int IMAGE_MAX_HEIGHT = 1192;
private Context mContext;
// In memory cache.
private Map<String, SoftReference<Bitmap>> mCache;
// MD5 hasher.
private MessageDigest mDigest;
public static Bitmap drawableToBitmap(Drawable drawable) {
Bitmap bitmap = Bitmap
.createBitmap(
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
public ImageManager(Context context) {
mContext = context;
mCache = new HashMap<String, SoftReference<Bitmap>>();
try {
mDigest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
// This shouldn't happen.
throw new RuntimeException("No MD5 algorithm.");
}
}
public void setContext(Context context) {
mContext = context;
}
private String getHashString(MessageDigest digest) {
StringBuilder builder = new StringBuilder();
for (byte b : digest.digest()) {
builder.append(Integer.toHexString((b >> 4) & 0xf));
builder.append(Integer.toHexString(b & 0xf));
}
return builder.toString();
}
// MD5 hases are used to generate filenames based off a URL.
private String getMd5(String url) {
mDigest.update(url.getBytes());
return getHashString(mDigest);
}
// Looks to see if an image is in the file system.
private Bitmap lookupFile(String url) {
String hashedUrl = getMd5(url);
FileInputStream fis = null;
try {
fis = mContext.openFileInput(hashedUrl);
return BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
// Not there.
return null;
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// Ignore.
}
}
}
}
/**
* Downloads a file
*
* @param url
* @return
* @throws HttpException
*/
public Bitmap downloadImage(String url) throws HttpException {
Log.d(TAG, "Fetching image: " + url);
Response res = TwitterApplication.mApi.getHttpClient().get(url);
return BitmapFactory.decodeStream(new BufferedInputStream(res
.asStream()));
}
public Bitmap downloadImage2(String url) throws HttpException {
Log.d(TAG, "[NEW]Fetching image: " + url);
final Response res = TwitterApplication.mApi.getHttpClient().get(url);
String file = writeToFile(res.asStream(), getMd5(url));
return BitmapFactory.decodeFile(file);
}
/**
* 下载远程图片 -> 转换为Bitmap -> 写入缓存器.
*
* @param url
* @param quality
* image quality 1~100
* @throws HttpException
*/
public void put(String url, int quality, boolean forceOverride)
throws HttpException {
if (!forceOverride && contains(url)) {
// Image already exists.
return;
// TODO: write to file if not present.
}
Bitmap bitmap = downloadImage(url);
if (bitmap != null) {
put(url, bitmap, quality); // file cache
} else {
Log.w(TAG, "Retrieved bitmap is null.");
}
}
/**
* 重载 put(String url, int quality)
*
* @param url
* @throws HttpException
*/
public void put(String url) throws HttpException {
put(url, DEFAULT_COMPRESS_QUALITY, false);
}
/**
* 将本地File -> 转换为Bitmap -> 写入缓存器. 如果图片大小超过MAX_WIDTH/MAX_HEIGHT, 则将会对图片缩放.
*
* @param file
* @param quality
* 图片质量(0~100)
* @param forceOverride
* @throws IOException
*/
public void put(File file, int quality, boolean forceOverride)
throws IOException {
if (!file.exists()) {
Log.w(TAG, file.getName() + " is not exists.");
return;
}
if (!forceOverride && contains(file.getPath())) {
// Image already exists.
Log.d(TAG, file.getName() + " is exists");
return;
// TODO: write to file if not present.
}
Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());
// bitmap = resizeBitmap(bitmap, MAX_WIDTH, MAX_HEIGHT);
if (bitmap == null) {
Log.w(TAG, "Retrieved bitmap is null.");
} else {
put(file.getPath(), bitmap, quality);
}
}
/**
* 将Bitmap写入缓存器.
*
* @param filePath
* file path
* @param bitmap
* @param quality
* 1~100
*/
public void put(String file, Bitmap bitmap, int quality) {
synchronized (this) {
mCache.put(file, new SoftReference<Bitmap>(bitmap));
}
writeFile(file, bitmap, quality);
}
/**
* 重载 put(String file, Bitmap bitmap, int quality)
*
* @param filePath
* file path
* @param bitmap
* @param quality
* 1~100
*/
@Override
public void put(String file, Bitmap bitmap) {
put(file, bitmap, DEFAULT_COMPRESS_QUALITY);
}
/**
* 将Bitmap写入本地缓存文件.
*
* @param file
* URL/PATH
* @param bitmap
* @param quality
*/
private void writeFile(String file, Bitmap bitmap, int quality) {
if (bitmap == null) {
Log.w(TAG, "Can't write file. Bitmap is null.");
return;
}
BufferedOutputStream bos = null;
try {
String hashedUrl = getMd5(file);
bos = new BufferedOutputStream(mContext.openFileOutput(hashedUrl,
Context.MODE_PRIVATE));
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos); // PNG
Log.d(TAG, "Writing file: " + file);
} catch (IOException ioe) {
Log.e(TAG, ioe.getMessage());
} finally {
try {
if (bos != null) {
bitmap.recycle();
bos.flush();
bos.close();
}
// bitmap.recycle();
} catch (IOException e) {
Log.e(TAG, "Could not close file.");
}
}
}
private String writeToFile(InputStream is, String filename) {
Log.d("LDS", "new write to file");
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(is);
out = new BufferedOutputStream(mContext.openFileOutput(filename,
Context.MODE_PRIVATE));
byte[] buffer = new byte[1024];
int l;
while ((l = in.read(buffer)) != -1) {
out.write(buffer, 0, l);
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (in != null)
in.close();
if (out != null) {
Log.d("LDS", "new write to file to -> " + filename);
out.flush();
out.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return mContext.getFilesDir() + "/" + filename;
}
public Bitmap get(File file) {
return get(file.getPath());
}
/**
* 判断缓存着中是否存在该文件对应的bitmap
*/
public boolean isContains(String file) {
return mCache.containsKey(file);
}
/**
* 获得指定file/URL对应的Bitmap,首先找本地文件,如果有直接使用,否则去网上获取
*
* @param file
* file URL/file PATH
* @param bitmap
* @param quality
* @throws HttpException
*/
public Bitmap safeGet(String file) throws HttpException {
Bitmap bitmap = lookupFile(file); // first try file.
if (bitmap != null) {
synchronized (this) { // memory cache
mCache.put(file, new SoftReference<Bitmap>(bitmap));
}
return bitmap;
} else { // get from web
String url = file;
bitmap = downloadImage2(url);
// 注释掉以测试新的写入文件方法
// put(file, bitmap); // file Cache
return bitmap;
}
}
/**
* 从缓存器中读取文件
*
* @param file
* file URL/file PATH
* @param bitmap
* @param quality
*/
public Bitmap get(String file) {
SoftReference<Bitmap> ref;
Bitmap bitmap;
// Look in memory first.
synchronized (this) {
ref = mCache.get(file);
}
if (ref != null) {
bitmap = ref.get();
if (bitmap != null) {
return bitmap;
}
}
// Now try file.
bitmap = lookupFile(file);
if (bitmap != null) {
synchronized (this) {
mCache.put(file, new SoftReference<Bitmap>(bitmap));
}
return bitmap;
}
// TODO: why?
// upload: see profileImageCacheManager line 96
Log.w(TAG, "Image is missing: " + file);
// return the default photo
return mDefaultBitmap;
}
public boolean contains(String url) {
return get(url) != mDefaultBitmap;
}
public void clear() {
String[] files = mContext.fileList();
for (String file : files) {
mContext.deleteFile(file);
}
synchronized (this) {
mCache.clear();
}
}
public void cleanup(HashSet<String> keepers) {
String[] files = mContext.fileList();
HashSet<String> hashedUrls = new HashSet<String>();
for (String imageUrl : keepers) {
hashedUrls.add(getMd5(imageUrl));
}
for (String file : files) {
if (!hashedUrls.contains(file)) {
Log.d(TAG, "Deleting unused file: " + file);
mContext.deleteFile(file);
}
}
}
/**
* Compress and resize the Image
*
* <br />
* 因为不论图片大小和尺寸如何, 饭否都会对图片进行一次有损压缩, 所以本地压缩应该 考虑图片将会被二次压缩所造成的图片质量损耗
*
* @param targetFile
* @param quality
* , 0~100, recommend 100
* @return
* @throws IOException
*/
public File compressImage(File targetFile, int quality) throws IOException {
String filepath = targetFile.getAbsolutePath();
// 1. Calculate scale
int scale = 1;
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filepath, o);
if (o.outWidth > IMAGE_MAX_WIDTH || o.outHeight > IMAGE_MAX_HEIGHT) {
scale = (int) Math.pow(
2.0,
(int) Math.round(Math.log(IMAGE_MAX_WIDTH
/ (double) Math.max(o.outHeight, o.outWidth))
/ Math.log(0.5)));
// scale = 2;
}
Log.d(TAG, scale + " scale");
// 2. File -> Bitmap (Returning a smaller image)
o.inJustDecodeBounds = false;
o.inSampleSize = scale;
Bitmap bitmap = BitmapFactory.decodeFile(filepath, o);
// 2.1. Resize Bitmap
// bitmap = resizeBitmap(bitmap, IMAGE_MAX_WIDTH, IMAGE_MAX_HEIGHT);
// 3. Bitmap -> File
writeFile(filepath, bitmap, quality);
// 4. Get resized Image File
String filePath = getMd5(targetFile.getPath());
File compressedImage = mContext.getFileStreamPath(filePath);
return compressedImage;
}
/**
* 保持长宽比缩小Bitmap
*
* @param bitmap
* @param maxWidth
* @param maxHeight
* @param quality
* 1~100
* @return
*/
public Bitmap resizeBitmap(Bitmap bitmap, int maxWidth, int maxHeight) {
int originWidth = bitmap.getWidth();
int originHeight = bitmap.getHeight();
// no need to resize
if (originWidth < maxWidth && originHeight < maxHeight) {
return bitmap;
}
int newWidth = originWidth;
int newHeight = originHeight;
// 若图片过宽, 则保持长宽比缩放图片
if (originWidth > maxWidth) {
newWidth = maxWidth;
double i = originWidth * 1.0 / maxWidth;
newHeight = (int) Math.floor(originHeight / i);
bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight,
true);
}
// 若图片过长, 则从中部截取
if (newHeight > maxHeight) {
newHeight = maxHeight;
int half_diff = (int) ((originHeight - maxHeight) / 2.0);
bitmap = Bitmap.createBitmap(bitmap, 0, half_diff, newWidth,
newHeight);
}
Log.d(TAG, newWidth + " width");
Log.d(TAG, newHeight + " height");
return bitmap;
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/app/ImageManager.java
|
Java
|
asf20
| 13,800
|
package com.ch_linghu.fanfoudroid.app;
import android.graphics.Bitmap;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
public interface ImageCache {
public static Bitmap mDefaultBitmap = ImageManager
.drawableToBitmap(TwitterApplication.mContext.getResources()
.getDrawable(R.drawable.user_default_photo));
public Bitmap get(String url);
public void put(String url, Bitmap bitmap);
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/app/ImageCache.java
|
Java
|
asf20
| 457
|
/*
* 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.app;
public class Preferences {
public static final String USERNAME_KEY = "username";
public static final String PASSWORD_KEY = "password";
public static final String CHECK_UPDATES_KEY = "check_updates";
public static final String CHECK_UPDATE_INTERVAL_KEY = "check_update_interval";
public static final String VIBRATE_KEY = "vibrate";
public static final String TIMELINE_ONLY_KEY = "timeline_only";
public static final String REPLIES_ONLY_KEY = "replies_only";
public static final String DM_ONLY_KEY = "dm_only";
public static String RINGTONE_KEY = "ringtone";
public static final String RINGTONE_DEFAULT_KEY = "content://settings/system/notification_sound";
public static final String LAST_TWEET_REFRESH_KEY = "last_tweet_refresh";
public static final String LAST_DM_REFRESH_KEY = "last_dm_refresh";
public static final String LAST_FOLLOWERS_REFRESH_KEY = "last_followers_refresh";
public static final String TWITTER_ACTIVITY_STATE_KEY = "twitter_activity_state";
public static final String HIGHLIGHT_BACKGROUND = "highlight_background";
public static final String USE_PROFILE_IMAGE = "use_profile_image";
public static final String PHOTO_PREVIEW = "photo_preview";
public static final String FORCE_SHOW_ALL_IMAGE = "force_show_all_image";
public static final String RT_PREFIX_KEY = "rt_prefix";
public static final String RT_INSERT_APPEND = "rt_insert_append"; // 转发时光标放置在开始还是结尾
public static final String NETWORK_TYPE = "network_type";
// DEBUG标记
public static final String DEBUG = "debug";
// 当前用户相关信息
public static final String CURRENT_USER_ID = "current_user_id";
public static final String CURRENT_USER_SCREEN_NAME = "current_user_screenname";
public static final String UI_FONT_SIZE = "ui_font_size";
public static final String USE_ENTER_SEND = "use_enter_send";
public static final String USE_GESTRUE = "use_gestrue";
public static final String USE_SHAKE = "use_shake";
public static final String FORCE_SCREEN_ORIENTATION_PORTRAIT = "force_screen_orientation_portrait";
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/app/Preferences.java
|
Java
|
asf20
| 2,768
|
package com.ch_linghu.fanfoudroid.app;
import java.util.HashMap;
import android.graphics.Bitmap;
public class MemoryImageCache implements ImageCache {
private HashMap<String, Bitmap> mCache;
public MemoryImageCache() {
mCache = new HashMap<String, Bitmap>();
}
@Override
public Bitmap get(String url) {
synchronized (this) {
Bitmap bitmap = mCache.get(url);
if (bitmap == null) {
return mDefaultBitmap;
} else {
return bitmap;
}
}
}
@Override
public void put(String url, Bitmap bitmap) {
synchronized (this) {
mCache.put(url, bitmap);
}
}
public void putAll(MemoryImageCache imageCache) {
synchronized (this) {
// TODO: is this thread safe?
mCache.putAll(imageCache.mCache);
}
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/app/MemoryImageCache.java
|
Java
|
asf20
| 785
|
package com.ch_linghu.fanfoudroid.app;
import android.app.Activity;
import android.content.Intent;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.LoginActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.fanfou.RefuseError;
import com.ch_linghu.fanfoudroid.http.HttpAuthException;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.HttpRefusedException;
import com.ch_linghu.fanfoudroid.http.HttpServerException;
public class ExceptionHandler {
private Activity mActivity;
public ExceptionHandler(Activity activity) {
mActivity = activity;
}
public void handle(HttpException e) {
Throwable cause = e.getCause();
if (null == cause)
return;
// Handle Different Exception
if (cause instanceof HttpAuthException) {
// 用户名/密码错误
Toast.makeText(mActivity, R.string.error_not_authorized,
Toast.LENGTH_LONG).show();
Intent intent = new Intent(mActivity, LoginActivity.class);
mActivity.startActivity(intent); // redirect to the login activity
} else if (cause instanceof HttpServerException) {
// 服务器暂时无法响应
Toast.makeText(mActivity, R.string.error_not_authorized,
Toast.LENGTH_LONG).show();
} else if (cause instanceof HttpAuthException) {
// FIXME: 集中处理用户名/密码验证错误,返回到登录界面
} else if (cause instanceof HttpRefusedException) {
// 服务器拒绝请求,如没有权限查看某用户信息
RefuseError error = ((HttpRefusedException) cause).getError();
switch (error.getErrorCode()) {
// TODO: finish it
case -1:
default:
Toast.makeText(mActivity, error.getMessage(), Toast.LENGTH_LONG)
.show();
break;
}
}
}
private void handleCause() {
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/app/ExceptionHandler.java
|
Java
|
asf20
| 1,794
|
/*
* 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;
import com.ch_linghu.fanfoudroid.R;
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(false))) {
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(false);
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/TwitterActivity.java
|
Java
|
asf20
| 6,852
|
/*
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 + '\'' + '}';
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/fanfou/Query.java
|
Java
|
asf20
| 6,257
|
/*
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 + "]";
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/fanfou/Photo.java
|
Java
|
asf20
| 3,073
|
/*
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 + '}';
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/fanfou/QueryResult.java
|
Java
|
asf20
| 5,759
|
/*
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;
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/fanfou/WeiboSupport.java
|
Java
|
asf20
| 2,420
|
/*
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 + '\'' + '}';
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/fanfou/Trend.java
|
Java
|
asf20
| 3,047
|
/*
* 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;
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/fanfou/UserWapper.java
|
Java
|
asf20
| 1,286
|
/*
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;
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/fanfou/WeiboResponse.java
|
Java
|
asf20
| 8,202
|
/*
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 + '}';
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/fanfou/Weibo.java
|
Java
|
asf20
| 60,114
|
/*
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");
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/fanfou/Configuration.java
|
Java
|
asf20
| 10,823
|
/*
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;
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/fanfou/User.java
|
Java
|
asf20
| 22,419
|
/*
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))
+ '}';
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/fanfou/Trends.java
|
Java
|
asf20
| 5,799
|
/*
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);
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/fanfou/Status.java
|
Java
|
asf20
| 11,959
|
/*
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 + '}';
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/fanfou/IDs.java
|
Java
|
asf20
| 4,386
|
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;
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/fanfou/WeiboException.java
|
Java
|
asf20
| 887
|
/*
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 + '}';
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/fanfou/RetweetDetails.java
|
Java
|
asf20
| 5,531
|
/*
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;
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/fanfou/RefuseError.java
|
Java
|
asf20
| 4,216
|
/*
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();
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/fanfou/RateLimitStatus.java
|
Java
|
asf20
| 3,814
|
/*
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 + '}';
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/fanfou/DirectMessage.java
|
Java
|
asf20
| 6,727
|
/*
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;
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/fanfou/Paging.java
|
Java
|
asf20
| 3,505
|
/*
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 + '}';
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/fanfou/SavedSearch.java
|
Java
|
asf20
| 4,541
|
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 + "]";
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/data2/Photo.java
|
Java
|
asf20
| 702
|
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);
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/data2/DataUtils.java
|
Java
|
asf20
| 531
|
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;
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/data2/User.java
|
Java
|
asf20
| 3,686
|
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 + "]";
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/data2/Status.java
|
Java
|
asf20
| 3,510
|
package com.ch_linghu.fanfoudroid.dao;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Database Helper
*
* @see SQLiteDatabase
*/
public class SQLiteTemplate {
/**
* Default Primary key
*/
protected String mPrimaryKey = "_id";
/**
* SQLiteDatabase Open Helper
*/
protected SQLiteOpenHelper mDatabaseOpenHelper;
/**
* Construct
*
* @param databaseOpenHelper
*/
public SQLiteTemplate(SQLiteOpenHelper databaseOpenHelper) {
mDatabaseOpenHelper = databaseOpenHelper;
}
/**
* Construct
*
* @param databaseOpenHelper
* @param primaryKey
*/
public SQLiteTemplate(SQLiteOpenHelper databaseOpenHelper, String primaryKey) {
this(databaseOpenHelper);
setPrimaryKey(primaryKey);
}
/**
* 根据某一个字段和值删除一行数据, 如 name="jack"
*
* @param table
* @param field
* @param value
* @return
*/
public int deleteByField(String table, String field, String value) {
return getDb(true).delete(table, field + "=?", new String[] { value });
}
/**
* 根据主键删除一行数据
*
* @param table
* @param id
* @return
*/
public int deleteById(String table, String id) {
return deleteByField(table, mPrimaryKey, id);
}
/**
* 根据主键更新一行数据
*
* @param table
* @param id
* @param values
* @return
*/
public int updateById(String table, String id, ContentValues values) {
return getDb(true).update(table, values, mPrimaryKey + "=?",
new String[] { id });
}
/**
* 根据主键查看某条数据是否存在
*
* @param table
* @param id
* @return
*/
public boolean isExistsById(String table, String id) {
return isExistsByField(table, mPrimaryKey, id);
}
/**
* 根据某字段/值查看某条数据是否存在
*
* @param status
* @return
*/
public boolean isExistsByField(String table, String field, String value) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT COUNT(*) FROM ").append(table).append(" WHERE ")
.append(field).append(" =?");
return isExistsBySQL(sql.toString(), new String[] { value });
}
/**
* 使用SQL语句查看某条数据是否存在
*
* @param sql
* @param selectionArgs
* @return
*/
public boolean isExistsBySQL(String sql, String[] selectionArgs) {
boolean result = false;
final Cursor c = getDb(false).rawQuery(sql, selectionArgs);
try {
if (c.moveToFirst()) {
result = (c.getInt(0) > 0);
}
} finally {
c.close();
}
return result;
}
/**
* Query for cursor
*
* @param <T>
* @param rowMapper
* @return a cursor
*
* @see SQLiteDatabase#query(String, String[], String, String[], String,
* String, String, String)
*/
public <T> T queryForObject(RowMapper<T> rowMapper, String table,
String[] columns, String selection, String[] selectionArgs,
String groupBy, String having, String orderBy, String limit) {
T object = null;
final Cursor c = getDb(false).query(table, columns, selection,
selectionArgs, groupBy, having, orderBy, limit);
try {
if (c.moveToFirst()) {
object = rowMapper.mapRow(c, c.getCount());
}
} finally {
c.close();
}
return object;
}
/**
* Query for list
*
* @param <T>
* @param rowMapper
* @return list of object
*
* @see SQLiteDatabase#query(String, String[], String, String[], String,
* String, String, String)
*/
public <T> List<T> queryForList(RowMapper<T> rowMapper, String table,
String[] columns, String selection, String[] selectionArgs,
String groupBy, String having, String orderBy, String limit) {
List<T> list = new ArrayList<T>();
final Cursor c = getDb(false).query(table, columns, selection,
selectionArgs, groupBy, having, orderBy, limit);
try {
while (c.moveToNext()) {
list.add(rowMapper.mapRow(c, 1));
}
} finally {
c.close();
}
return list;
}
/**
* Get Primary Key
*
* @return
*/
public String getPrimaryKey() {
return mPrimaryKey;
}
/**
* Set Primary Key
*
* @param primaryKey
*/
public void setPrimaryKey(String primaryKey) {
this.mPrimaryKey = primaryKey;
}
/**
* Get Database Connection
*
* @param writeable
* @return
* @see SQLiteOpenHelper#getWritableDatabase();
* @see SQLiteOpenHelper#getReadableDatabase();
*/
public SQLiteDatabase getDb(boolean writeable) {
if (writeable) {
return mDatabaseOpenHelper.getWritableDatabase();
} else {
return mDatabaseOpenHelper.getReadableDatabase();
}
}
/**
* Some as Spring JDBC RowMapper
*
* @see org.springframework.jdbc.core.RowMapper
* @see com.ch_linghu.fanfoudroid.db.dao.SqliteTemplate
* @param <T>
*/
public interface RowMapper<T> {
public T mapRow(Cursor cursor, int rowNum);
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/dao/SQLiteTemplate.java
|
Java
|
asf20
| 4,913
|
package com.ch_linghu.fanfoudroid.dao;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import android.util.Log;
import com.ch_linghu.fanfoudroid.dao.SQLiteTemplate.RowMapper;
import com.ch_linghu.fanfoudroid.data2.Photo;
import com.ch_linghu.fanfoudroid.data2.Status;
import com.ch_linghu.fanfoudroid.data2.User;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.db2.FanContent;
import com.ch_linghu.fanfoudroid.db2.FanContent.StatusesPropertyTable;
import com.ch_linghu.fanfoudroid.db2.FanDatabase;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.db2.FanContent.*;
public class StatusDAO {
private static final String TAG = "StatusDAO";
private SQLiteTemplate mSqlTemplate;
public StatusDAO(Context context) {
mSqlTemplate = new SQLiteTemplate(FanDatabase.getInstance(context)
.getSQLiteOpenHelper());
}
/**
* Insert a Status
*
* 若报 SQLiteconstraintexception 异常, 检查是否某not null字段为空
*
* @param status
* @param isUnread
* @return
*/
public long insertStatus(Status status) {
if (!isExists(status)) {
return mSqlTemplate.getDb(true).insert(StatusesTable.TABLE_NAME,
null, statusToContentValues(status));
} else {
Log.e(TAG, status.getId() + " is exists.");
return -1;
}
}
// TODO:
public int insertStatuses(List<Status> statuses) {
int result = 0;
SQLiteDatabase db = mSqlTemplate.getDb(true);
try {
db.beginTransaction();
for (int i = statuses.size() - 1; i >= 0; i--) {
Status status = statuses.get(i);
long id = db.insertWithOnConflict(StatusesTable.TABLE_NAME,
null, statusToContentValues(status),
SQLiteDatabase.CONFLICT_IGNORE);
if (-1 == id) {
Log.e(TAG, "cann't insert the tweet : " + status.toString());
} else {
++result;
Log.v(TAG, String.format(
"Insert a status into database : %s",
status.toString()));
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
return result;
}
/**
* Delete a status
*
* @param statusId
* @param owner_id
* owner id
* @param type
* status type
* @return
* @see StatusDAO#deleteStatus(Status)
*/
public int deleteStatus(String statusId, String owner_id, int type) {
// FIXME: 数据模型改变后这里的逻辑需要完全重写,目前仅保证编译可通过
String where = StatusesTable.Columns.ID + " =? ";
String[] binds;
if (!TextUtils.isEmpty(owner_id)) {
where += " AND " + StatusesPropertyTable.Columns.OWNER_ID + " = ? ";
binds = new String[] { statusId, owner_id };
} else {
binds = new String[] { statusId };
}
if (-1 != type) {
where += " AND " + StatusesPropertyTable.Columns.TYPE + " = "
+ type;
}
return mSqlTemplate.getDb(true).delete(StatusesTable.TABLE_NAME,
where.toString(), binds);
}
/**
* Delete a Status
*
* @param status
* @return
* @see StatusDAO#deleteStatus(String, String, int)
*/
public int deleteStatus(Status status) {
return deleteStatus(status.getId(), status.getOwnerId(),
status.getType());
}
/**
* Find a status by status ID
*
* @param statusId
* @return
*/
public Status fetchStatus(String statusId) {
return mSqlTemplate.queryForObject(mRowMapper,
StatusesTable.TABLE_NAME, null, StatusesTable.Columns.ID
+ " = ?", new String[] { statusId }, null, null,
"created_at DESC", "1");
}
/**
* Find user's statuses
*
* @param userId
* user id
* @param statusType
* status type, see {@link StatusTable#TYPE_USER}...
* @return list of statuses
*/
public List<Status> fetchStatuses(String userId, int statusType) {
return mSqlTemplate.queryForList(mRowMapper,
FanContent.StatusesTable.TABLE_NAME, null,
StatusesPropertyTable.Columns.OWNER_ID + " = ? AND "
+ StatusesPropertyTable.Columns.TYPE + " = "
+ statusType, new String[] { userId }, null, null,
"created_at DESC", null);
}
/**
* @see StatusDAO#fetchStatuses(String, int)
*/
public List<Status> fetchStatuses(String userId, String statusType) {
return fetchStatuses(userId, Integer.parseInt(statusType));
}
/**
* Update by using {@link ContentValues}
*
* @param statusId
* @param newValues
* @return
*/
public int updateStatus(String statusId, ContentValues values) {
return mSqlTemplate.updateById(FanContent.StatusesTable.TABLE_NAME,
statusId, values);
}
/**
* Update by using {@link Status}
*
* @param status
* @return
*/
public int updateStatus(Status status) {
return updateStatus(status.getId(), statusToContentValues(status));
}
/**
* Check if status exists
*
* FIXME: 取消使用Query
*
* @param status
* @return
*/
public boolean isExists(Status status) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT COUNT(*) FROM ")
.append(FanContent.StatusesTable.TABLE_NAME).append(" WHERE ")
.append(StatusesTable.Columns.ID).append(" =? AND ")
.append(StatusesPropertyTable.Columns.OWNER_ID)
.append(" =? AND ").append(StatusesPropertyTable.Columns.TYPE)
.append(" = ").append(status.getType());
return mSqlTemplate.isExistsBySQL(sql.toString(),
new String[] { status.getId(), status.getUser().getId() });
}
/**
* Status -> ContentValues
*
* @param status
* @param isUnread
* @return
*/
private ContentValues statusToContentValues(Status status) {
final ContentValues v = new ContentValues();
v.put(StatusesTable.Columns.ID, status.getId());
v.put(StatusesPropertyTable.Columns.TYPE, status.getType());
v.put(StatusesTable.Columns.TEXT, status.getText());
v.put(StatusesPropertyTable.Columns.OWNER_ID, status.getOwnerId());
v.put(StatusesTable.Columns.FAVORITED, status.isFavorited() + "");
v.put(StatusesTable.Columns.TRUNCATED, status.isTruncated()); // TODO:
v.put(StatusesTable.Columns.IN_REPLY_TO_STATUS_ID,
status.getInReplyToStatusId());
v.put(StatusesTable.Columns.IN_REPLY_TO_USER_ID,
status.getInReplyToUserId());
// v.put(StatusTable.Columns.IN_REPLY_TO_SCREEN_NAME,
// status.getInReplyToScreenName());
// v.put(IS_REPLY, status.isReply());
v.put(StatusesTable.Columns.CREATED_AT,
TwitterDatabase.DB_DATE_FORMATTER.format(status.getCreatedAt()));
v.put(StatusesTable.Columns.SOURCE, status.getSource());
// v.put(StatusTable.Columns.IS_UNREAD, status.isUnRead());
final User user = status.getUser();
if (user != null) {
v.put(UserTable.Columns.USER_ID, user.getId());
v.put(UserTable.Columns.SCREEN_NAME, user.getScreenName());
v.put(UserTable.Columns.PROFILE_IMAGE_URL,
user.getProfileImageUrl());
}
final Photo photo = status.getPhotoUrl();
/*
* if (photo != null) { v.put(StatusTable.Columns.PIC_THUMB,
* photo.getThumburl()); v.put(StatusTable.Columns.PIC_MID,
* photo.getImageurl()); v.put(StatusTable.Columns.PIC_ORIG,
* photo.getLargeurl()); }
*/
return v;
}
private static final RowMapper<Status> mRowMapper = new RowMapper<Status>() {
@Override
public Status mapRow(Cursor cursor, int rowNum) {
Photo photo = new Photo();
/*
* photo.setImageurl(cursor.getString(cursor
* .getColumnIndex(StatusTable.Columns.PIC_MID)));
* photo.setLargeurl(cursor.getString(cursor
* .getColumnIndex(StatusTable.Columns.PIC_ORIG)));
* photo.setThumburl(cursor.getString(cursor
* .getColumnIndex(StatusTable.Columns.PIC_THUMB)));
*/
User user = new User();
user.setScreenName(cursor.getString(cursor
.getColumnIndex(UserTable.Columns.SCREEN_NAME)));
user.setId(cursor.getString(cursor
.getColumnIndex(UserTable.Columns.USER_ID)));
user.setProfileImageUrl(cursor.getString(cursor
.getColumnIndex(UserTable.Columns.PROFILE_IMAGE_URL)));
Status status = new Status();
status.setPhotoUrl(photo);
status.setUser(user);
status.setOwnerId(cursor.getString(cursor
.getColumnIndex(StatusesPropertyTable.Columns.OWNER_ID)));
// TODO: 将数据库中的statusType改成Int类型
status.setType(cursor.getInt(cursor
.getColumnIndex(StatusesPropertyTable.Columns.TYPE)));
status.setId(cursor.getString(cursor
.getColumnIndex(StatusesTable.Columns.ID)));
status.setCreatedAt(DateTimeHelper.parseDateTimeFromSqlite(cursor
.getString(cursor
.getColumnIndex(StatusesTable.Columns.CREATED_AT))));
// TODO: 更改favorite 在数据库类型为boolean后改为 " != 0 "
status.setFavorited(cursor.getString(
cursor.getColumnIndex(StatusesTable.Columns.FAVORITED))
.equals("true"));
status.setText(cursor.getString(cursor
.getColumnIndex(StatusesTable.Columns.TEXT)));
status.setSource(cursor.getString(cursor
.getColumnIndex(StatusesTable.Columns.SOURCE)));
// status.setInReplyToScreenName(cursor.getString(cursor
// .getColumnIndex(StatusTable.IN_REPLY_TO_SCREEN_NAME)));
status.setInReplyToStatusId(cursor.getString(cursor
.getColumnIndex(StatusesTable.Columns.IN_REPLY_TO_STATUS_ID)));
status.setInReplyToUserId(cursor.getString(cursor
.getColumnIndex(StatusesTable.Columns.IN_REPLY_TO_USER_ID)));
status.setTruncated(cursor.getInt(cursor
.getColumnIndex(StatusesTable.Columns.TRUNCATED)) != 0);
// status.setUnRead(cursor.getInt(cursor
// .getColumnIndex(StatusTable.Columns.IS_UNREAD)) != 0);
return status;
}
};
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/dao/StatusDAO.java
|
Java
|
asf20
| 9,581
|
package com.ch_linghu.fanfoudroid.db2;
import java.util.ArrayList;
import java.util.Arrays;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
/**
* Wrapper of SQliteDatabse#query, OOP style.
*
* Usage: ------------------------------------------------ Query select = new
* Query(SQLiteDatabase);
*
* // SELECT query.from("tableName", new String[] { "colName" })
* .where("id = ?", 123456) .where("name = ?", "jack")
* .orderBy("created_at DESC") .limit(1); Cursor cursor = query.select();
*
* // DELETE query.from("tableName") .where("id = ?", 123455); .delete();
*
* // UPDATE query.setTable("tableName") .values(contentValues) .update();
*
* // INSERT query.into("tableName") .values(contentValues) .insert();
* ------------------------------------------------
*
* @see SQLiteDatabase#query(String, String[], String, String[], String, String,
* String, String)
*/
public class Query {
private static final String TAG = "Query-Builder";
/** TEMP list for selctionArgs */
private ArrayList<String> binds = new ArrayList<String>();
private SQLiteDatabase mDb = null;
private String mTable;
private String[] mColumns;
private String mSelection = null;
private String[] mSelectionArgs = null;
private String mGroupBy = null;
private String mHaving = null;
private String mOrderBy = null;
private String mLimit = null;
private ContentValues mValues = null;
private String mNullColumnHack = null;
public Query() {
}
/**
* Construct
*
* @param db
*/
public Query(SQLiteDatabase db) {
this.setDb(db);
}
/**
* Query the given table, returning a Cursor over the result set.
*
* @param db
* SQLitedatabase
* @return A Cursor object, which is positioned before the first entry, or
* NULL
*/
public Cursor select() {
if (preCheck()) {
buildQuery();
return mDb.query(mTable, mColumns, mSelection, mSelectionArgs,
mGroupBy, mHaving, mOrderBy, mLimit);
} else {
// throw new SelectException("Cann't build the query . " +
// toString());
Log.e(TAG, "Cann't build the query " + toString());
return null;
}
}
/**
* @return the number of rows affected if a whereClause is passed in, 0
* otherwise. To remove all rows and get a count pass "1" as the
* whereClause.
*/
public int delete() {
if (preCheck()) {
buildQuery();
return mDb.delete(mTable, mSelection, mSelectionArgs);
} else {
Log.e(TAG, "Cann't build the query " + toString());
return -1;
}
}
/**
* Set FROM
*
* @param table
* The table name to compile the query against.
* @param columns
* A list of which columns to return. Passing null will return
* all columns, which is discouraged to prevent reading data from
* storage that isn't going to be used.
* @return self
*
*/
public Query from(String table, String[] columns) {
mTable = table;
mColumns = columns;
return this;
}
/**
* @see Query#from(String table, String[] columns)
* @param table
* @return self
*/
public Query from(String table) {
return from(table, null); // all columns
}
/**
* Add WHERE
*
* @param selection
* A filter declaring which rows to return, formatted as an SQL
* WHERE clause (excluding the WHERE itself). Passing null will
* return all rows for the given table.
* @param selectionArgs
* You may include ?s in selection, which will be replaced by the
* values from selectionArgs, in order that they appear in the
* selection. The values will be bound as Strings.
* @return self
*/
public Query where(String selection, String[] selectionArgs) {
addSelection(selection);
binds.addAll(Arrays.asList(selectionArgs));
return this;
}
/**
* @see Query#where(String selection, String[] selectionArgs)
*/
public Query where(String selection, String selectionArg) {
addSelection(selection);
binds.add(selectionArg);
return this;
}
/**
* @see Query#where(String selection, String[] selectionArgs)
*/
public Query where(String selection) {
addSelection(selection);
return this;
}
/**
* add selection part
*
* @param selection
*/
private void addSelection(String selection) {
if (null == mSelection) {
mSelection = selection;
} else {
mSelection += " AND " + selection;
}
}
/**
* set HAVING
*
* @param having
* A filter declare which row groups to include in the cursor, if
* row grouping is being used, formatted as an SQL HAVING clause
* (excluding the HAVING itself). Passing null will cause all row
* groups to be included, and is required when row grouping is
* not being used.
* @return self
*/
public Query having(String having) {
this.mHaving = having;
return this;
}
/**
* Set GROUP BY
*
* @param groupBy
* A filter declaring how to group rows, formatted as an SQL
* GROUP BY clause (excluding the GROUP BY itself). Passing null
* will cause the rows to not be grouped.
* @return self
*/
public Query groupBy(String groupBy) {
this.mGroupBy = groupBy;
return this;
}
/**
* Set ORDER BY
*
* @param orderBy
* How to order the rows, formatted as an SQL ORDER BY clause
* (excluding the ORDER BY itself). Passing null will use the
* default sort order, which may be unordered.
* @return self
*/
public Query orderBy(String orderBy) {
this.mOrderBy = orderBy;
return this;
}
/**
* @param limit
* Limits the number of rows returned by the query, formatted as
* LIMIT clause. Passing null denotes no LIMIT clause.
* @return self
*/
public Query limit(String limit) {
this.mLimit = limit;
return this;
}
/**
* @see Query#limit(String limit)
*/
public Query limit(int limit) {
return limit(limit + "");
}
/**
* Merge selectionArgs
*/
private void buildQuery() {
mSelectionArgs = new String[binds.size()];
binds.toArray(mSelectionArgs);
Log.v(TAG, toString());
}
private boolean preCheck() {
return (mTable != null && mDb != null);
}
// For Insert
/**
* set insert table
*
* @param table
* table name
* @return self
*/
public Query into(String table) {
return setTable(table);
}
/**
* Set new values
*
* @param values
* new values
* @return self
*/
public Query values(ContentValues values) {
mValues = values;
return this;
}
/**
* Insert a row
*
* @return the row ID of the newly inserted row, or -1 if an error occurred
*/
public long insert() {
return mDb.insert(mTable, mNullColumnHack, mValues);
}
// For update
/**
* Set target table
*
* @param table
* table name
* @return self
*/
public Query setTable(String table) {
mTable = table;
return this;
}
/**
* Update a row
*
* @return the number of rows affected, or -1 if an error occurred
*/
public int update() {
if (preCheck()) {
buildQuery();
return mDb.update(mTable, mValues, mSelection, mSelectionArgs);
} else {
Log.e(TAG, "Cann't build the query " + toString());
return -1;
}
}
/**
* Set back-end database
*
* @param db
*/
public void setDb(SQLiteDatabase db) {
if (null == this.mDb) {
this.mDb = db;
}
}
@Override
public String toString() {
return "Query [table=" + mTable + ", columns="
+ Arrays.toString(mColumns) + ", selection=" + mSelection
+ ", selectionArgs=" + Arrays.toString(mSelectionArgs)
+ ", groupBy=" + mGroupBy + ", having=" + mHaving
+ ", orderBy=" + mOrderBy + "]";
}
/** for debug */
public ContentValues getContentValues() {
return mValues;
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/db2/Query.java
|
Java
|
asf20
| 7,915
|
package com.ch_linghu.fanfoudroid.db2;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.ch_linghu.fanfoudroid.db2.FanContent.*;
public class FanDatabase {
private static final String TAG = FanDatabase.class.getSimpleName();
/**
* SQLite Database file name
*/
private static final String DATABASE_NAME = "fanfoudroid.db";
/**
* Database Version
*/
public static final int DATABASE_VERSION = 2;
/**
* self instance
*/
private static FanDatabase sInstance = null;
/**
* SQLiteDatabase Open Helper
*/
private DatabaseHelper mOpenHelper = null;
/**
* SQLiteOpenHelper
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
// Construct
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "Create Database.");
// TODO: create tables
createAllTables(db);
createAllIndexes(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "Upgrade Database.");
// TODO: DROP TABLE
onCreate(db);
}
}
/**
* Construct
*
* @param context
*/
private FanDatabase(Context context) {
mOpenHelper = new DatabaseHelper(context);
}
/**
* Get Database
*
* @param context
* @return
*/
public static synchronized FanDatabase getInstance(Context context) {
if (null == sInstance) {
sInstance = new FanDatabase(context);
}
return sInstance;
}
/**
* Get SQLiteDatabase Open Helper
*
* @return
*/
public SQLiteOpenHelper getSQLiteOpenHelper() {
return mOpenHelper;
}
/**
* Get Database Connection
*
* @param writeable
* @return
*/
public SQLiteDatabase getDb(boolean writeable) {
if (writeable) {
return mOpenHelper.getWritableDatabase();
} else {
return mOpenHelper.getReadableDatabase();
}
}
/**
* Close Database
*/
public void close() {
if (null != sInstance) {
mOpenHelper.close();
sInstance = null;
}
}
// Create All tables
private static void createAllTables(SQLiteDatabase db) {
db.execSQL(StatusesTable.getCreateSQL());
db.execSQL(StatusesPropertyTable.getCreateSQL());
db.execSQL(UserTable.getCreateSQL());
db.execSQL(DirectMessageTable.getCreateSQL());
db.execSQL(FollowRelationshipTable.getCreateSQL());
db.execSQL(TrendTable.getCreateSQL());
db.execSQL(SavedSearchTable.getCreateSQL());
}
private static void dropAllTables(SQLiteDatabase db) {
db.execSQL(StatusesTable.getDropSQL());
db.execSQL(StatusesPropertyTable.getDropSQL());
db.execSQL(UserTable.getDropSQL());
db.execSQL(DirectMessageTable.getDropSQL());
db.execSQL(FollowRelationshipTable.getDropSQL());
db.execSQL(TrendTable.getDropSQL());
db.execSQL(SavedSearchTable.getDropSQL());
}
private static void resetAllTables(SQLiteDatabase db, int oldVersion,
int newVersion) {
try {
dropAllTables(db);
} catch (SQLException e) {
Log.e(TAG, "resetAllTables ERROR!");
}
createAllTables(db);
}
// indexes
private static void createAllIndexes(SQLiteDatabase db) {
db.execSQL(StatusesTable.getCreateIndexSQL());
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/db2/FanDatabase.java
|
Java
|
asf20
| 3,309
|
package com.ch_linghu.fanfoudroid.db2;
import java.util.zip.CheckedOutputStream;
import android.R.color;
public abstract class FanContent {
/**
* 消息表 消息表存放消息本身
*
* @author phoenix
*
*/
public static class StatusesTable {
public static final String TABLE_NAME = "t_statuses";
public static class Columns {
public static final String ID = "_id";
public static final String STATUS_ID = "status_id";
public static final String AUTHOR_ID = "author_id";
public static final String TEXT = "text";
public static final String SOURCE = "source";
public static final String CREATED_AT = "created_at";
public static final String TRUNCATED = "truncated";
public static final String FAVORITED = "favorited";
public static final String PHOTO_URL = "photo_url";
public static final String IN_REPLY_TO_STATUS_ID = "in_reply_to_status_id";
public static final String IN_REPLY_TO_USER_ID = "in_reply_to_user_id";
public static final String IN_REPLY_TO_SCREEN_NAME = "in_reply_to_screen_name";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.ID
+ " INTEGER PRIMARY KEY, " + Columns.STATUS_ID
+ " TEXT UNIQUE NOT NULL, " + Columns.AUTHOR_ID + " TEXT, "
+ Columns.TEXT + " TEXT, " + Columns.SOURCE + " TEXT, "
+ Columns.CREATED_AT + " INT, " + Columns.TRUNCATED
+ " INT DEFAULT 0, " + Columns.FAVORITED
+ " INT DEFAULT 0, " + Columns.PHOTO_URL + " TEXT, "
+ Columns.IN_REPLY_TO_STATUS_ID + " TEXT, "
+ Columns.IN_REPLY_TO_USER_ID + " TEXT, "
+ Columns.IN_REPLY_TO_SCREEN_NAME + " TEXT " + ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.ID, Columns.STATUS_ID,
Columns.AUTHOR_ID, Columns.TEXT, Columns.SOURCE,
Columns.CREATED_AT, Columns.TRUNCATED, Columns.FAVORITED,
Columns.PHOTO_URL, Columns.IN_REPLY_TO_STATUS_ID,
Columns.IN_REPLY_TO_USER_ID,
Columns.IN_REPLY_TO_SCREEN_NAME };
}
public static String getCreateIndexSQL() {
String createIndexSQL = "CREATE INDEX " + TABLE_NAME + "_idx ON "
+ TABLE_NAME + " ( " + getIndexColumns()[1] + " );";
return createIndexSQL;
}
}
/**
* 消息属性表 每一条消息所属类别、所有者等信息 消息ID(外键) 所有者(随便看看的所有者为空)
* 消息类别(随便看看/首页(自己及自己好友)/个人(仅自己)/收藏/照片)
*
* @author phoenix
*
*/
public static class StatusesPropertyTable {
public static final String TABLE_NAME = "t_statuses_property";
public static class Columns {
public static final String ID = "_id";
public static final String STATUS_ID = "status_id";
public static final String OWNER_ID = "owner_id";
public static final String TYPE = "type";
public static final String SEQUENCE_FLAG = "sequence_flag";
public static final String LOAD_TIME = "load_time";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.ID
+ " INTEGER PRIMARY KEY, " + Columns.STATUS_ID
+ " TEXT NOT NULL, " + Columns.OWNER_ID + " TEXT, "
+ Columns.TYPE + " INT, " + Columns.SEQUENCE_FLAG
+ " INT, " + Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.ID, Columns.STATUS_ID,
Columns.OWNER_ID, Columns.TYPE, Columns.SEQUENCE_FLAG,
Columns.LOAD_TIME };
}
}
/**
* User表 包括User的基本信息和扩展信息(每次获得最新User信息都update进User表)
* 每次更新User表时希望能更新LOAD_TIME,记录最后更新时间
*
* @author phoenix
*
*/
public static class UserTable {
public static final String TABLE_NAME = "t_user";
public static class Columns {
public static final String ID = "_id";
public static final String USER_ID = "user_id";
public static final String USER_NAME = "user_name";
public static final String SCREEN_NAME = "screen_name";
public static final String LOCATION = "location";
public static final String DESCRIPTION = "description";
public static final String URL = "url";
public static final String PROTECTED = "protected";
public static final String PROFILE_IMAGE_URL = "profile_image_url";
public static final String FOLLOWERS_COUNT = "followers_count";
public static final String FRIENDS_COUNT = "friends_count";
public static final String FAVOURITES_COUNT = "favourites_count";
public static final String STATUSES_COUNT = "statuses_count";
public static final String CREATED_AT = "created_at";
public static final String FOLLOWING = "following";
public static final String NOTIFICATIONS = "notifications";
public static final String UTC_OFFSET = "utc_offset";
public static final String LOAD_TIME = "load_time";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.ID
+ " INTEGER PRIMARY KEY, " + Columns.USER_ID
+ " TEXT UNIQUE NOT NULL, " + Columns.USER_NAME
+ " TEXT UNIQUE NOT NULL, " + Columns.SCREEN_NAME
+ " TEXT, " + Columns.LOCATION + " TEXT, "
+ Columns.DESCRIPTION + " TEXT, " + Columns.URL + " TEXT, "
+ Columns.PROTECTED + " INT DEFAULT 0, "
+ Columns.PROFILE_IMAGE_URL + " TEXT "
+ Columns.FOLLOWERS_COUNT + " INT, "
+ Columns.FRIENDS_COUNT + " INT, "
+ Columns.FAVOURITES_COUNT + " INT, "
+ Columns.STATUSES_COUNT + " INT, " + Columns.CREATED_AT
+ " INT, " + Columns.FOLLOWING + " INT DEFAULT 0, "
+ Columns.NOTIFICATIONS + " INT DEFAULT 0, "
+ Columns.UTC_OFFSET + " TEXT, " + Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.ID, Columns.USER_ID,
Columns.USER_NAME, Columns.SCREEN_NAME, Columns.LOCATION,
Columns.DESCRIPTION, Columns.URL, Columns.PROTECTED,
Columns.PROFILE_IMAGE_URL, Columns.FOLLOWERS_COUNT,
Columns.FRIENDS_COUNT, Columns.FAVOURITES_COUNT,
Columns.STATUSES_COUNT, Columns.CREATED_AT,
Columns.FOLLOWING, Columns.NOTIFICATIONS,
Columns.UTC_OFFSET, Columns.LOAD_TIME };
}
}
/**
* 私信表 私信的基本信息
*
* @author phoenix
*
*/
public static class DirectMessageTable {
public static final String TABLE_NAME = "t_direct_message";
public static class Columns {
public static final String ID = "_id";
public static final String MSG_ID = "msg_id";
public static final String TEXT = "text";
public static final String SENDER_ID = "sender_id";
public static final String RECIPINET_ID = "recipinet_id";
public static final String CREATED_AT = "created_at";
public static final String LOAD_TIME = "load_time";
public static final String SEQUENCE_FLAG = "sequence_flag";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.ID
+ " INTEGER PRIMARY KEY, " + Columns.MSG_ID
+ " TEXT UNIQUE NOT NULL, " + Columns.TEXT + " TEXT, "
+ Columns.SENDER_ID + " TEXT, " + Columns.RECIPINET_ID
+ " TEXT, " + Columns.CREATED_AT + " INT, "
+ Columns.SEQUENCE_FLAG + " INT, " + Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.ID, Columns.MSG_ID, Columns.TEXT,
Columns.SENDER_ID, Columns.RECIPINET_ID,
Columns.CREATED_AT, Columns.SEQUENCE_FLAG,
Columns.LOAD_TIME };
}
}
/**
* Follow关系表 某个特定用户的Follow关系(User1 following User2,
* 查找关联某人好友只需限定User1或者User2)
*
* @author phoenix
*
*/
public static class FollowRelationshipTable {
public static final String TABLE_NAME = "t_follow_relationship";
public static class Columns {
public static final String USER1_ID = "user1_id";
public static final String USER2_ID = "user2_id";
public static final String LOAD_TIME = "load_time";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.USER1_ID
+ " TEXT, " + Columns.USER2_ID + " TEXT, "
+ Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.USER1_ID, Columns.USER2_ID,
Columns.LOAD_TIME };
}
}
/**
* 热门话题表 记录每次查询得到的热词
*
* @author phoenix
*
*/
public static class TrendTable {
public static final String TABLE_NAME = "t_trend";
public static class Columns {
public static final String NAME = "name";
public static final String QUERY = "query";
public static final String URL = "url";
public static final String LOAD_TIME = "load_time";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.NAME + " TEXT, "
+ Columns.QUERY + " TEXT, " + Columns.URL + " TEXT, "
+ Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.NAME, Columns.QUERY, Columns.URL,
Columns.LOAD_TIME };
}
}
/**
* 保存搜索表 QUERY_ID(这个ID在API删除保存搜索词时使用)
*
* @author phoenix
*
*/
public static class SavedSearchTable {
public static final String TABLE_NAME = "t_saved_search";
public static class Columns {
public static final String QUERY_ID = "query_id";
public static final String QUERY = "query";
public static final String NAME = "name";
public static final String CREATED_AT = "created_at";
public static final String LOAD_TIME = "load_time";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.QUERY_ID
+ " INT, " + Columns.QUERY + " TEXT, " + Columns.NAME
+ " TEXT, " + Columns.CREATED_AT + " INT, "
+ Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.QUERY_ID, Columns.QUERY,
Columns.NAME, Columns.CREATED_AT, Columns.LOAD_TIME };
}
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/db2/FanContent.java
|
Java
|
asf20
| 11,166
|
/*
* 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;
import com.ch_linghu.fanfoudroid.R;
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(false))
&& !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() {
if (dialog != null){
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();
*/
}
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/WriteActivity.java
|
Java
|
asf20
| 24,239
|
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.List;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.hardware.SensorManager;
import android.util.Log;
import android.widget.RemoteViews;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.service.TwitterService;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.util.TextHelper;
import com.ch_linghu.fanfoudroid.R;
public class FanfouWidget extends AppWidgetProvider {
public final String TAG = "FanfouWidget";
public final String NEXTACTION = "com.ch_linghu.fanfoudroid.FanfouWidget.NEXT";
public final String PREACTION = "com.ch_linghu.fanfoudroid.FanfouWidget.PREV";
private static List<Tweet> tweets;
private SensorManager sensorManager;
private static int position = 0;
class CacheCallback implements ImageLoaderCallback {
private RemoteViews updateViews;
CacheCallback(RemoteViews updateViews) {
this.updateViews = updateViews;
}
@Override
public void refresh(String url, Bitmap bitmap) {
updateViews.setImageViewBitmap(R.id.status_image, bitmap);
}
}
@Override
public void onUpdate(Context context, AppWidgetManager appwidgetmanager,
int[] appWidgetIds) {
Log.d(TAG, "onUpdate");
TwitterService.setWidgetStatus(true);
// if (!isRunning(context, WidgetService.class.getName())) {
// Intent i = new Intent(context, WidgetService.class);
// context.startService(i);
// }
update(context);
}
private void update(Context context) {
fetchMessages();
position = 0;
refreshView(context, NEXTACTION);
}
private TwitterDatabase getDb() {
return TwitterApplication.mDb;
}
public String getUserId() {
return TwitterApplication.getMyselfId(false);
}
private void fetchMessages() {
if (tweets == null) {
tweets = new ArrayList<Tweet>();
} else {
tweets.clear();
}
Cursor cursor = getDb().fetchAllTweets(getUserId(),
StatusTable.TYPE_HOME);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Tweet tweet = StatusTable.parseCursor(cursor);
tweets.add(tweet);
} while (cursor.moveToNext());
}
}
Log.d(TAG, "Tweets size " + tweets.size());
}
private void refreshView(Context context) {
ComponentName fanfouWidget = new ComponentName(context,
FanfouWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(fanfouWidget, buildLogin(context));
}
private RemoteViews buildLogin(Context context) {
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_initial_layout);
updateViews.setTextViewText(R.id.status_text,
TextHelper.getSimpleTweetText("请登录"));
updateViews.setTextViewText(R.id.status_screen_name, "");
updateViews.setTextViewText(R.id.tweet_source, "");
updateViews.setTextViewText(R.id.tweet_created_at, "");
return updateViews;
}
private void refreshView(Context context, String action) {
// 某些情况下,tweets会为null
if (tweets == null) {
fetchMessages();
}
// 防止引发IndexOutOfBoundsException
if (tweets.size() != 0) {
if (action.equals(NEXTACTION)) {
--position;
} else if (action.equals(PREACTION)) {
++position;
}
// Log.d(TAG, "Tweets size =" + tweets.size());
if (position >= tweets.size() || position < 0) {
position = 0;
}
// Log.d(TAG, "position=" + position);
ComponentName fanfouWidget = new ComponentName(context,
FanfouWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(fanfouWidget, buildUpdate(context));
}
}
public RemoteViews buildUpdate(Context context) {
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_initial_layout);
Tweet t = tweets.get(position);
Log.d(TAG, "tweet=" + t);
updateViews.setTextViewText(R.id.status_screen_name, t.screenName);
updateViews.setTextViewText(R.id.status_text,
TextHelper.getSimpleTweetText(t.text));
updateViews.setTextViewText(R.id.tweet_source,
context.getString(R.string.tweet_source_prefix) + t.source);
updateViews.setTextViewText(R.id.tweet_created_at,
DateTimeHelper.getRelativeDate(t.createdAt));
updateViews.setImageViewBitmap(R.id.status_image,
TwitterApplication.mImageLoader.get(t.profileImageUrl,
new CacheCallback(updateViews)));
Intent inext = new Intent(context, FanfouWidget.class);
inext.setAction(NEXTACTION);
PendingIntent pinext = PendingIntent.getBroadcast(context, 0, inext,
PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.btn_next, pinext);
Intent ipre = new Intent(context, FanfouWidget.class);
ipre.setAction(PREACTION);
PendingIntent pipre = PendingIntent.getBroadcast(context, 0, ipre,
PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.btn_pre, pipre);
Intent write = WriteActivity.createNewTweetIntent("");
PendingIntent piwrite = PendingIntent.getActivity(context, 0, write,
PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.write_message, piwrite);
Intent home = TwitterActivity.createIntent(context);
PendingIntent pihome = PendingIntent.getActivity(context, 0, home,
PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.logo_image, pihome);
Intent status = StatusActivity.createIntent(t);
PendingIntent pistatus = PendingIntent.getActivity(context, 0, status,
PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.main_body, pistatus);
return updateViews;
}
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "OnReceive");
// FIXME: NullPointerException
Log.i(TAG, context.getApplicationContext().toString());
if (!TwitterApplication.mApi.isLoggedIn()) {
refreshView(context);
} else {
super.onReceive(context, intent);
String action = intent.getAction();
if (NEXTACTION.equals(action) || PREACTION.equals(action)) {
refreshView(context, intent.getAction());
} else if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
update(context);
}
}
}
/**
*
* @param c
* @param serviceName
* @return
*/
@Deprecated
public boolean isRunning(Context c, String serviceName) {
ActivityManager myAM = (ActivityManager) c
.getSystemService(Context.ACTIVITY_SERVICE);
ArrayList<RunningServiceInfo> runningServices = (ArrayList<RunningServiceInfo>) myAM
.getRunningServices(40);
// 获取最多40个当前正在运行的服务,放进ArrList里,以现在手机的处理能力,要是超过40个服务,估计已经卡死,所以不用考虑超过40个该怎么办
int servicesSize = runningServices.size();
for (int i = 0; i < servicesSize; i++)// 循环枚举对比
{
if (runningServices.get(i).service.getClassName().toString()
.equals(serviceName)) {
return true;
}
}
return false;
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
Log.d(TAG, "onDeleted");
}
@Override
public void onEnabled(Context context) {
Log.d(TAG, "onEnabled");
TwitterService.setWidgetStatus(true);
}
@Override
public void onDisabled(Context context) {
Log.d(TAG, "onDisabled");
TwitterService.setWidgetStatus(false);
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/FanfouWidget.java
|
Java
|
asf20
| 8,139
|
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* AbstractTwitterListBaseLine用于抽象tweets List的展现
* UI基本元素要求:一个ListView用于tweet列表
* 一个ProgressText用于提示信息
*/
package com.ch_linghu.fanfoudroid.ui.base;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.DmActivity;
import com.ch_linghu.fanfoudroid.MentionActivity;
import com.ch_linghu.fanfoudroid.ProfileActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.StatusActivity;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.WriteActivity;
import com.ch_linghu.fanfoudroid.WriteDmActivity;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.task.TweetCommonTask;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter;
public abstract class TwitterListBaseActivity extends BaseActivity implements
Refreshable {
static final String TAG = "TwitterListBaseActivity";
protected TextView mProgressText;
protected Feedback mFeedback;
protected NavBar mNavbar;
protected static final int STATE_ALL = 0;
protected static final String SIS_RUNNING_KEY = "running";
// Tasks.
protected GenericTask mFavTask;
private TaskListener mFavTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "FavoriteTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
onFavSuccess();
} else if (result == TaskResult.IO_ERROR) {
onFavFailure();
}
}
};
static final int DIALOG_WRITE_ID = 0;
abstract protected int getLayoutId();
abstract protected ListView getTweetList();
abstract protected TweetAdapter getTweetAdapter();
abstract protected void setupState();
abstract protected String getActivityTitle();
abstract protected boolean useBasicMenu();
abstract protected Tweet getContextItemTweet(int position);
abstract protected void updateTweet(Tweet tweet);
public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1;
// public static final int CONTEXT_AT_ID = Menu.FIRST + 2;
public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3;
public static final int CONTEXT_DM_ID = Menu.FIRST + 4;
public static final int CONTEXT_MORE_ID = Menu.FIRST + 5;
public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6;
public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7;
/**
* 如果增加了Context Menu常量的数量,则必须重载此方法, 以保证其他人使用常量时不产生重复
*
* @return 最大的Context Menu常量
*/
protected int getLastContextMenuId() {
return CONTEXT_DEL_FAV_ID;
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState)) {
setContentView(getLayoutId());
mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this);
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
mPreferences.getInt(Preferences.TWITTER_ACTIVITY_STATE_KEY,
STATE_ALL);
// 提示栏
mProgressText = (TextView) findViewById(R.id.progress_text);
setupState();
registerForContextMenu(getTweetList());
registerOnClickListener(getTweetList());
return true;
} else {
return false;
}
}
@Override
protected void onResume() {
super.onResume();
checkIsLogedIn();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
mFavTask.cancel(true);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
Log.d("FLING", "onContextItemSelected");
super.onCreateContextMenu(menu, v, menuInfo);
if (useBasicMenu()) {
AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
Tweet tweet = getContextItemTweet(info.position);
if (tweet == null) {
Log.w(TAG, "Selected item not available.");
return;
}
menu.add(
0,
CONTEXT_MORE_ID,
0,
tweet.screenName
+ getResources().getString(
R.string.cmenu_user_profile_prefix));
menu.add(0, CONTEXT_REPLY_ID, 0, R.string.cmenu_reply);
menu.add(0, CONTEXT_RETWEET_ID, 0, R.string.cmenu_retweet);
menu.add(0, CONTEXT_DM_ID, 0, R.string.cmenu_direct_message);
if (tweet.favorited.equals("true")) {
menu.add(0, CONTEXT_DEL_FAV_ID, 0, R.string.cmenu_del_fav);
} else {
menu.add(0, CONTEXT_ADD_FAV_ID, 0, R.string.cmenu_add_fav);
}
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
Tweet tweet = getContextItemTweet(info.position);
if (tweet == null) {
Log.w(TAG, "Selected item not available.");
return super.onContextItemSelected(item);
}
switch (item.getItemId()) {
case CONTEXT_MORE_ID:
launchActivity(ProfileActivity.createIntent(tweet.userId));
return true;
case CONTEXT_REPLY_ID: {
// TODO: this isn't quite perfect. It leaves extra empty spaces if
// you perform the reply action again.
Intent intent = WriteActivity.createNewReplyIntent(tweet.text,
tweet.screenName, tweet.id);
startActivity(intent);
return true;
}
case CONTEXT_RETWEET_ID:
Intent intent = WriteActivity.createNewRepostIntent(this,
tweet.text, tweet.screenName, tweet.id);
startActivity(intent);
return true;
case CONTEXT_DM_ID:
launchActivity(WriteDmActivity.createIntent(tweet.userId));
return true;
case CONTEXT_ADD_FAV_ID:
doFavorite("add", tweet.id);
return true;
case CONTEXT_DEL_FAV_ID:
doFavorite("del", tweet.id);
return true;
default:
return super.onContextItemSelected(item);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case OPTIONS_MENU_ID_TWEETS:
launchActivity(TwitterActivity.createIntent(this));
return true;
case OPTIONS_MENU_ID_REPLIES:
launchActivity(MentionActivity.createIntent(this));
return true;
case OPTIONS_MENU_ID_DM:
launchActivity(DmActivity.createIntent());
return true;
}
return super.onOptionsItemSelected(item);
}
protected void draw() {
getTweetAdapter().refresh();
}
protected void goTop() {
getTweetList().setSelection(1);
}
protected void adapterRefresh() {
getTweetAdapter().refresh();
}
// for HasFavorite interface
public void doFavorite(String action, String id) {
if (!TextUtils.isEmpty(id)) {
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mFavTask = new TweetCommonTask.FavoriteTask(this);
mFavTask.setListener(mFavTaskListener);
TaskParams params = new TaskParams();
params.put("action", action);
params.put("id", id);
mFavTask.execute(params);
}
}
}
public void onFavSuccess() {
// updateProgress(getString(R.string.refreshing));
adapterRefresh();
}
public void onFavFailure() {
// updateProgress(getString(R.string.refreshing));
}
protected void specialItemClicked(int position) {
}
protected void registerOnClickListener(ListView listView) {
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Tweet tweet = getContextItemTweet(position);
if (tweet == null) {
Log.w(TAG, "Selected item not available.");
specialItemClicked(position);
} else {
launchActivity(StatusActivity.createIntent(tweet));
}
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
if(getTweetList() != null) {
int lastPosition = getTweetList().getFirstVisiblePosition();
outState.putInt("LAST_POSITION", lastPosition);
}
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if(getTweetList() != null) {
int lastPosition = savedInstanceState.getInt("LAST_POSITION");
getTweetList().setSelection(lastPosition);
}
}
@Override
public void doRetrieve() {
// TODO Auto-generated method stub
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/ui/base/TwitterListBaseActivity.java
|
Java
|
asf20
| 9,965
|
package com.ch_linghu.fanfoudroid.ui.base;
import android.app.ListActivity;
/**
* TODO: 准备重构现有的几个ListActivity
*
* 目前几个ListActivity存在的问题是 : 1. 因为要实现[刷新]这些功能, 父类设定了子类继承时必须要实现的方法,
* 而刷新/获取其实更多的时候可以理解成是ListView的层面, 这在于讨论到底是一个"可刷新的Activity"
* 还是一个拥有"可刷新的ListView"的Activity, 如果改成后者, 则只要在父类拥有一个实现了可刷新接口的ListView即可,
* 而无需强制要求子类去直接实现某些方法. 2. 父类过于专制,
* 比如getLayoutId()等抽象方法的存在只是为了在父类进行setContentView, 而此类方法可以下放到子类去自行实现, 诸如此类的,
* 应该下放给子类更自由的空间. 理想状态为不使用抽象类. 3. 随着功能扩展, 需要将几个不同的ListActivity子类重复的部分重新抽象到父类来,
* 已减少代码重复. 4. TwitterList和UserList代码存在重复现象, 可抽象. 5.
* TwitterList目前过于依赖Cursor类型的List, 而没有Array类型的抽象类.
*
*/
public class BaseListActivity extends ListActivity {
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/ui/base/BaseListActivity.java
|
Java
|
asf20
| 1,225
|
package com.ch_linghu.fanfoudroid.ui.base;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.ch_linghu.fanfoudroid.AboutActivity;
import com.ch_linghu.fanfoudroid.LoginActivity;
import com.ch_linghu.fanfoudroid.PreferencesActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.fanfou.Weibo;
import com.ch_linghu.fanfoudroid.service.TwitterService;
/**
* A BaseActivity has common routines and variables for an Activity that
* contains a list of tweets and a text input field.
*
* Not the cleanest design, but works okay for several Activities in this app.
*/
public class BaseActivity extends Activity {
private static final String TAG = "BaseActivity";
protected SharedPreferences mPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_onCreate(savedInstanceState);
}
// 因为onCreate方法无法返回状态,因此无法进行状态判断,
// 为了能对上层返回的信息进行判断处理,我们使用_onCreate代替真正的
// onCreate进行工作。onCreate仅在顶层调用_onCreate。
protected boolean _onCreate(Bundle savedInstanceState) {
if (TwitterApplication.mPref.getBoolean(
Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
if (!checkIsLogedIn()) {
return false;
} else {
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
mPreferences = TwitterApplication.mPref; // PreferenceManager.getDefaultSharedPreferences(this);
return true;
}
}
protected void handleLoggedOut() {
if (isTaskRoot()) {
showLogin();
} else {
setResult(RESULT_LOGOUT);
}
finish();
}
public TwitterDatabase getDb() {
return TwitterApplication.mDb;
}
public Weibo getApi() {
return TwitterApplication.mApi;
}
public SharedPreferences getPreferences() {
return mPreferences;
}
@Override
protected void onDestroy() {
super.onDestroy();
}
protected boolean isLoggedIn() {
return getApi().isLoggedIn();
}
private static final int RESULT_LOGOUT = RESULT_FIRST_USER + 1;
// Retrieve interface
// public ImageManager getImageManager() {
// return TwitterApplication.mImageManager;
// }
private void _logout() {
TwitterService.unschedule(BaseActivity.this);
getDb().clearData();
getApi().reset();
// Clear SharedPreferences
SharedPreferences.Editor editor = mPreferences.edit();
editor.clear();
editor.commit();
// TODO: 提供用户手动情况所有缓存选项
TwitterApplication.mImageLoader.getImageManager().clear();
// TODO: cancel notifications.
TwitterService.unschedule(BaseActivity.this);
handleLoggedOut();
}
public void logout() {
Dialog dialog = new AlertDialog.Builder(BaseActivity.this)
.setTitle("提示").setMessage("确实要注销吗?")
.setPositiveButton("确定", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
_logout();
}
}).setNegativeButton("取消", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create();
dialog.show();
}
protected void showLogin() {
Intent intent = new Intent(this, LoginActivity.class);
// TODO: might be a hack?
intent.putExtra(Intent.EXTRA_INTENT, getIntent());
startActivity(intent);
}
protected void manageUpdateChecks() {
// 检查后台更新状态设置
boolean isUpdateEnabled = mPreferences.getBoolean(
Preferences.CHECK_UPDATES_KEY, false);
if (isUpdateEnabled) {
TwitterService.schedule(this);
} else if (!TwitterService.isWidgetEnabled()) {
TwitterService.unschedule(this);
}
// 检查强制竖屏设置
boolean isOrientationPortrait = mPreferences.getBoolean(
Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false);
if (isOrientationPortrait) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
}
// Menus.
protected static final int OPTIONS_MENU_ID_LOGOUT = 1;
protected static final int OPTIONS_MENU_ID_PREFERENCES = 2;
protected static final int OPTIONS_MENU_ID_ABOUT = 3;
protected static final int OPTIONS_MENU_ID_SEARCH = 4;
protected static final int OPTIONS_MENU_ID_REPLIES = 5;
protected static final int OPTIONS_MENU_ID_DM = 6;
protected static final int OPTIONS_MENU_ID_TWEETS = 7;
protected static final int OPTIONS_MENU_ID_TOGGLE_REPLIES = 8;
protected static final int OPTIONS_MENU_ID_FOLLOW = 9;
protected static final int OPTIONS_MENU_ID_UNFOLLOW = 10;
protected static final int OPTIONS_MENU_ID_IMAGE_CAPTURE = 11;
protected static final int OPTIONS_MENU_ID_PHOTO_LIBRARY = 12;
protected static final int OPTIONS_MENU_ID_EXIT = 13;
/**
* 如果增加了Option Menu常量的数量,则必须重载此方法, 以保证其他人使用常量时不产生重复
*
* @return 最大的Option Menu常量
*/
protected int getLastOptionMenuId() {
return OPTIONS_MENU_ID_EXIT;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// SubMenu submenu =
// menu.addSubMenu(R.string.write_label_insert_picture);
// submenu.setIcon(android.R.drawable.ic_menu_gallery);
//
// submenu.add(0, OPTIONS_MENU_ID_IMAGE_CAPTURE, 0,
// R.string.write_label_take_a_picture);
// submenu.add(0, OPTIONS_MENU_ID_PHOTO_LIBRARY, 0,
// R.string.write_label_choose_a_picture);
//
// MenuItem item = menu.add(0, OPTIONS_MENU_ID_SEARCH, 0,
// R.string.omenu_search);
// item.setIcon(android.R.drawable.ic_search_category_default);
// item.setAlphabeticShortcut(SearchManager.MENU_KEY);
MenuItem item;
item = menu.add(0, OPTIONS_MENU_ID_PREFERENCES, 0,
R.string.omenu_settings);
item.setIcon(android.R.drawable.ic_menu_preferences);
item = menu.add(0, OPTIONS_MENU_ID_LOGOUT, 0, R.string.omenu_signout);
item.setIcon(android.R.drawable.ic_menu_revert);
item = menu.add(0, OPTIONS_MENU_ID_ABOUT, 0, R.string.omenu_about);
item.setIcon(android.R.drawable.ic_menu_info_details);
item = menu.add(0, OPTIONS_MENU_ID_EXIT, 0, R.string.omenu_exit);
item.setIcon(android.R.drawable.ic_menu_close_clear_cancel);
return true;
}
protected static final int REQUEST_CODE_LAUNCH_ACTIVITY = 0;
protected static final int REQUEST_CODE_PREFERENCES = 1;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case OPTIONS_MENU_ID_LOGOUT:
logout();
return true;
case OPTIONS_MENU_ID_SEARCH:
onSearchRequested();
return true;
case OPTIONS_MENU_ID_PREFERENCES:
Intent launchPreferencesIntent = new Intent().setClass(this,
PreferencesActivity.class);
startActivityForResult(launchPreferencesIntent,
REQUEST_CODE_PREFERENCES);
return true;
case OPTIONS_MENU_ID_ABOUT:
// AboutDialog.show(this);
Intent intent = new Intent().setClass(this, AboutActivity.class);
startActivity(intent);
return true;
case OPTIONS_MENU_ID_EXIT:
exit();
return true;
}
return super.onOptionsItemSelected(item);
}
protected void exit() {
TwitterService.unschedule(this);
Intent i = new Intent(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
startActivity(i);
}
protected void launchActivity(Intent intent) {
// TODO: probably don't need this result chaining to finish upon logout.
// since the subclasses have to check in onResume.
startActivityForResult(intent, REQUEST_CODE_LAUNCH_ACTIVITY);
}
protected void launchDefaultActivity() {
Intent intent = new Intent();
intent.setClass(this, TwitterActivity.class);
startActivity(intent);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_PREFERENCES && resultCode == RESULT_OK) {
manageUpdateChecks();
} else if (requestCode == REQUEST_CODE_LAUNCH_ACTIVITY
&& resultCode == RESULT_LOGOUT) {
Log.d(TAG, "Result logout.");
handleLoggedOut();
}
}
protected boolean checkIsLogedIn() {
if (!getApi().isLoggedIn()) {
Log.d(TAG, "Not logged in.");
handleLoggedOut();
return false;
}
return true;
}
public static boolean isTrue(Bundle bundle, String key) {
return bundle != null && bundle.containsKey(key)
&& bundle.getBoolean(key);
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/ui/base/BaseActivity.java
|
Java
|
asf20
| 9,412
|
package com.ch_linghu.fanfoudroid.ui.base;
public interface Refreshable {
void doRetrieve();
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/ui/base/Refreshable.java
|
Java
|
asf20
| 97
|
package com.ch_linghu.fanfoudroid.ui.base;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.SearchActivity;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.WriteActivity;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.MenuDialog;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
/**
* @deprecated 使用 {@link NavBar} 代替
*/
public class WithHeaderActivity extends BaseActivity {
private static final String TAG = "WithHeaderActivity";
public static final int HEADER_STYLE_HOME = 1;
public static final int HEADER_STYLE_WRITE = 2;
public static final int HEADER_STYLE_BACK = 3;
public static final int HEADER_STYLE_SEARCH = 4;
protected ImageView refreshButton;
protected ImageButton searchButton;
protected ImageButton writeButton;
protected TextView titleButton;
protected Button backButton;
protected ImageButton homeButton;
protected MenuDialog dialog;
protected EditText searchEdit;
protected Feedback mFeedback;
// FIXME: 刷新动画二选一, DELETE ME
protected AnimationDrawable mRefreshAnimation;
protected ProgressBar mProgress = null;
protected ProgressBar mLoadingProgress = null;
// 搜索硬按键行为
@Override
public boolean onSearchRequested() {
Intent intent = new Intent();
intent.setClass(this, SearchActivity.class);
startActivity(intent);
return true;
}
// LOGO按钮
protected void addTitleButton() {
titleButton = (TextView) findViewById(R.id.title);
titleButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int top = titleButton.getTop();
int height = titleButton.getHeight();
int x = top + height;
if (null == dialog) {
Log.d(TAG, "Create menu dialog.");
dialog = new MenuDialog(WithHeaderActivity.this);
dialog.bindEvent(WithHeaderActivity.this);
dialog.setPosition(-1, x);
}
// toggle dialog
if (dialog.isShowing()) {
dialog.dismiss(); // 没机会触发
} else {
dialog.show();
}
}
});
}
protected void setHeaderTitle(String title) {
titleButton.setBackgroundDrawable(new BitmapDrawable());
titleButton.setText(title);
LayoutParams lp = new LayoutParams(
android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
lp.setMargins(3, 12, 0, 0);
titleButton.setLayoutParams(lp);
// 中文粗体
TextPaint tp = titleButton.getPaint();
tp.setFakeBoldText(true);
}
protected void setHeaderTitle(int resource) {
titleButton.setBackgroundResource(resource);
}
// 刷新
protected void addRefreshButton() {
final Activity that = this;
refreshButton = (ImageView) findViewById(R.id.top_refresh);
// FIXME: 暂时取消旋转效果, 测试ProgressBar
// refreshButton.setBackgroundResource(R.drawable.top_refresh);
// mRefreshAnimation = (AnimationDrawable)
// refreshButton.getBackground();
// FIXME: DELETE ME
mProgress = (ProgressBar) findViewById(R.id.progress_bar);
mLoadingProgress = (ProgressBar) findViewById(R.id.top_refresh_progressBar);
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
refreshButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (that instanceof Refreshable) {
((Refreshable) that).doRetrieve();
} else {
Log.e(TAG, "The current view " + that.getClass().getName()
+ " cann't be retrieved");
}
}
});
}
/**
* @param v
* @deprecated use {@link WithHeaderActivity#setRefreshAnimation(boolean)}
*/
protected void animRotate(View v) {
setRefreshAnimation(true);
}
/**
* @param progress
* 0~100
* @deprecated use feedback
*/
public void setGlobalProgress(int progress) {
if (null != mProgress) {
mProgress.setProgress(progress);
}
}
/**
* Start/Stop Top Refresh Button's Animation
*
* @param animate
* start or stop
* @deprecated use feedback
*/
public void setRefreshAnimation(boolean animate) {
if (mRefreshAnimation != null) {
if (animate) {
mRefreshAnimation.start();
} else {
mRefreshAnimation.setVisible(true, true); // restart
mRefreshAnimation.start(); // goTo frame 0
mRefreshAnimation.stop();
}
} else {
Log.w(TAG, "mRefreshAnimation is null");
}
}
// 搜索
protected void addSearchButton() {
searchButton = (ImageButton) findViewById(R.id.search);
searchButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// // 旋转动画
// Animation anim = AnimationUtils.loadAnimation(v.getContext(),
// R.anim.scale_lite);
// v.startAnimation(anim);
// go to SearchActivity
startSearch();
}
});
}
// 这个方法会在SearchActivity里重写
protected boolean startSearch() {
Intent intent = new Intent();
intent.setClass(this, SearchActivity.class);
startActivity(intent);
return true;
}
// 搜索框
protected void addSearchBox() {
searchEdit = (EditText) findViewById(R.id.search_edit);
}
// 撰写
protected void addWriteButton() {
writeButton = (ImageButton) findViewById(R.id.writeMessage);
writeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// 动画
Animation anim = AnimationUtils.loadAnimation(v.getContext(),
R.anim.scale_lite);
v.startAnimation(anim);
// forward to write activity
Intent intent = new Intent();
intent.setClass(v.getContext(), WriteActivity.class);
v.getContext().startActivity(intent);
}
});
}
// 回首页
protected void addHomeButton() {
homeButton = (ImageButton) findViewById(R.id.home);
homeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// 动画
Animation anim = AnimationUtils.loadAnimation(v.getContext(),
R.anim.scale_lite);
v.startAnimation(anim);
// forward to TwitterActivity
Intent intent = new Intent();
intent.setClass(v.getContext(), TwitterActivity.class);
v.getContext().startActivity(intent);
}
});
}
// 返回
protected void addBackButton() {
backButton = (Button) findViewById(R.id.top_back);
// 中文粗体
// TextPaint tp = backButton.getPaint();
// tp.setFakeBoldText(true);
backButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Go back to previous activity
finish();
}
});
}
protected void initHeader(int style) {
// FIXME: android 1.6似乎不支持addHeaderView中使用的方法
// 来增加header,造成header无法显示和使用。
// 改用在layout xml里include的方法来确保显示
switch (style) {
case HEADER_STYLE_HOME:
// addHeaderView(R.layout.header);
addTitleButton();
addWriteButton();
addSearchButton();
addRefreshButton();
break;
case HEADER_STYLE_BACK:
// addHeaderView(R.layout.header_back);
addBackButton();
addWriteButton();
addSearchButton();
addRefreshButton();
break;
case HEADER_STYLE_WRITE:
// addHeaderView(R.layout.header_write);
addBackButton();
// addHomeButton();
break;
case HEADER_STYLE_SEARCH:
// addHeaderView(R.layout.header_search);
addBackButton();
addSearchBox();
addSearchButton();
break;
}
}
private void addHeaderView(int resource) {
// find content root view
ViewGroup root = (ViewGroup) getWindow().getDecorView();
ViewGroup content = (ViewGroup) root.getChildAt(0);
View header = View.inflate(WithHeaderActivity.this, resource, null);
// LayoutParams params = new
// LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);
content.addView(header, 0);
}
@Override
protected void onDestroy() {
// dismiss dialog before destroy
// to avoid android.view.WindowLeaked Exception
if (dialog != null) {
dialog.dismiss();
}
super.onDestroy();
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/ui/base/WithHeaderActivity.java
|
Java
|
asf20
| 8,671
|
package com.ch_linghu.fanfoudroid.ui.base;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.data.User;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskManager;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback;
import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter;
import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter;
public abstract class UserArrayBaseActivity extends UserListBaseActivity {
static final String TAG = "UserArrayBaseActivity";
// Views.
//protected PullToRefreshListView mUserList;
protected ListView mUserList;
protected UserArrayAdapter mUserListAdapter;
protected TextView loadMoreBtn;
protected ProgressBar loadMoreGIF;
protected TextView loadMoreBtnTop;
protected ProgressBar loadMoreGIFTop;
// Tasks.
protected TaskManager taskManager = new TaskManager();
private GenericTask mRetrieveTask;
private GenericTask mFollowersRetrieveTask;
private GenericTask mGetMoreTask;// 每次100用户
private static class State {
State(UserArrayBaseActivity activity) {
allUserList = activity.allUserList;
}
public ArrayList<com.ch_linghu.fanfoudroid.data.User> allUserList;
}
public abstract Paging getCurrentPage();// 加载
public abstract Paging getNextPage();// 加载
// protected abstract String[] getIds();
protected abstract List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers(
String userId, Paging page) throws HttpException;
private ArrayList<com.ch_linghu.fanfoudroid.data.User> allUserList;
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)) {
State state = (State) getLastNonConfigurationInstance();
if (state != null){
allUserList = state.allUserList;
draw();
}else{
doRetrieve();// 加载第一页
}
return true;
} else {
return false;
}
}
@Override
protected String getUserId() {
// TODO Auto-generated method stub
return null;
}
@Override
public void doRetrieve() {
Log.d(TAG, "Attempting retrieve.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mRetrieveTask = new RetrieveTask();
mRetrieveTask.setFeedback(mFeedback);
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.execute();
// Add Task to manager
taskManager.addTask(mRetrieveTask);
}
}
private TaskListener mRetrieveTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "RetrieveTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
draw();
}
//mUserList.onRefreshComplete();
updateProgress("");
}
@Override
public void onPreExecute(GenericTask task) {
onRetrieveBegin();
}
@Override
public void onProgressUpdate(GenericTask task, Object param) {
Log.d(TAG, "onProgressUpdate");
draw();
}
};
public void updateProgress(String progress) {
mProgressText.setText(progress);
}
public void onRetrieveBegin() {
updateProgress(getString(R.string.page_status_refreshing));
}
/**
* TODO:从API获取当前Followers
*
* @author Dino
*
*/
private class RetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
Log.d(TAG, "load RetrieveTask");
List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null;
try {
usersList = getUsers(getUserId(), getCurrentPage());
} catch (HttpException e) {
e.printStackTrace();
return TaskResult.IO_ERROR;
}
publishProgress(SimpleFeedback.calProgressBySize(40, 20, usersList));
allUserList.clear();
for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
User u = User.create(user);
allUserList.add(u);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
return TaskResult.OK;
}
}
@Override
protected int getLayoutId() {
return R.layout.follower;
}
@Override
protected void setupState() {
setTitle(getActivityTitle());
mUserList = (ListView) findViewById(R.id.follower_list);
setupListHeader(true);
mUserListAdapter = new UserArrayAdapter(this);
mUserList.setAdapter(mUserListAdapter);
allUserList = new ArrayList<com.ch_linghu.fanfoudroid.data.User>();
}
@Override
protected String getActivityTitle() {
// TODO Auto-generated method stub
return null;
}
@Override
protected boolean useBasicMenu() {
return true;
}
@Override
protected User getContextItemUser(int position) {
// position = position - 1;
Log.d(TAG, "list position:" + position);
// 加入footer跳过footer
if (position < mUserListAdapter.getCount()) {
User item = (User) mUserListAdapter.getItem(position);
if (item == null) {
return null;
} else {
return item;
}
} else {
return null;
}
}
/**
* TODO:不知道啥用
*/
@Override
protected void updateTweet(Tweet tweet) {
// TODO Auto-generated method stub
}
@Override
protected ListView getUserList() {
return mUserList;
}
@Override
protected TweetAdapter getUserAdapter() {
return mUserListAdapter;
}
/**
* 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用
*/
protected void setupListHeader(boolean addFooter) {
// Add footer to Listview
View footer = View.inflate(this, R.layout.listview_footer, null);
mUserList.addFooterView(footer, null, true);
// mUserList.setOnRefreshListener(new OnRefreshListener() {
//
// @Override
// public void onRefresh() {
// doRetrieve();
//
// }
// });
// Find View
loadMoreBtn = (TextView) findViewById(R.id.ask_for_more);
loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar);
}
@Override
protected void specialItemClicked(int position) {
if (position == mUserList.getCount() - 1) {
// footer
loadMoreGIF.setVisibility(View.VISIBLE);
doGetMore();
}
}
public void doGetMore() {
Log.d(TAG, "Attempting getMore.");
mFeedback.start("");
if (mGetMoreTask != null
&& mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mGetMoreTask = new GetMoreTask();
mGetMoreTask.setListener(getMoreListener);
mGetMoreTask.execute();
// Add Task to manager
taskManager.addTask(mGetMoreTask);
}
}
private TaskListener getMoreListener = new TaskAdapter() {
@Override
public String getName() {
return "getMore";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
super.onPostExecute(task, result);
draw();
mFeedback.success("");
loadMoreGIF.setVisibility(View.GONE);
}
};
/**
* TODO:需要重写,获取下一批用户,按页分100页一次
*
* @author Dino
*
*/
private class GetMoreTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
Log.d(TAG, "load RetrieveTask");
List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null;
try {
usersList = getUsers(getUserId(), getNextPage());
mFeedback.update(60);
} catch (HttpException e) {
e.printStackTrace();
return TaskResult.IO_ERROR;
}
// 将获取到的数据(保存/更新)到数据库
getDb().syncWeiboUsers(usersList);
mFeedback.update(100 - (int) Math.floor(usersList.size() * 2));
for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
allUserList.add(User.create(user));
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
mFeedback.update(99);
return TaskResult.OK;
}
}
public void draw() {
mUserListAdapter.refresh(allUserList);
}
@Override
public Object onRetainNonConfigurationInstance() {
return createState();
}
private synchronized State createState() {
return new State(this);
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/ui/base/UserArrayBaseActivity.java
|
Java
|
asf20
| 9,000
|
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid.ui.base;
import java.util.ArrayList;
import java.util.List;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.data.User;
import com.ch_linghu.fanfoudroid.db.UserInfoTable;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskManager;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback;
import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter;
import com.ch_linghu.fanfoudroid.ui.module.UserCursorAdapter;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
/**
* TwitterCursorBaseLine用于带有静态数据来源(对应数据库的,与twitter表同构的特定表)的展现
*/
public abstract class UserCursorBaseActivity extends UserListBaseActivity {
/**
* 第一种方案:(采取第一种) 暂不放在数据库中,直接从Api读取。
*
* 第二种方案: 麻烦的是api数据与数据库同步,当收听人数比较多的时候,一次性读取太费流量 按照饭否api每次分页100人
* 当收听数<100时先从数据库一次性根据API返回的ID列表读取数据,如果数据库中的收听数<总数,那么从API中读取所有用户信息并同步到数据库中。
* 当收听数>100时采取分页加载,先按照id
* 获取数据库里前100用户,如果用户数量<100则从api中加载,从page=1开始下载,同步到数据库中,单击更多继续从数据库中加载
* 当数据库中的数据读取到最后一页后,则从api中加载并更新到数据库中。 单击刷新按钮则从api加载并同步到数据库中
*
*/
static final String TAG = "UserCursorBaseActivity";
// Views.
protected ListView mUserList;
protected UserCursorAdapter mUserListAdapter;
protected TextView loadMoreBtn;
protected ProgressBar loadMoreGIF;
protected TextView loadMoreBtnTop;
protected ProgressBar loadMoreGIFTop;
protected static int lastPosition = 0;
// Tasks.
protected TaskManager taskManager = new TaskManager();
private GenericTask mRetrieveTask;
private GenericTask mFollowersRetrieveTask;
private GenericTask mGetMoreTask;// 每次十个用户
protected abstract String getUserId();// 获得用户id
private TaskListener mRetrieveTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "RetrieveTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
SharedPreferences.Editor editor = getPreferences().edit();
editor.putLong(Preferences.LAST_TWEET_REFRESH_KEY,
DateTimeHelper.getNowTime());
editor.commit();
// TODO: 1. StatusType(DONE) ; 2. 只有在取回的数据大于MAX时才做GC,
// 因为小于时可以保证数据的连续性
// FIXME: gc需要带owner
// getDb().gc(getDatabaseType()); // GC
draw();
goTop();
} else {
// Do nothing.
}
// loadMoreGIFTop.setVisibility(View.GONE);
updateProgress("");
}
@Override
public void onPreExecute(GenericTask task) {
onRetrieveBegin();
}
@Override
public void onProgressUpdate(GenericTask task, Object param) {
Log.d(TAG, "onProgressUpdate");
draw();
}
};
private TaskListener mFollowerRetrieveTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "FollowerRetrieve";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
SharedPreferences sp = getPreferences();
SharedPreferences.Editor editor = sp.edit();
editor.putLong(Preferences.LAST_FOLLOWERS_REFRESH_KEY,
DateTimeHelper.getNowTime());
editor.commit();
} else {
// Do nothing.
}
}
};
// Refresh data at startup if last refresh was this long ago or greater.
private static final long REFRESH_THRESHOLD = 5 * 60 * 1000;
// Refresh followers if last refresh was this long ago or greater.
private static final long FOLLOWERS_REFRESH_THRESHOLD = 12 * 60 * 60 * 1000;
abstract protected Cursor fetchUsers();
public abstract int getDatabaseType();
public abstract String fetchMaxId();
public abstract String fetchMinId();
public abstract List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers()
throws HttpException;
public abstract void addUsers(
ArrayList<com.ch_linghu.fanfoudroid.data.User> tusers);
// public abstract List<Status> getMessageSinceId(String maxId)
// throws WeiboException;
public abstract List<com.ch_linghu.fanfoudroid.fanfou.User> getUserSinceId(
String maxId) throws HttpException;
public abstract List<Status> getMoreMessageFromId(String minId)
throws HttpException;
public abstract Paging getNextPage();// 下一页数
public abstract Paging getCurrentPage();// 当前页数
protected abstract String[] getIds();
public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1;
// public static final int CONTEXT_AT_ID = Menu.FIRST + 2;
public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3;
public static final int CONTEXT_DM_ID = Menu.FIRST + 4;
public static final int CONTEXT_MORE_ID = Menu.FIRST + 5;
public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6;
public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7;
@Override
protected void setupState() {
Cursor cursor;
cursor = fetchUsers(); //
setTitle(getActivityTitle());
startManagingCursor(cursor);
mUserList = (ListView) findViewById(R.id.follower_list);
// TODO: 需处理没有数据时的情况
Log.d("LDS", cursor.getCount() + " cursor count");
setupListHeader(true);
mUserListAdapter = new UserCursorAdapter(this, cursor);
mUserList.setAdapter(mUserListAdapter);
// ? registerOnClickListener(mTweetList);
}
/**
* 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用
*/
protected void setupListHeader(boolean addFooter) {
// Add footer to Listview
View footer = View.inflate(this, R.layout.listview_footer, null);
mUserList.addFooterView(footer, null, true);
// Find View
loadMoreBtn = (TextView) findViewById(R.id.ask_for_more);
loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar);
// loadMoreBtnTop = (TextView)findViewById(R.id.ask_for_more_header);
// loadMoreGIFTop =
// (ProgressBar)findViewById(R.id.rectangleProgressBar_header);
// loadMoreAnimation = (AnimationDrawable)
// loadMoreGIF.getIndeterminateDrawable();
}
@Override
protected void specialItemClicked(int position) {
if (position == mUserList.getCount() - 1) {
// footer
loadMoreGIF.setVisibility(View.VISIBLE);
doGetMore();
}
}
@Override
protected int getLayoutId() {
return R.layout.follower;
}
@Override
protected ListView getUserList() {
return mUserList;
}
@Override
protected TweetAdapter getUserAdapter() {
return mUserListAdapter;
}
@Override
protected boolean useBasicMenu() {
return true;
}
protected User getContextItemUser(int position) {
// position = position - 1;
// 加入footer跳过footer
if (position < mUserListAdapter.getCount()) {
Cursor cursor = (Cursor) mUserListAdapter.getItem(position);
if (cursor == null) {
return null;
} else {
return UserInfoTable.parseCursor(cursor);
}
} else {
return null;
}
}
@Override
protected void updateTweet(Tweet tweet) {
// TODO: updateTweet() 在哪里调用的? 目前尚只支持:
// updateTweet(String tweetId, ContentValues values)
// setFavorited(String tweetId, String isFavorited)
// 看是否还需要增加updateTweet(Tweet tweet)方法
// 对所有相关表的对应消息都进行刷新(如果存在的话)
// getDb().updateTweet(TwitterDbAdapter.TABLE_FAVORITE, tweet);
// getDb().updateTweet(TwitterDbAdapter.TABLE_MENTION, tweet);
// getDb().updateTweet(TwitterDbAdapter.TABLE_TWEET, tweet);
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)) {
goTop(); // skip the header
boolean shouldRetrieve = false;
// FIXME: 该子类页面全部使用了这个统一的计时器,导致进入Mention等分页面后经常不会自动刷新
long lastRefreshTime = mPreferences.getLong(
Preferences.LAST_TWEET_REFRESH_KEY, 0);
long nowTime = DateTimeHelper.getNowTime();
long diff = nowTime - lastRefreshTime;
Log.d(TAG, "Last refresh was " + diff + " ms ago.");
/*
* if (diff > REFRESH_THRESHOLD) { shouldRetrieve = true; } else if
* (Utils.isTrue(savedInstanceState, SIS_RUNNING_KEY)) { // Check to
* see if it was running a send or retrieve task. // It makes no
* sense to resend the send request (don't want dupes) // so we
* instead retrieve (refresh) to see if the message has // posted.
* Log.d(TAG,
* "Was last running a retrieve or send task. Let's refresh.");
* shouldRetrieve = true; }
*/
shouldRetrieve = true;
if (shouldRetrieve) {
doRetrieve();
}
long lastFollowersRefreshTime = mPreferences.getLong(
Preferences.LAST_FOLLOWERS_REFRESH_KEY, 0);
diff = nowTime - lastFollowersRefreshTime;
Log.d(TAG, "Last followers refresh was " + diff + " ms ago.");
/*
* if (diff > FOLLOWERS_REFRESH_THRESHOLD && (mRetrieveTask == null
* || mRetrieveTask.getStatus() != GenericTask.Status.RUNNING)) {
* Log.d(TAG, "Refresh followers."); doRetrieveFollowers(); }
*/
return true;
} else {
return false;
}
}
@Override
protected void onResume() {
Log.d(TAG, "onResume.");
if (lastPosition != 0) {
mUserList.setSelection(lastPosition);
}
super.onResume();
checkIsLogedIn();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
@Override
protected void onRestoreInstanceState(Bundle bundle) {
super.onRestoreInstanceState(bundle);
// mTweetEdit.updateCharsRemain();
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
super.onDestroy();
taskManager.cancelAll();
}
@Override
protected void onPause() {
Log.d(TAG, "onPause.");
super.onPause();
lastPosition = mUserList.getFirstVisiblePosition();
}
@Override
protected void onRestart() {
Log.d(TAG, "onRestart.");
super.onRestart();
}
@Override
protected void onStart() {
Log.d(TAG, "onStart.");
super.onStart();
}
@Override
protected void onStop() {
Log.d(TAG, "onStop.");
super.onStop();
}
// UI helpers.
@Override
protected String getActivityTitle() {
// TODO Auto-generated method stub
return null;
}
@Override
protected void adapterRefresh() {
mUserListAdapter.notifyDataSetChanged();
mUserListAdapter.refresh();
}
// Retrieve interface
public void updateProgress(String progress) {
mProgressText.setText(progress);
}
public void draw() {
mUserListAdapter.refresh();
}
public void goTop() {
Log.d(TAG, "goTop.");
mUserList.setSelection(1);
}
private void doRetrieveFollowers() {
Log.d(TAG, "Attempting followers retrieve.");
if (mFollowersRetrieveTask != null
&& mFollowersRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mFollowersRetrieveTask = new FollowersRetrieveTask();
mFollowersRetrieveTask.setListener(mFollowerRetrieveTaskListener);
mFollowersRetrieveTask.execute();
taskManager.addTask(mFollowersRetrieveTask);
// Don't need to cancel FollowersTask (assuming it ends properly).
mFollowersRetrieveTask.setCancelable(false);
}
}
public void onRetrieveBegin() {
updateProgress(getString(R.string.page_status_refreshing));
}
public void doRetrieve() {
Log.d(TAG, "Attempting retrieve.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mRetrieveTask = new RetrieveTask();
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.setFeedback(mFeedback);
mRetrieveTask.execute();
// Add Task to manager
taskManager.addTask(mRetrieveTask);
}
}
/**
* TODO:从API获取当前Followers,并同步到数据库
*
* @author Dino
*
*/
private class RetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
Log.d(TAG, "load RetrieveTask");
List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null;
try {
usersList = getApi().getFollowersList(getUserId(),
getCurrentPage());
} catch (HttpException e) {
e.printStackTrace();
}
publishProgress(SimpleFeedback.calProgressBySize(40, 20, usersList));
ArrayList<User> users = new ArrayList<User>();
for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
users.add(User.create(user));
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
addUsers(users);
return TaskResult.OK;
}
}
private class FollowersRetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
Log.d(TAG, "load FollowersErtrieveTask");
List<com.ch_linghu.fanfoudroid.fanfou.User> t_users = getUsers();
getDb().syncWeiboUsers(t_users);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
/**
* TODO:需要重写,获取下一批用户,按页分100页一次
*
* @author Dino
*
*/
private class GetMoreTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
Log.d(TAG, "load RetrieveTask");
List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null;
try {
usersList = getApi().getFollowersList(getUserId(),
getNextPage());
} catch (HttpException e) {
e.printStackTrace();
}
publishProgress(SimpleFeedback.calProgressBySize(40, 20, usersList));
ArrayList<User> users = new ArrayList<User>();
for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
users.add(User.create(user));
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
addUsers(users);
return TaskResult.OK;
}
}
private TaskListener getMoreListener = new TaskAdapter() {
@Override
public String getName() {
return "getMore";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
super.onPostExecute(task, result);
draw();
loadMoreGIF.setVisibility(View.GONE);
}
};
public void doGetMore() {
Log.d(TAG, "Attempting getMore.");
if (mGetMoreTask != null
&& mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mGetMoreTask = new GetMoreTask();
mGetMoreTask.setFeedback(mFeedback);
mGetMoreTask.setListener(getMoreListener);
mGetMoreTask.execute();
// Add Task to manager
taskManager.addTask(mGetMoreTask);
}
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/ui/base/UserCursorBaseActivity.java
|
Java
|
asf20
| 16,453
|
package com.ch_linghu.fanfoudroid.ui.base;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.DmActivity;
import com.ch_linghu.fanfoudroid.MentionActivity;
import com.ch_linghu.fanfoudroid.ProfileActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.UserTimelineActivity;
import com.ch_linghu.fanfoudroid.WriteActivity;
import com.ch_linghu.fanfoudroid.WriteDmActivity;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.data.User;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.task.TweetCommonTask;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter;
public abstract class UserListBaseActivity extends BaseActivity implements
Refreshable {
static final String TAG = "TwitterListBaseActivity";
protected TextView mProgressText;
protected NavBar mNavbar;
protected Feedback mFeedback;
protected static final int STATE_ALL = 0;
protected static final String SIS_RUNNING_KEY = "running";
private static final String USER_ID = "userId";
// Tasks.
protected GenericTask mFavTask;
private TaskListener mFavTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "FavoriteTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
onFavSuccess();
} else if (result == TaskResult.IO_ERROR) {
onFavFailure();
}
}
};
static final int DIALOG_WRITE_ID = 0;
abstract protected int getLayoutId();
abstract protected ListView getUserList();
abstract protected TweetAdapter getUserAdapter();
abstract protected void setupState();
abstract protected String getActivityTitle();
abstract protected boolean useBasicMenu();
abstract protected User getContextItemUser(int position);
abstract protected void updateTweet(Tweet tweet);
protected abstract String getUserId();// 获得用户id
public static final int CONTENT_PROFILE_ID = Menu.FIRST + 1;
public static final int CONTENT_STATUS_ID = Menu.FIRST + 2;
public static final int CONTENT_DEL_FRIEND = Menu.FIRST + 3;
public static final int CONTENT_ADD_FRIEND = Menu.FIRST + 4;
public static final int CONTENT_SEND_DM = Menu.FIRST + 5;
public static final int CONTENT_SEND_MENTION = Menu.FIRST + 6;
/**
* 如果增加了Context Menu常量的数量,则必须重载此方法, 以保证其他人使用常量时不产生重复
*
* @return 最大的Context Menu常量
*/
// protected int getLastContextMenuId(){
// return CONTEXT_DEL_FAV_ID;
// }
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState)) {
setContentView(getLayoutId());
mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this);
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
mPreferences.getInt(Preferences.TWITTER_ACTIVITY_STATE_KEY,
STATE_ALL);
mProgressText = (TextView) findViewById(R.id.progress_text);
setupState();
registerForContextMenu(getUserList());
registerOnClickListener(getUserList());
return true;
} else {
return false;
}
}
@Override
protected void onResume() {
super.onResume();
checkIsLogedIn();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
mFavTask.cancel(true);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (useBasicMenu()) {
AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
User user = getContextItemUser(info.position);
if (user == null) {
Log.w(TAG, "Selected item not available.");
return;
}
menu.add(
0,
CONTENT_PROFILE_ID,
0,
user.screenName
+ getResources().getString(
R.string.cmenu_user_profile_prefix));
menu.add(0, CONTENT_STATUS_ID, 0, user.screenName
+ getResources().getString(R.string.cmenu_user_status));
menu.add(
0,
CONTENT_SEND_MENTION,
0,
getResources().getString(R.string.cmenu_user_send_prefix)
+ user.screenName
+ getResources().getString(
R.string.cmenu_user_sendmention_suffix));
menu.add(
0,
CONTENT_SEND_DM,
0,
getResources().getString(R.string.cmenu_user_send_prefix)
+ user.screenName
+ getResources().getString(
R.string.cmenu_user_senddm_suffix));
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
User user = getContextItemUser(info.position);
if (user == null) {
Log.w(TAG, "Selected item not available.");
return super.onContextItemSelected(item);
}
switch (item.getItemId()) {
case CONTENT_PROFILE_ID:
launchActivity(ProfileActivity.createIntent(user.id));
return true;
case CONTENT_STATUS_ID:
launchActivity(UserTimelineActivity
.createIntent(user.id, user.name));
return true;
case CONTENT_DEL_FRIEND:
delFriend(user.id);
return true;
case CONTENT_ADD_FRIEND:
addFriend(user.id);
return true;
case CONTENT_SEND_MENTION:
launchActivity(WriteActivity.createNewTweetIntent(String.format(
"@%s ", user.screenName)));
return true;
case CONTENT_SEND_DM:
launchActivity(WriteDmActivity.createIntent(user.id));
return true;
default:
return super.onContextItemSelected(item);
}
}
/**
* 取消关注
*
* @param id
*/
private void delFriend(final String id) {
Builder diaBuilder = new AlertDialog.Builder(UserListBaseActivity.this)
.setTitle("关注提示").setMessage("确实要取消关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (cancelFollowingTask != null
&& cancelFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
cancelFollowingTask = new CancelFollowingTask();
cancelFollowingTask
.setListener(cancelFollowingTaskLinstener);
TaskParams params = new TaskParams();
params.put(USER_ID, id);
cancelFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
private GenericTask cancelFollowingTask;
/**
* 取消关注
*
* @author Dino
*
*/
private class CancelFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
// TODO:userid
String userId = params[0].getString(USER_ID);
getApi().destroyFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener cancelFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
// followingBtn.setText("添加关注");
// isFollowingText.setText(getResources().getString(
// R.string.profile_notfollowing));
// followingBtn.setOnClickListener(setfollowingListener);
Toast.makeText(getBaseContext(), "取消关注成功", Toast.LENGTH_SHORT)
.show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(getBaseContext(), "取消关注失败", Toast.LENGTH_SHORT)
.show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
private GenericTask setFollowingTask;
/**
* 设置关注
*
* @param id
*/
private void addFriend(String id) {
Builder diaBuilder = new AlertDialog.Builder(UserListBaseActivity.this)
.setTitle("关注提示").setMessage("确实要添加关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (setFollowingTask != null
&& setFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
setFollowingTask = new SetFollowingTask();
setFollowingTask
.setListener(setFollowingTaskLinstener);
TaskParams params = new TaskParams();
setFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
/**
* 设置关注
*
* @author Dino
*
*/
private class SetFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
String userId = params[0].getString(USER_ID);
getApi().createFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener setFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
// followingBtn.setText("取消关注");
// isFollowingText.setText(getResources().getString(
// R.string.profile_isfollowing));
// followingBtn.setOnClickListener(cancelFollowingListener);
Toast.makeText(getBaseContext(), "关注成功", Toast.LENGTH_SHORT)
.show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(getBaseContext(), "关注失败", Toast.LENGTH_SHORT)
.show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case OPTIONS_MENU_ID_TWEETS:
launchActivity(TwitterActivity.createIntent(this));
return true;
case OPTIONS_MENU_ID_REPLIES:
launchActivity(MentionActivity.createIntent(this));
return true;
case OPTIONS_MENU_ID_DM:
launchActivity(DmActivity.createIntent());
return true;
}
return super.onOptionsItemSelected(item);
}
private void draw() {
getUserAdapter().refresh();
}
private void goTop() {
getUserList().setSelection(0);
}
protected void adapterRefresh() {
getUserAdapter().refresh();
}
// for HasFavorite interface
public void doFavorite(String action, String id) {
if (!TextUtils.isEmpty(id)) {
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mFavTask = new TweetCommonTask.FavoriteTask(this);
mFavTask.setFeedback(mFeedback);
mFavTask.setListener(mFavTaskListener);
TaskParams params = new TaskParams();
params.put("action", action);
params.put("id", id);
mFavTask.execute(params);
}
}
}
public void onFavSuccess() {
// updateProgress(getString(R.string.refreshing));
adapterRefresh();
}
public void onFavFailure() {
// updateProgress(getString(R.string.refreshing));
}
protected void specialItemClicked(int position) {
}
/*
* TODO:单击列表项
*/
protected void registerOnClickListener(ListView listView) {
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Toast.makeText(getBaseContext(),
// "选择第"+position+"个列表",Toast.LENGTH_SHORT).show();
User user = getContextItemUser(position);
if (user == null) {
Log.w(TAG, "selected item not available");
specialItemClicked(position);
} else {
launchActivity(ProfileActivity.createIntent(user.id));
}
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
if(getUserList() != null) {
int lastPosition = getUserList().getFirstVisiblePosition();
outState.putInt("LAST_POSITION", lastPosition);
}
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if(getUserList() != null) {
int lastPosition = savedInstanceState.getInt("LAST_POSITION");
getUserList().setSelection(lastPosition);
}
}
@Override
public void doRetrieve() {
// TODO Auto-generated method stub
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/ui/base/UserListBaseActivity.java
|
Java
|
asf20
| 14,619
|
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid.ui.base;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.fanfou.IDs;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskManager;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.module.FlingGestureListener;
import com.ch_linghu.fanfoudroid.ui.module.MyActivityFlipper;
import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback;
import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter;
import com.ch_linghu.fanfoudroid.ui.module.TweetCursorAdapter;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.util.DebugTimer;
import com.hlidskialf.android.hardware.ShakeListener;
import com.markupartist.android.widget.PullToRefreshListView;
import com.markupartist.android.widget.PullToRefreshListView.OnRefreshListener;
/**
* TwitterCursorBaseLine用于带有静态数据来源(对应数据库的,与twitter表同构的特定表)的展现
*/
public abstract class TwitterCursorBaseActivity extends TwitterListBaseActivity {
static final String TAG = "TwitterCursorBaseActivity";
// Views.
protected PullToRefreshListView mTweetList;
protected TweetCursorAdapter mTweetAdapter;
protected View mListHeader;
protected View mListFooter;
protected TextView loadMoreBtn;
protected ProgressBar loadMoreGIF;
protected TextView loadMoreBtnTop;
protected ProgressBar loadMoreGIFTop;
protected static int lastPosition = 0;
protected ShakeListener mShaker = null;
// Tasks.
protected TaskManager taskManager = new TaskManager();
private GenericTask mRetrieveTask;
private GenericTask mFollowersRetrieveTask;
private GenericTask mGetMoreTask;
private int mRetrieveCount = 0;
private TaskListener mRetrieveTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "RetrieveTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
// 刷新按钮停止旋转
loadMoreGIF.setVisibility(View.GONE);
mTweetList.onRefreshComplete();
if (result == TaskResult.AUTH_ERROR) {
mFeedback.failed("登录信息出错");
logout();
} else if (result == TaskResult.OK) {
// TODO: XML处理, GC压力
SharedPreferences.Editor editor = getPreferences().edit();
editor.putLong(Preferences.LAST_TWEET_REFRESH_KEY,
DateTimeHelper.getNowTime());
editor.commit();
// TODO: 1. StatusType(DONE) ;
if (mRetrieveCount >= StatusTable.MAX_ROW_NUM) {
// 只有在取回的数据大于MAX时才做GC, 因为小于时可以保证数据的连续性
getDb().gc(getUserId(), getDatabaseType()); // GC
}
draw();
if (task == mRetrieveTask) {
goTop();
}
} else if (result == TaskResult.IO_ERROR) {
// FIXME: bad smell
if (task == mRetrieveTask) {
mFeedback.failed(((RetrieveTask) task).getErrorMsg());
} else if (task == mGetMoreTask) {
mFeedback.failed(((GetMoreTask) task).getErrorMsg());
}
} else {
// do nothing
}
// DEBUG
if (TwitterApplication.DEBUG) {
DebugTimer.stop();
Log.v("DEBUG", DebugTimer.getProfileAsString());
}
}
@Override
public void onPreExecute(GenericTask task) {
mRetrieveCount = 0;
mTweetList.prepareForRefresh();
if (TwitterApplication.DEBUG) {
DebugTimer.start();
}
}
@Override
public void onProgressUpdate(GenericTask task, Object param) {
Log.d(TAG, "onProgressUpdate");
draw();
}
};
private TaskListener mFollowerRetrieveTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "FollowerRetrieve";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
SharedPreferences sp = getPreferences();
SharedPreferences.Editor editor = sp.edit();
editor.putLong(Preferences.LAST_FOLLOWERS_REFRESH_KEY,
DateTimeHelper.getNowTime());
editor.commit();
} else {
// Do nothing.
}
}
};
// Refresh data at startup if last refresh was this long ago or greater.
private static final long REFRESH_THRESHOLD = 5 * 60 * 1000;
// Refresh followers if last refresh was this long ago or greater.
private static final long FOLLOWERS_REFRESH_THRESHOLD = 12 * 60 * 60 * 1000;
abstract protected void markAllRead();
abstract protected Cursor fetchMessages();
public abstract int getDatabaseType();
public abstract String getUserId();
public abstract String fetchMaxId();
public abstract String fetchMinId();
public abstract int addMessages(ArrayList<Tweet> tweets, boolean isUnread);
public abstract List<Status> getMessageSinceId(String maxId)
throws HttpException;
public abstract List<Status> getMoreMessageFromId(String minId)
throws HttpException;
public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1;
// public static final int CONTEXT_AT_ID = Menu.FIRST + 2;
public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3;
public static final int CONTEXT_DM_ID = Menu.FIRST + 4;
public static final int CONTEXT_MORE_ID = Menu.FIRST + 5;
public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6;
public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7;
@Override
protected void setupState() {
Cursor cursor;
cursor = fetchMessages(); // getDb().fetchMentions();
setTitle(getActivityTitle());
startManagingCursor(cursor);
mTweetList = (PullToRefreshListView) findViewById(R.id.tweet_list);
// TODO: 需处理没有数据时的情况
Log.d("LDS", cursor.getCount() + " cursor count");
setupListHeader(true);
mTweetAdapter = new TweetCursorAdapter(this, cursor);
mTweetList.setAdapter(mTweetAdapter);
// ? registerOnClickListener(mTweetList);
}
/**
* 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用
*/
protected void setupListHeader(boolean addFooter) {
// Add Header to ListView
//mListHeader = View.inflate(this, R.layout.listview_header, null);
//mTweetList.addHeaderView(mListHeader, null, true);
mTweetList.setOnRefreshListener(new OnRefreshListener(){
@Override
public void onRefresh(){
doRetrieve();
}
});
// Add Footer to ListView
mListFooter = View.inflate(this, R.layout.listview_footer, null);
mTweetList.addFooterView(mListFooter, null, true);
// Find View
loadMoreBtn = (TextView) findViewById(R.id.ask_for_more);
loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar);
loadMoreBtnTop = (TextView) findViewById(R.id.ask_for_more_header);
loadMoreGIFTop = (ProgressBar) findViewById(R.id.rectangleProgressBar_header);
}
@Override
protected void specialItemClicked(int position) {
// 注意 mTweetAdapter.getCount 和 mTweetList.getCount的区别
// 前者仅包含数据的数量(不包括foot和head),后者包含foot和head
// 因此在同时存在foot和head的情况下,list.count = adapter.count + 2
if (position == 0) {
// 第一个Item(header)
loadMoreGIFTop.setVisibility(View.VISIBLE);
doRetrieve();
} else if (position == mTweetList.getCount() - 1) {
// 最后一个Item(footer)
loadMoreGIF.setVisibility(View.VISIBLE);
doGetMore();
}
}
@Override
protected int getLayoutId() {
return R.layout.main;
}
@Override
protected ListView getTweetList() {
return mTweetList;
}
@Override
protected TweetAdapter getTweetAdapter() {
return mTweetAdapter;
}
@Override
protected boolean useBasicMenu() {
return true;
}
@Override
protected Tweet getContextItemTweet(int position) {
position = position - 1;
// 因为List加了Header和footer,所以要跳过第一个以及忽略最后一个
if (position >= 0 && position < mTweetAdapter.getCount()) {
Cursor cursor = (Cursor) mTweetAdapter.getItem(position);
if (cursor == null) {
return null;
} else {
return StatusTable.parseCursor(cursor);
}
} else {
return null;
}
}
@Override
protected void updateTweet(Tweet tweet) {
// TODO: updateTweet() 在哪里调用的? 目前尚只支持:
// updateTweet(String tweetId, ContentValues values)
// setFavorited(String tweetId, String isFavorited)
// 看是否还需要增加updateTweet(Tweet tweet)方法
// 对所有相关表的对应消息都进行刷新(如果存在的话)
// getDb().updateTweet(TwitterDbAdapter.TABLE_FAVORITE, tweet);
// getDb().updateTweet(TwitterDbAdapter.TABLE_MENTION, tweet);
// getDb().updateTweet(TwitterDbAdapter.TABLE_TWEET, tweet);
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)) {
// Mark all as read.
// getDb().markAllMentionsRead();
markAllRead();
boolean shouldRetrieve = false;
// FIXME: 该子类页面全部使用了这个统一的计时器,导致进入Mention等分页面后经常不会自动刷新
long lastRefreshTime = mPreferences.getLong(
Preferences.LAST_TWEET_REFRESH_KEY, 0);
long nowTime = DateTimeHelper.getNowTime();
long diff = nowTime - lastRefreshTime;
Log.d(TAG, "Last refresh was " + diff + " ms ago.");
if (diff > REFRESH_THRESHOLD) {
shouldRetrieve = true;
} else if (isTrue(savedInstanceState, SIS_RUNNING_KEY)) {
// Check to see if it was running a send or retrieve task.
// It makes no sense to resend the send request (don't want
// dupes)
// so we instead retrieve (refresh) to see if the message has
// posted.
Log.d(TAG,
"Was last running a retrieve or send task. Let's refresh.");
shouldRetrieve = true;
}
if (shouldRetrieve) {
doRetrieve();
}
goTop(); // skip the header
long lastFollowersRefreshTime = mPreferences.getLong(
Preferences.LAST_FOLLOWERS_REFRESH_KEY, 0);
diff = nowTime - lastFollowersRefreshTime;
Log.d(TAG, "Last followers refresh was " + diff + " ms ago.");
// FIXME: 目前还没有对Followers列表做逻辑处理,因此暂时去除对Followers的获取。
// 未来需要实现@用户提示时,对Follower操作需要做一次review和refactoring
// 现在频繁会出现主键冲突的问题。
//
// Should Refresh Followers
// if (diff > FOLLOWERS_REFRESH_THRESHOLD
// && (mRetrieveTask == null || mRetrieveTask.getStatus() !=
// GenericTask.Status.RUNNING)) {
// Log.d(TAG, "Refresh followers.");
// doRetrieveFollowers();
// }
// 手势识别
registerGestureListener();
//晃动刷新
registerShakeListener();
return true;
} else {
return false;
}
}
@Override
protected void onResume() {
Log.d(TAG, "onResume.");
if (lastPosition != 0) {
mTweetList.setSelection(lastPosition);
}
if (mShaker != null){
mShaker.resume();
}
super.onResume();
checkIsLogedIn();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
@Override
protected void onRestoreInstanceState(Bundle bundle) {
super.onRestoreInstanceState(bundle);
// mTweetEdit.updateCharsRemain();
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
super.onDestroy();
taskManager.cancelAll();
// 刷新按钮停止旋转
if (loadMoreGIF != null){
loadMoreGIF.setVisibility(View.GONE);
}
if (mTweetList != null){
mTweetList.onRefreshComplete();
}
}
@Override
protected void onPause() {
Log.d(TAG, "onPause.");
if (mShaker != null){
mShaker.pause();
}
super.onPause();
lastPosition = mTweetList.getFirstVisiblePosition();
}
@Override
protected void onRestart() {
Log.d(TAG, "onRestart.");
super.onRestart();
}
@Override
protected void onStart() {
Log.d(TAG, "onStart.");
super.onStart();
}
@Override
protected void onStop() {
Log.d(TAG, "onStop.");
super.onStop();
}
// UI helpers.
@Override
protected String getActivityTitle() {
return null;
}
@Override
protected void adapterRefresh() {
mTweetAdapter.notifyDataSetChanged();
mTweetAdapter.refresh();
}
// Retrieve interface
public void updateProgress(String progress) {
mProgressText.setText(progress);
}
public void draw() {
mTweetAdapter.refresh();
}
public void goTop() {
Log.d(TAG, "goTop.");
mTweetList.setSelection(1);
}
private void doRetrieveFollowers() {
Log.d(TAG, "Attempting followers retrieve.");
if (mFollowersRetrieveTask != null
&& mFollowersRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mFollowersRetrieveTask = new FollowersRetrieveTask();
mFollowersRetrieveTask.setListener(mFollowerRetrieveTaskListener);
mFollowersRetrieveTask.execute();
taskManager.addTask(mFollowersRetrieveTask);
// Don't need to cancel FollowersTask (assuming it ends properly).
mFollowersRetrieveTask.setCancelable(false);
}
}
public void doRetrieve() {
Log.d(TAG, "Attempting retrieve.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mRetrieveTask = new RetrieveTask();
mRetrieveTask.setFeedback(mFeedback);
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.execute();
// Add Task to manager
taskManager.addTask(mRetrieveTask);
}
}
private class RetrieveTask extends GenericTask {
private String _errorMsg;
public String getErrorMsg() {
return _errorMsg;
}
@Override
protected TaskResult _doInBackground(TaskParams... params) {
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
try {
String maxId = fetchMaxId(); // getDb().fetchMaxMentionId();
statusList = getMessageSinceId(maxId);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
_errorMsg = e.getMessage();
return TaskResult.IO_ERROR;
}
ArrayList<Tweet> tweets = new ArrayList<Tweet>();
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
tweets.add(Tweet.create(status));
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
publishProgress(SimpleFeedback.calProgressBySize(40, 20, tweets));
mRetrieveCount = addMessages(tweets, false);
return TaskResult.OK;
}
}
private class FollowersRetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
// TODO: 目前仅做新API兼容性改动,待完善Follower处理
IDs followers = getApi().getFollowersIDs();
List<String> followerIds = Arrays.asList(followers.getIDs());
getDb().syncFollowers(followerIds);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
// GET MORE TASK
private class GetMoreTask extends GenericTask {
private String _errorMsg;
public String getErrorMsg() {
return _errorMsg;
}
@Override
protected TaskResult _doInBackground(TaskParams... params) {
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
String minId = fetchMinId(); // getDb().fetchMaxMentionId();
if (minId == null) {
return TaskResult.FAILED;
}
try {
statusList = getMoreMessageFromId(minId);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
_errorMsg = e.getMessage();
return TaskResult.IO_ERROR;
}
if (statusList == null) {
return TaskResult.FAILED;
}
ArrayList<Tweet> tweets = new ArrayList<Tweet>();
publishProgress(SimpleFeedback.calProgressBySize(40, 20, tweets));
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
tweets.add(Tweet.create(status));
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
addMessages(tweets, false); // getDb().addMentions(tweets, false);
return TaskResult.OK;
}
}
public void doGetMore() {
Log.d(TAG, "Attempting getMore.");
if (mGetMoreTask != null
&& mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mGetMoreTask = new GetMoreTask();
mGetMoreTask.setFeedback(mFeedback);
mGetMoreTask.setListener(mRetrieveTaskListener);
mGetMoreTask.execute();
// Add Task to manager
taskManager.addTask(mGetMoreTask);
}
}
//////////////////// Gesture test /////////////////////////////////////
private static boolean useGestrue;
{
useGestrue = TwitterApplication.mPref.getBoolean(
Preferences.USE_GESTRUE, false);
if (useGestrue) {
Log.v(TAG, "Using Gestrue!");
} else {
Log.v(TAG, "Not Using Gestrue!");
}
}
//////////////////// Gesture test /////////////////////////////////////
private static boolean useShake;
{
useShake = TwitterApplication.mPref.getBoolean(
Preferences.USE_SHAKE, false);
if (useShake) {
Log.v(TAG, "Using Shake to refresh!");
} else {
Log.v(TAG, "Not Using Shake!");
}
}
protected FlingGestureListener myGestureListener = null;
@Override
public boolean onTouchEvent(MotionEvent event) {
if (useGestrue && myGestureListener != null) {
return myGestureListener.getDetector().onTouchEvent(event);
}
return super.onTouchEvent(event);
}
// use it in _onCreate
private void registerGestureListener() {
if (useGestrue) {
myGestureListener = new FlingGestureListener(this,
MyActivityFlipper.create(this));
getTweetList().setOnTouchListener(myGestureListener);
}
}
// use it in _onCreate
private void registerShakeListener() {
if (useShake){
mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener() {
@Override
public void onShake() {
Log.v(TAG, "onShake");
doRetrieve();
}
});
}
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/ui/base/TwitterCursorBaseActivity.java
|
Java
|
asf20
| 22,940
|
package com.ch_linghu.fanfoudroid.ui.module;
import com.ch_linghu.fanfoudroid.R;
import android.app.Activity;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
/**
* FlingGestureLIstener, 封装 {@link SimpleOnGestureListener} .
* 主要用于识别类似向上下或向左右滑动等基本手势.
*
* 该类主要解决了与ListView自带的上下滑动冲突问题. 解决方法为将listView的onTouchListener进行覆盖:<code>
* FlingGestureListener gListener = new FlingGestureListener(this,
* MyActivityFlipper.create(this));
* myListView.setOnTouchListener(gListener);
* </code>
*
* 该类一般和实现了 {@link Widget.OnGestureListener} 接口的类共同协作. 在识别到手势后会自动调用其相关的回调方法,
* 以实现手势触发事件效果.
*
* @see Widget.OnGestureListener
*
*/
public class FlingGestureListener extends SimpleOnGestureListener implements
OnTouchListener {
private static final String TAG = "FlipperGestureListener";
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_DISTANCE = 400;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
private Widget.OnGestureListener mListener;
private GestureDetector gDetector;
private Activity activity;
public FlingGestureListener(Activity activity,
Widget.OnGestureListener listener) {
this(activity, listener, null);
}
public FlingGestureListener(Activity activity,
Widget.OnGestureListener listener, GestureDetector gDetector) {
if (gDetector == null) {
gDetector = new GestureDetector(activity, this);
}
this.gDetector = gDetector;
mListener = listener;
this.activity = activity;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
Log.d(TAG, "On fling");
boolean result = super.onFling(e1, e2, velocityX, velocityY);
float xDistance = Math.abs(e1.getX() - e2.getX());
float yDistance = Math.abs(e1.getY() - e2.getY());
velocityX = Math.abs(velocityX);
velocityY = Math.abs(velocityY);
try {
if (xDistance > SWIPE_MAX_DISTANCE
|| yDistance > SWIPE_MAX_DISTANCE) {
Log.d(TAG, "OFF_PATH");
return result;
}
if (velocityX > SWIPE_THRESHOLD_VELOCITY
&& xDistance > SWIPE_MIN_DISTANCE) {
if (e1.getX() > e2.getX()) {
Log.d(TAG, "<------");
result = mListener
.onFlingLeft(e1, e1, velocityX, velocityY);
activity.overridePendingTransition(R.anim.push_left_in,
R.anim.push_left_out);
} else {
Log.d(TAG, "------>");
result = mListener.onFlingRight(e1, e1, velocityX,
velocityY);
activity.overridePendingTransition(R.anim.push_right_in,
R.anim.push_right_out);
}
} else if (velocityY > SWIPE_THRESHOLD_VELOCITY
&& yDistance > SWIPE_MIN_DISTANCE) {
if (e1.getY() > e2.getY()) {
Log.d(TAG, "up");
result = mListener.onFlingUp(e1, e1, velocityX, velocityY);
} else {
Log.d(TAG, "down");
result = mListener
.onFlingDown(e1, e1, velocityX, velocityY);
}
} else {
Log.d(TAG, "not hint");
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "onFling error " + e.getMessage());
}
return result;
}
@Override
public void onLongPress(MotionEvent e) {
// TODO Auto-generated method stub
super.onLongPress(e);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.d(TAG, "On Touch");
// Within the MyGestureListener class you can now manage the
// event.getAction() codes.
// Note that we are now calling the gesture Detectors onTouchEvent.
// And given we've set this class as the GestureDetectors listener
// the onFling, onSingleTap etc methods will be executed.
return gDetector.onTouchEvent(event);
}
public GestureDetector getDetector() {
return gDetector;
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/ui/module/FlingGestureListener.java
|
Java
|
asf20
| 4,028
|
/**
*
*/
package com.ch_linghu.fanfoudroid.ui.module;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.db.UserInfoTable;
public class UserCursorAdapter extends CursorAdapter implements TweetAdapter {
private static final String TAG = "TweetCursorAdapter";
private Context mContext;
public UserCursorAdapter(Context context, Cursor cursor) {
super(context, cursor);
mContext = context;
if (context != null) {
mInflater = LayoutInflater.from(context);
}
if (cursor != null) {
mScreenNametColumn = cursor
.getColumnIndexOrThrow(UserInfoTable.FIELD_USER_SCREEN_NAME);
mUserIdColumn = cursor.getColumnIndexOrThrow(UserInfoTable._ID);
mProfileImageUrlColumn = cursor
.getColumnIndexOrThrow(UserInfoTable.FIELD_PROFILE_IMAGE_URL);
// mLastStatusColumn=cursor.getColumnIndexOrThrow(UserInfoTable.FIELD_LAST_STATUS);
}
mMetaBuilder = new StringBuilder();
}
private LayoutInflater mInflater;
private int mScreenNametColumn;
private int mUserIdColumn;
private int mProfileImageUrlColumn;
// private int mLastStatusColumn;
private StringBuilder mMetaBuilder;
private ImageLoaderCallback callback = new ImageLoaderCallback() {
@Override
public void refresh(String url, Bitmap bitmap) {
UserCursorAdapter.this.refresh();
}
};
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = mInflater.inflate(R.layout.follower_item, parent, false);
Log.d(TAG, "load newView");
UserCursorAdapter.ViewHolder holder = new ViewHolder();
holder.screenName = (TextView) view.findViewById(R.id.screen_name);
holder.profileImage = (ImageView) view.findViewById(R.id.profile_image);
// holder.lastStatus=(TextView) view.findViewById(R.id.last_status);
holder.userId = (TextView) view.findViewById(R.id.user_id);
view.setTag(holder);
return view;
}
private static class ViewHolder {
public TextView screenName;
public TextView userId;
public TextView lastStatus;
public ImageView profileImage;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
UserCursorAdapter.ViewHolder holder = (UserCursorAdapter.ViewHolder) view
.getTag();
Log.d(TAG, "cursor count=" + cursor.getCount());
Log.d(TAG, "holder is null?" + (holder == null ? "yes" : "no"));
SharedPreferences pref = TwitterApplication.mPref; // PreferenceManager.getDefaultSharedPreferences(mContext);;
boolean useProfileImage = pref.getBoolean(
Preferences.USE_PROFILE_IMAGE, true);
String profileImageUrl = cursor.getString(mProfileImageUrlColumn);
if (useProfileImage) {
if (!TextUtils.isEmpty(profileImageUrl)) {
holder.profileImage
.setImageBitmap(TwitterApplication.mImageLoader.get(
profileImageUrl, callback));
}
} else {
holder.profileImage.setVisibility(View.GONE);
}
holder.screenName.setText(cursor.getString(mScreenNametColumn));
holder.userId.setText(cursor.getString(mUserIdColumn));
}
@Override
public void refresh() {
getCursor().requery();
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/ui/module/UserCursorAdapter.java
|
Java
|
asf20
| 3,612
|
package com.ch_linghu.fanfoudroid.ui.module;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.R;
public class SimpleFeedback implements Feedback, Widget {
private static final String TAG = "SimpleFeedback";
public static final int MAX = 100;
private ProgressBar mProgress = null;
//private ProgressBar mLoadingProgress = null;
public SimpleFeedback(Context context) {
mProgress = (ProgressBar) ((Activity) context)
.findViewById(R.id.progress_bar);
//mLoadingProgress = (ProgressBar) ((Activity) context)
// .findViewById(R.id.top_refresh_progressBar);
}
@Override
public void start(CharSequence text) {
mProgress.setProgress(20);
//mLoadingProgress.setVisibility(View.VISIBLE);
}
@Override
public void success(CharSequence text) {
mProgress.setProgress(100);
//mLoadingProgress.setVisibility(View.GONE);
resetProgressBar();
}
@Override
public void failed(CharSequence text) {
resetProgressBar();
showMessage(text);
}
@Override
public void cancel(CharSequence text) {
}
@Override
public void update(Object arg0) {
if (arg0 instanceof Integer) {
mProgress.setProgress((Integer) arg0);
} else if (arg0 instanceof CharSequence) {
showMessage((String) arg0);
}
}
@Override
public void setIndeterminate(boolean indeterminate) {
mProgress.setIndeterminate(indeterminate);
}
@Override
public Context getContext() {
if (mProgress != null) {
return mProgress.getContext();
}
//if (mLoadingProgress != null) {
// return mLoadingProgress.getContext();
//}
return null;
}
@Override
public boolean isAvailable() {
if (null == mProgress) {
Log.e(TAG, "R.id.progress_bar is missing");
return false;
}
//if (null == mLoadingProgress) {
// Log.e(TAG, "R.id.top_refresh_progressBar is missing");
// return false;
//}
return true;
}
/**
* @param total
* 0~100
* @param maxSize
* max size of list
* @param list
* @return
*/
public static int calProgressBySize(int total, int maxSize, List<?> list) {
if (null != list) {
return (MAX - (int) Math.floor(list.size() * (total / maxSize)));
}
return MAX;
}
private void resetProgressBar() {
if (mProgress.isIndeterminate()) {
// TODO: 第二次不会出现
mProgress.setIndeterminate(false);
}
mProgress.setProgress(0);
}
private void showMessage(CharSequence text) {
Toast.makeText(getContext(), text, Toast.LENGTH_LONG).show();
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/ui/module/SimpleFeedback.java
|
Java
|
asf20
| 2,632
|
package com.ch_linghu.fanfoudroid.ui.module;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;
import com.ch_linghu.fanfoudroid.R;
/**
* ActivityFlipper, 和 {@link ViewFactory} 类似, 只是设计用于切换activity.
*
* 切换的前后顺序取决与注册时的先后顺序
*
* USAGE: <code>
* ActivityFlipper mFlipper = new ActivityFlipper(this);
* mFlipper.addActivity(TwitterActivity.class);
* mFlipper.addActivity(MentionActivity.class);
* mFlipper.addActivity(DmActivity.class);
*
* // switch activity
* mFlipper.setCurrentActivity(TwitterActivity.class);
* mFlipper.showNext();
* mFlipper.showPrevious();
*
* // or without set current activity
* mFlipper.showNextOf(TwitterActivity.class);
* mFlipper.showPreviousOf(TwitterActivity.class);
*
* // or auto mode, use the context as current activity
* mFlipper.autoShowNext();
* mFlipper.autoShowPrevious();
*
* // set toast
* mFlipper.setToastResource(new int[] {
* R.drawable.point_left,
* R.drawable.point_center,
* R.drawable.point_right
* });
*
* // set Animation
* mFlipper.setInAnimation(R.anim.push_left_in);
* mFlipper.setOutAnimation(R.anim.push_left_out);
* mFlipper.setPreviousInAnimation(R.anim.push_right_in);
* mFlipper.setPreviousOutAnimation(R.anim.push_right_out);
* </code>
*
*/
public class ActivityFlipper implements IFlipper {
private static final String TAG = "ActivityFlipper";
private static final int SHOW_NEXT = 0;
private static final int SHOW_PROVIOUS = 1;
private int mDirection = SHOW_NEXT;
private boolean mToastEnabled = false;
private int[] mToastResourcesMap = new int[] {};
private boolean mAnimationEnabled = false;
private int mNextInAnimation = -1;
private int mNextOutAnimation = -1;
private int mPreviousInAnimation = -1;
private int mPreviousOutAnimation = -1;
private Activity mActivity;
private List<Class<?>> mActivities = new ArrayList<Class<?>>();;
private int mWhichActivity = 0;
public ActivityFlipper() {
}
public ActivityFlipper(Activity activity) {
mActivity = activity;
}
/**
* Launch Activity
*
* @param cls
* class of activity
*/
public void launchActivity(Class<?> cls) {
Log.v(TAG, "launch activity :" + cls.getName());
Intent intent = new Intent();
intent.setClass(mActivity, cls);
mActivity.startActivity(intent);
}
public void setToastResource(int[] resourceIds) {
mToastEnabled = true;
mToastResourcesMap = resourceIds;
}
private void maybeShowToast(int whichActicity) {
if (mToastEnabled && whichActicity < mToastResourcesMap.length) {
final Toast myToast = new Toast(mActivity);
final ImageView myView = new ImageView(mActivity);
myView.setImageResource(mToastResourcesMap[whichActicity]);
myToast.setView(myView);
myToast.setDuration(Toast.LENGTH_SHORT);
myToast.setGravity(Gravity.BOTTOM | Gravity.CENTER, 0, 0);
myToast.show();
}
}
private void maybeShowAnimation(int whichActivity) {
if (mAnimationEnabled) {
boolean showPrevious = (mDirection == SHOW_PROVIOUS);
if (showPrevious && mPreviousInAnimation != -1
&& mPreviousOutAnimation != -1) {
mActivity.overridePendingTransition(mPreviousInAnimation,
mPreviousOutAnimation);
return; // use Previous Animation
}
if (mNextInAnimation != -1 && mNextOutAnimation != -1) {
mActivity.overridePendingTransition(mNextInAnimation,
mNextOutAnimation);
}
}
}
/**
* Launch Activity by index
*
* @param whichActivity
* the index of Activity
*/
private void launchActivity(int whichActivity) {
launchActivity(mActivities.get(whichActivity));
maybeShowToast(whichActivity);
maybeShowAnimation(whichActivity);
}
/**
* Add Activity NOTE: 添加的顺序很重要
*
* @param cls
* class of activity
*/
public void addActivity(Class<?> cls) {
mActivities.add(cls);
}
/**
* Get index of the Activity
*
* @param cls
* class of activity
* @return
*/
private int getIndexOf(Class<?> cls) {
int index = mActivities.indexOf(cls);
if (-1 == index) {
Log.e(TAG, "No such activity: " + cls.getName());
}
return index;
}
@SuppressWarnings("unused")
private Class<?> getActivityAt(int index) {
if (index > 0 && index < mActivities.size()) {
return mActivities.get(index);
}
return null;
}
/**
* Show next activity(already setCurrentActivity)
*/
@Override
public void showNext() {
mDirection = SHOW_NEXT;
setDisplayedActivity(mWhichActivity + 1, true);
}
/**
* Show next activity of
*
* @param cls
* class of activity
*/
public void showNextOf(Class<?> cls) {
setCurrentActivity(cls);
showNext();
}
/**
* Show next activity(use current context as a activity)
*/
public void autoShowNext() {
showNextOf(mActivity.getClass());
}
/**
* Show previous activity(already setCurrentActivity)
*/
@Override
public void showPrevious() {
mDirection = SHOW_PROVIOUS;
setDisplayedActivity(mWhichActivity - 1, true);
}
/**
* Show previous activity of
*
* @param cls
* class of activity
*/
public void showPreviousOf(Class<?> cls) {
setCurrentActivity(cls);
showPrevious();
}
/**
* Show previous activity(use current context as a activity)
*/
public void autoShowPrevious() {
showPreviousOf(mActivity.getClass());
}
/**
* Sets which child view will be displayed
*
* @param whichActivity
* the index of the child view to display
* @param display
* display immediately
*/
public void setDisplayedActivity(int whichActivity, boolean display) {
mWhichActivity = whichActivity;
if (whichActivity >= getCount()) {
mWhichActivity = 0;
} else if (whichActivity < 0) {
mWhichActivity = getCount() - 1;
}
if (display) {
launchActivity(mWhichActivity);
}
}
/**
* Set current Activity
*
* @param cls
* class of activity
*/
public void setCurrentActivity(Class<?> cls) {
setDisplayedActivity(getIndexOf(cls), false);
}
public void setInAnimation(int resourceId) {
setEnableAnimation(true);
mNextInAnimation = resourceId;
}
public void setOutAnimation(int resourceId) {
setEnableAnimation(true);
mNextOutAnimation = resourceId;
}
public void setPreviousInAnimation(int resourceId) {
mPreviousInAnimation = resourceId;
}
public void setPreviousOutAnimation(int resourceId) {
mPreviousOutAnimation = resourceId;
}
public void setEnableAnimation(boolean enable) {
mAnimationEnabled = enable;
}
/**
* Count activities
*
* @return the number of activities
*/
public int getCount() {
return mActivities.size();
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/ui/module/ActivityFlipper.java
|
Java
|
asf20
| 6,954
|
package com.ch_linghu.fanfoudroid.ui.module;
import android.content.Context;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
public interface Widget {
Context getContext();
// TEMP
public static interface OnGestureListener {
/**
* @param e1
* The first down motion event that started the fling.
* @param e2
* The move motion event that triggered the current onFling.
* @param velocityX
* The velocity of this fling measured in pixels per second
* along the x axis.
* @param velocityY
* The velocity of this fling measured in pixels per second
* along the y axis.
* @return true if the event is consumed, else false
*
* @see SimpleOnGestureListener#onFling
*/
boolean onFlingDown(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY);
boolean onFlingUp(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY);
boolean onFlingLeft(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY);
boolean onFlingRight(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY);
}
public static interface OnRefreshListener {
void onRefresh();
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/ui/module/Widget.java
|
Java
|
asf20
| 1,270
|
package com.ch_linghu.fanfoudroid.ui.module;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.text.Layout;
import android.text.Spannable;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.URLSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
public class MyTextView extends TextView {
private static float mFontSize = 15;
private static boolean mFontSizeChanged = true;
public MyTextView(Context context) {
super(context, null);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setLinksClickable(false);
Resources res = getResources();
int color = res.getColor(R.color.link_color);
setLinkTextColor(color);
initFontSize();
}
public void initFontSize() {
if (mFontSizeChanged) {
mFontSize = getFontSizeFromPreferences(mFontSize);
setFontSizeChanged(false); // reset
}
setTextSize(mFontSize);
}
private float getFontSizeFromPreferences(float defaultValue) {
SharedPreferences preferences = TwitterApplication.mPref;
if (preferences.contains(Preferences.UI_FONT_SIZE)) {
Log.v("DEBUG",
preferences.getString(Preferences.UI_FONT_SIZE, "null")
+ " CHANGE FONT SIZE");
return Float.parseFloat(preferences.getString(
Preferences.UI_FONT_SIZE, "14"));
}
return defaultValue;
}
private URLSpan mCurrentLink;
private ForegroundColorSpan mLinkFocusStyle = new ForegroundColorSpan(
Color.RED);
@Override
public boolean onTouchEvent(MotionEvent event) {
CharSequence text = getText();
int action = event.getAction();
if (!(text instanceof Spannable)) {
return super.onTouchEvent(event);
}
Spannable buffer = (Spannable) text;
if (action == MotionEvent.ACTION_UP
|| action == MotionEvent.ACTION_DOWN
|| action == MotionEvent.ACTION_MOVE) {
TextView widget = this;
int x = (int) event.getX();
int y = (int) event.getY();
x -= widget.getTotalPaddingLeft();
y -= widget.getTotalPaddingTop();
x += widget.getScrollX();
y += widget.getScrollY();
Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
URLSpan[] link = buffer.getSpans(off, off, URLSpan.class);
if (link.length != 0) {
if (action == MotionEvent.ACTION_UP) {
if (mCurrentLink == link[0]) {
link[0].onClick(widget);
}
mCurrentLink = null;
buffer.removeSpan(mLinkFocusStyle);
} else if (action == MotionEvent.ACTION_DOWN) {
mCurrentLink = link[0];
buffer.setSpan(mLinkFocusStyle,
buffer.getSpanStart(link[0]),
buffer.getSpanEnd(link[0]),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return true;
}
}
mCurrentLink = null;
buffer.removeSpan(mLinkFocusStyle);
return super.onTouchEvent(event);
}
public static void setFontSizeChanged(boolean isChanged) {
mFontSizeChanged = isChanged;
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/ui/module/MyTextView.java
|
Java
|
asf20
| 3,502
|
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid.ui.module;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.BrowseActivity;
import com.ch_linghu.fanfoudroid.DmActivity;
import com.ch_linghu.fanfoudroid.FavoritesActivity;
import com.ch_linghu.fanfoudroid.FollowersActivity;
import com.ch_linghu.fanfoudroid.FollowingActivity;
import com.ch_linghu.fanfoudroid.MentionActivity;
import com.ch_linghu.fanfoudroid.ProfileActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.UserTimelineActivity;
/**
* 顶部主菜单切换浮动层
*
* @author lds
*
*/
public class MenuDialog extends Dialog {
private static final int PAGE_MINE = 0;
private static final int PAGE_PROFILE = 1;
private static final int PAGE_FOLLOWERS = 2;
private static final int PAGE_FOLLOWING = 3;
private static final int PAGE_HOME = 4;
private static final int PAGE_MENTIONS = 5;
private static final int PAGE_BROWSE = 6;
private static final int PAGE_FAVORITES = 7;
private static final int PAGE_MESSAGE = 8;
private List<int[]> pages = new ArrayList<int[]>();
{
pages.add(new int[] { R.drawable.menu_tweets, R.string.pages_mine });
pages.add(new int[] { R.drawable.menu_profile, R.string.pages_profile });
pages.add(new int[] { R.drawable.menu_followers,
R.string.pages_followers });
pages.add(new int[] { R.drawable.menu_following,
R.string.pages_following });
pages.add(new int[] { R.drawable.menu_list, R.string.pages_home });
pages.add(new int[] { R.drawable.menu_mentions, R.string.pages_mentions });
pages.add(new int[] { R.drawable.menu_listed, R.string.pages_browse });
pages.add(new int[] { R.drawable.menu_favorites, R.string.pages_search });
pages.add(new int[] { R.drawable.menu_create_list,
R.string.pages_message });
};
private GridView gridview;
public MenuDialog(Context context, boolean cancelable,
OnCancelListener cancelListener) {
super(context, cancelable, cancelListener);
// TODO Auto-generated constructor stub
}
public MenuDialog(Context context, int theme) {
super(context, theme);
// TODO Auto-generated constructor stub
}
public MenuDialog(Context context) {
super(context, R.style.Theme_Transparent);
setContentView(R.layout.menu_dialog);
// setTitle("Custom Dialog");
setCanceledOnTouchOutside(true);
// 设置window属性
LayoutParams a = getWindow().getAttributes();
a.gravity = Gravity.TOP;
a.dimAmount = 0; // 去背景遮盖
getWindow().setAttributes(a);
initMenu();
}
public void setPosition(int x, int y) {
LayoutParams a = getWindow().getAttributes();
if (-1 != x)
a.x = x;
if (-1 != y)
a.y = y;
getWindow().setAttributes(a);
}
private void goTo(Class<?> cls, Intent intent) {
if (getOwnerActivity().getClass() != cls) {
dismiss();
intent.setClass(getContext(), cls);
getContext().startActivity(intent);
} else {
String msg = getContext().getString(R.string.page_status_same_page);
Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
}
}
private void goTo(Class<?> cls) {
Intent intent = new Intent();
goTo(cls, intent);
}
private void initMenu() {
// 准备要添加的数据条目
List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();
for (int[] item : pages) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("image", item[0]);
map.put("title", getContext().getString(item[1]));
items.add(map);
}
// 实例化一个适配器
SimpleAdapter adapter = new SimpleAdapter(getContext(), items, // data
R.layout.menu_item, // grid item layout
new String[] { "title", "image" }, // data's key
new int[] { R.id.item_text, R.id.item_image }); // item view id
// 获得GridView实例
gridview = (GridView) findViewById(R.id.mygridview);
// 将GridView和数据适配器关联
gridview.setAdapter(adapter);
}
public void bindEvent(Activity activity) {
setOwnerActivity(activity);
// 绑定监听器
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
switch (position) {
case PAGE_MINE:
String user = TwitterApplication.getMyselfId(false);
String name = TwitterApplication.getMyselfName(false);
Intent intent = UserTimelineActivity.createIntent(user,
name);
goTo(UserTimelineActivity.class, intent);
break;
case PAGE_PROFILE:
goTo(ProfileActivity.class);
break;
case PAGE_FOLLOWERS:
goTo(FollowersActivity.class);
break;
case PAGE_FOLLOWING:
goTo(FollowingActivity.class);
break;
case PAGE_HOME:
goTo(TwitterActivity.class);
break;
case PAGE_MENTIONS:
goTo(MentionActivity.class);
break;
case PAGE_BROWSE:
goTo(BrowseActivity.class);
break;
case PAGE_FAVORITES:
goTo(FavoritesActivity.class);
break;
case PAGE_MESSAGE:
goTo(DmActivity.class);
break;
}
}
});
Button close_button = (Button) findViewById(R.id.close_menu);
close_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/ui/module/MenuDialog.java
|
Java
|
asf20
| 6,622
|
package com.ch_linghu.fanfoudroid.ui.module;
import android.content.Context;
import android.util.Log;
public class FeedbackFactory {
private static final String TAG = "FeedbackFactory";
public static enum FeedbackType {
DIALOG, PROGRESS, REFRESH
};
public static Feedback create(Context context, FeedbackType type) {
Feedback feedback = null;
switch (type) {
case PROGRESS:
feedback = new SimpleFeedback(context);
break;
}
if (null == feedback || !feedback.isAvailable()) {
feedback = new FeedbackAdapter(context);
Log.e(TAG, type + " feedback is not available.");
}
return feedback;
}
public static class FeedbackAdapter implements Feedback {
public FeedbackAdapter(Context context) {
}
@Override
public void start(CharSequence text) {
}
@Override
public void cancel(CharSequence text) {
}
@Override
public void success(CharSequence text) {
}
@Override
public void failed(CharSequence text) {
}
@Override
public void update(Object arg0) {
}
@Override
public boolean isAvailable() {
return true;
}
@Override
public void setIndeterminate(boolean indeterminate) {
}
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/ui/module/FeedbackFactory.java
|
Java
|
asf20
| 1,165
|
package com.ch_linghu.fanfoudroid.ui.module;
import android.app.Activity;
import android.view.MotionEvent;
import com.ch_linghu.fanfoudroid.BrowseActivity;
import com.ch_linghu.fanfoudroid.MentionActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterActivity;
/**
* MyActivityFlipper 利用左右滑动手势切换Activity
*
* 1. 切换Activity, 继承与 {@link ActivityFlipper} 2. 手势识别, 实现接口
* {@link Widget.OnGestureListener}
*
*/
public class MyActivityFlipper extends ActivityFlipper implements
Widget.OnGestureListener {
public MyActivityFlipper() {
super();
}
public MyActivityFlipper(Activity activity) {
super(activity);
// TODO Auto-generated constructor stub
}
// factory
public static MyActivityFlipper create(Activity activity) {
MyActivityFlipper flipper = new MyActivityFlipper(activity);
flipper.addActivity(BrowseActivity.class);
flipper.addActivity(TwitterActivity.class);
flipper.addActivity(MentionActivity.class);
flipper.setToastResource(new int[] { R.drawable.point_left,
R.drawable.point_center, R.drawable.point_right });
flipper.setInAnimation(R.anim.push_left_in);
flipper.setOutAnimation(R.anim.push_left_out);
flipper.setPreviousInAnimation(R.anim.push_right_in);
flipper.setPreviousOutAnimation(R.anim.push_right_out);
return flipper;
}
@Override
public boolean onFlingDown(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return false; // do nothing
}
@Override
public boolean onFlingUp(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return false; // do nothing
}
@Override
public boolean onFlingLeft(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
autoShowNext();
return true;
}
@Override
public boolean onFlingRight(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
autoShowPrevious();
return true;
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/ui/module/MyActivityFlipper.java
|
Java
|
asf20
| 1,958
|
/**
*
*/
package com.ch_linghu.fanfoudroid.ui.module;
import java.text.ParseException;
import java.util.Date;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.app.SimpleImageLoader;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class TweetCursorAdapter extends CursorAdapter implements TweetAdapter {
private static final String TAG = "TweetCursorAdapter";
private Context mContext;
public TweetCursorAdapter(Context context, Cursor cursor) {
super(context, cursor);
mContext = context;
if (context != null) {
mInflater = LayoutInflater.from(context);
}
if (cursor != null) {
// TODO: 可使用:
// Tweet tweet = StatusTable.parseCursor(cursor);
mUserTextColumn = cursor
.getColumnIndexOrThrow(StatusTable.USER_SCREEN_NAME);
mTextColumn = cursor.getColumnIndexOrThrow(StatusTable.TEXT);
mProfileImageUrlColumn = cursor
.getColumnIndexOrThrow(StatusTable.PROFILE_IMAGE_URL);
mCreatedAtColumn = cursor
.getColumnIndexOrThrow(StatusTable.CREATED_AT);
mSourceColumn = cursor.getColumnIndexOrThrow(StatusTable.SOURCE);
mInReplyToScreenName = cursor
.getColumnIndexOrThrow(StatusTable.IN_REPLY_TO_SCREEN_NAME);
mFavorited = cursor.getColumnIndexOrThrow(StatusTable.FAVORITED);
mThumbnailPic = cursor.getColumnIndexOrThrow(StatusTable.PIC_THUMB);
mMiddlePic = cursor.getColumnIndexOrThrow(StatusTable.PIC_MID);
mOriginalPic = cursor.getColumnIndexOrThrow(StatusTable.PIC_ORIG);
}
mMetaBuilder = new StringBuilder();
}
private LayoutInflater mInflater;
private int mUserTextColumn;
private int mTextColumn;
private int mProfileImageUrlColumn;
private int mCreatedAtColumn;
private int mSourceColumn;
private int mInReplyToScreenName;
private int mFavorited;
private int mThumbnailPic;
private int mMiddlePic;
private int mOriginalPic;
private StringBuilder mMetaBuilder;
/*
* private ProfileImageCacheCallback callback = new
* ProfileImageCacheCallback(){
*
* @Override public void refresh(String url, Bitmap bitmap) {
* TweetCursorAdapter.this.refresh(); }
*
* };
*/
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = mInflater.inflate(R.layout.tweet, parent, false);
TweetCursorAdapter.ViewHolder holder = new ViewHolder();
holder.tweetUserText = (TextView) view
.findViewById(R.id.tweet_user_text);
holder.tweetText = (TextView) view.findViewById(R.id.tweet_text);
holder.profileLayout = (FrameLayout) view.findViewById(R.id.profile_layout);
holder.profileImage = (ImageView) view.findViewById(R.id.profile_image);
holder.metaText = (TextView) view.findViewById(R.id.tweet_meta_text);
holder.fav = (ImageView) view.findViewById(R.id.tweet_fav);
holder.has_image = (ImageView) view.findViewById(R.id.tweet_has_image);
holder.tweetLayout=(LinearLayout)view.findViewById(R.id.tweet_layout);
view.setTag(holder);
return view;
}
private static class ViewHolder {
public LinearLayout tweetLayout;
public TextView tweetUserText;
public TextView tweetText;
public FrameLayout profileLayout;
public ImageView profileImage;
public TextView metaText;
public ImageView fav;
public ImageView has_image;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TweetCursorAdapter.ViewHolder holder = (TweetCursorAdapter.ViewHolder) view
.getTag();
SharedPreferences pref = TwitterApplication.mPref; // PreferenceManager.getDefaultSharedPreferences(mContext);;
boolean useProfileImage = pref.getBoolean(
Preferences.USE_PROFILE_IMAGE, true);
boolean useHighlightBackground = pref.getBoolean(
Preferences.HIGHLIGHT_BACKGROUND, true);
holder.tweetUserText.setText(cursor.getString(mUserTextColumn));
TextHelper.setSimpleTweetText(holder.tweetText,
cursor.getString(mTextColumn));
String profileImageUrl = cursor.getString(mProfileImageUrlColumn);
if (useProfileImage && !TextUtils.isEmpty(profileImageUrl)) {
holder.profileLayout.setVisibility(View.VISIBLE);
SimpleImageLoader.display(holder.profileImage, profileImageUrl);
} else {
holder.profileLayout.setVisibility(View.GONE);
}
if (cursor.getString(mFavorited).equals("true")) {
holder.fav.setVisibility(View.VISIBLE);
} else {
holder.fav.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(cursor.getString(mThumbnailPic))) {
holder.has_image.setVisibility(View.VISIBLE);
} else {
holder.has_image.setVisibility(View.GONE);
}
try {
Date createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(cursor
.getString(mCreatedAtColumn));
holder.metaText.setText(Tweet.buildMetaText(mMetaBuilder,
createdAt, cursor.getString(mSourceColumn),
cursor.getString(mInReplyToScreenName)));
} catch (ParseException e) {
Log.w(TAG, "Invalid created at data.");
}
/**
* 添加特殊行的背景色
*/
if (useHighlightBackground){
String myself = TwitterApplication.getMyselfName(false);
StringBuilder b = new StringBuilder();
b.append("@");
b.append(myself);
String to_myself = b.toString();
//FIXME: contains操作影响效率,应该在获得时作判断,置标志,在这里对标志进行直接判断。
if(holder.tweetUserText.getText().equals(myself)){
holder.tweetLayout.setBackgroundResource(R.drawable.list_selector_self);
holder.profileLayout.setBackgroundResource(R.color.self_background);
}else if(holder.tweetText.getText().toString().contains(to_myself)){
holder.tweetLayout.setBackgroundResource(R.drawable.list_selector_mention);
holder.profileLayout.setBackgroundResource(R.color.mention_background);
}else{
holder.tweetLayout.setBackgroundResource(android.R.drawable.list_selector_background);
holder.profileLayout.setBackgroundResource(android.R.color.transparent);
}
}else{
holder.tweetLayout.setBackgroundResource(android.R.drawable.list_selector_background);
holder.profileLayout.setBackgroundResource(android.R.color.transparent);
}
}
@Override
public void refresh() {
getCursor().requery();
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/ui/module/TweetCursorAdapter.java
|
Java
|
asf20
| 6,786
|
package com.ch_linghu.fanfoudroid.ui.module;
public interface Feedback {
public boolean isAvailable();
public void start(CharSequence text);
public void cancel(CharSequence text);
public void success(CharSequence text);
public void failed(CharSequence text);
public void update(Object arg0);
public void setIndeterminate(boolean indeterminate);
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/ui/module/Feedback.java
|
Java
|
asf20
| 361
|
package com.ch_linghu.fanfoudroid.ui.module;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.User;
import com.ch_linghu.fanfoudroid.fanfou.Weibo;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
/*
* 用于用户的Adapter
*/
public class UserArrayAdapter extends BaseAdapter implements TweetAdapter {
private static final String TAG = "UserArrayAdapter";
private static final String USER_ID = "userId";
protected ArrayList<User> mUsers;
private Context mContext;
protected LayoutInflater mInflater;
public UserArrayAdapter(Context context) {
mUsers = new ArrayList<User>();
mContext = context;
mInflater = LayoutInflater.from(mContext);
}
@Override
public int getCount() {
return mUsers.size();
}
@Override
public Object getItem(int position) {
return mUsers.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
private static class ViewHolder {
public ImageView profileImage;
public TextView screenName;
public TextView userId;
public TextView lastStatus;
public TextView followBtn;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
SharedPreferences pref = TwitterApplication.mPref; // PreferenceManager.getDefaultSharedPreferences(mContext);
boolean useProfileImage = pref.getBoolean(
Preferences.USE_PROFILE_IMAGE, true);
if (convertView == null) {
view = mInflater.inflate(R.layout.follower_item, parent, false);
ViewHolder holder = new ViewHolder();
holder.profileImage = (ImageView) view
.findViewById(R.id.profile_image);
holder.screenName = (TextView) view.findViewById(R.id.screen_name);
holder.userId = (TextView) view.findViewById(R.id.user_id);
// holder.lastStatus = (TextView)
// view.findViewById(R.id.last_status);
holder.followBtn = (TextView) view.findViewById(R.id.follow_btn);
view.setTag(holder);
} else {
view = convertView;
}
ViewHolder holder = (ViewHolder) view.getTag();
final User user = mUsers.get(position);
String profileImageUrl = user.profileImageUrl;
if (useProfileImage) {
if (!TextUtils.isEmpty(profileImageUrl)) {
holder.profileImage
.setImageBitmap(TwitterApplication.mImageLoader.get(
profileImageUrl, callback));
}
} else {
holder.profileImage.setVisibility(View.GONE);
}
// holder.profileImage.setImageBitmap(ImageManager.mDefaultBitmap);
holder.screenName.setText(user.screenName);
holder.userId.setText(user.id);
// holder.lastStatus.setText(user.lastStatus);
holder.followBtn.setText(user.isFollowing ? mContext
.getString(R.string.general_del_friend) : mContext
.getString(R.string.general_add_friend));
holder.followBtn
.setOnClickListener(user.isFollowing ? new OnClickListener() {
@Override
public void onClick(View v) {
// Toast.makeText(mContext, user.name+"following",
// Toast.LENGTH_SHORT).show();
delFriend(user.id,v);
}
} : new OnClickListener() {
@Override
public void onClick(View v) {
// Toast.makeText(mContext, user.name+"not following",
// Toast.LENGTH_SHORT).show();
addFriend(user.id,v);
}
});
return view;
}
public void refresh(ArrayList<User> users) {
mUsers = (ArrayList<User>)users.clone();
notifyDataSetChanged();
}
@Override
public void refresh() {
notifyDataSetChanged();
}
private ImageLoaderCallback callback = new ImageLoaderCallback() {
@Override
public void refresh(String url, Bitmap bitmap) {
UserArrayAdapter.this.refresh();
}
};
/**
* 取消关注
*
* @param id
*/
private void delFriend(final String id,final View v) {
Builder diaBuilder = new AlertDialog.Builder(mContext).setTitle("关注提示")
.setMessage("确实要取消关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (cancelFollowingTask != null
&& cancelFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
cancelFollowingTask = new CancelFollowingTask();
cancelFollowingTask.setListener(new TaskAdapter() {//闭包?
@Override
public void onPostExecute(GenericTask task,
TaskResult result) {
if (result == TaskResult.OK) {
//添加成功后动态改变按钮
TextView followBtn=(TextView)v.findViewById(R.id.follow_btn);
followBtn.setText("添加关注");
followBtn.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View view) {
addFriend(id,view);
}
});
Toast.makeText(mContext, "取消关注成功",
Toast.LENGTH_SHORT).show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(mContext, "取消关注失败",
Toast.LENGTH_SHORT).show();
}
}
@Override
public String getName() {
return null;
}
});
TaskParams params = new TaskParams();
params.put(USER_ID, id);
cancelFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
private GenericTask cancelFollowingTask;
/**
* 取消关注
*
* @author Dino
*
*/
private class CancelFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
String userId = params[0].getString(USER_ID);
getApi().destroyFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private GenericTask setFollowingTask;
/**
* 设置关注
*
* @param id
*/
private void addFriend(final String id,final View view) {
Builder diaBuilder = new AlertDialog.Builder(mContext).setTitle("关注提示")
.setMessage("确实要添加关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (setFollowingTask != null
&& setFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
setFollowingTask = new SetFollowingTask();
setFollowingTask
.setListener(new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
//添加成功后动态改变按钮
TextView followBtn=(TextView)view.findViewById(R.id.follow_btn);
followBtn.setText("取消关注");
followBtn.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
delFriend(id,v);
}
});
Toast.makeText(mContext, "关注成功", Toast.LENGTH_SHORT).show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(mContext, "关注失败", Toast.LENGTH_SHORT).show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
});
TaskParams params = new TaskParams();
params.put(USER_ID, id);
setFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
/**
* 设置关注
*
* @author Dino
*
*/
private class SetFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
String userId = params[0].getString(USER_ID);
getApi().createFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
public Weibo getApi() {
return TwitterApplication.mApi;
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/ui/module/UserArrayAdapter.java
|
Java
|
asf20
| 9,914
|
package com.ch_linghu.fanfoudroid.ui.module;
import android.graphics.Color;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Selection;
import android.text.TextWatcher;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.TextView;
public class TweetEdit {
private EditText mEditText;
private TextView mCharsRemainText;
private int originTextColor;
public TweetEdit(EditText editText, TextView charsRemainText) {
mEditText = editText;
mCharsRemainText = charsRemainText;
originTextColor = mCharsRemainText.getTextColors().getDefaultColor();
mEditText.addTextChangedListener(mTextWatcher);
mEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
MAX_TWEET_INPUT_LENGTH) });
}
private static final int MAX_TWEET_LENGTH = 140;
private static final int MAX_TWEET_INPUT_LENGTH = 400;
public void setTextAndFocus(String text, boolean start) {
setText(text);
Editable editable = mEditText.getText();
if (!start) {
Selection.setSelection(editable, editable.length());
} else {
Selection.setSelection(editable, 0);
}
mEditText.requestFocus();
}
public void setText(String text) {
mEditText.setText(text);
updateCharsRemain();
}
private TextWatcher mTextWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable e) {
updateCharsRemain();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
};
public void updateCharsRemain() {
int remaining = MAX_TWEET_LENGTH - mEditText.length();
if (remaining < 0) {
mCharsRemainText.setTextColor(Color.RED);
} else {
mCharsRemainText.setTextColor(originTextColor);
}
mCharsRemainText.setText(remaining + "");
}
public String getText() {
return mEditText.getText().toString();
}
public void setEnabled(boolean b) {
mEditText.setEnabled(b);
}
public void setOnKeyListener(OnKeyListener listener) {
mEditText.setOnKeyListener(listener);
}
public void addTextChangedListener(TextWatcher watcher) {
mEditText.addTextChangedListener(watcher);
}
public void requestFocus() {
mEditText.requestFocus();
}
public EditText getEditText() {
return mEditText;
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/ui/module/TweetEdit.java
|
Java
|
asf20
| 2,457
|
package com.ch_linghu.fanfoudroid.ui.module;
import java.util.ArrayList;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.app.SimpleImageLoader;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class TweetArrayAdapter extends BaseAdapter implements TweetAdapter {
private static final String TAG = "TweetArrayAdapter";
protected ArrayList<Tweet> mTweets;
private Context mContext;
protected LayoutInflater mInflater;
protected StringBuilder mMetaBuilder;
public TweetArrayAdapter(Context context) {
mTweets = new ArrayList<Tweet>();
mContext = context;
mInflater = LayoutInflater.from(mContext);
mMetaBuilder = new StringBuilder();
}
@Override
public int getCount() {
return mTweets.size();
}
@Override
public Object getItem(int position) {
return mTweets.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
private static class ViewHolder {
public LinearLayout tweetLayout;
public TextView tweetUserText;
public TextView tweetText;
public FrameLayout profileLayout;
public ImageView profileImage;
public TextView metaText;
public ImageView fav;
public ImageView has_image;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
SharedPreferences pref = TwitterApplication.mPref; // PreferenceManager.getDefaultSharedPreferences(mContext);
boolean useProfileImage = pref.getBoolean(
Preferences.USE_PROFILE_IMAGE, true);
boolean useHighlightBackground = pref.getBoolean(
Preferences.HIGHLIGHT_BACKGROUND, true);
if (convertView == null) {
view = mInflater.inflate(R.layout.tweet, parent, false);
ViewHolder holder = new ViewHolder();
holder.tweetLayout=(LinearLayout) view.findViewById(R.id.tweet_layout);
holder.tweetUserText = (TextView) view
.findViewById(R.id.tweet_user_text);
holder.tweetText = (TextView) view.findViewById(R.id.tweet_text);
holder.profileLayout = (FrameLayout) view
.findViewById(R.id.profile_layout);
holder.profileImage = (ImageView) view
.findViewById(R.id.profile_image);
holder.metaText = (TextView) view
.findViewById(R.id.tweet_meta_text);
holder.fav = (ImageView) view.findViewById(R.id.tweet_fav);
holder.has_image = (ImageView) view
.findViewById(R.id.tweet_has_image);
view.setTag(holder);
} else {
view = convertView;
}
ViewHolder holder = (ViewHolder) view.getTag();
Tweet tweet = mTweets.get(position);
holder.tweetUserText.setText(tweet.screenName);
TextHelper.setSimpleTweetText(holder.tweetText, tweet.text);
// holder.tweetText.setText(tweet.text, BufferType.SPANNABLE);
String profileImageUrl = tweet.profileImageUrl;
if (useProfileImage && !TextUtils.isEmpty(profileImageUrl)) {
holder.profileLayout.setVisibility(View.VISIBLE);
SimpleImageLoader.display(holder.profileImage, profileImageUrl);
} else {
holder.profileLayout.setVisibility(View.GONE);
}
holder.metaText.setText(Tweet.buildMetaText(mMetaBuilder,
tweet.createdAt, tweet.source, tweet.inReplyToScreenName));
if (tweet.favorited.equals("true")) {
holder.fav.setVisibility(View.VISIBLE);
} else {
holder.fav.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(tweet.thumbnail_pic)) {
holder.has_image.setVisibility(View.VISIBLE);
} else {
holder.has_image.setVisibility(View.GONE);
}
/**
* 添加特殊行的背景色
*/
if (useHighlightBackground){
String myself = TwitterApplication.getMyselfName(false);
StringBuilder b = new StringBuilder();
b.append("@");
b.append(myself);
String to_myself = b.toString();
//FIXME: contains操作影响效率,应该在获得时作判断,置标志,在这里对标志进行直接判断。
if(holder.tweetUserText.getText().equals(myself)){
holder.tweetLayout.setBackgroundResource(R.drawable.list_selector_self);
holder.profileLayout.setBackgroundResource(R.color.self_background);
}else if(holder.tweetText.getText().toString().contains(to_myself)){
holder.tweetLayout.setBackgroundResource(R.drawable.list_selector_mention);
holder.profileLayout.setBackgroundResource(R.color.mention_background);
}else{
holder.tweetLayout.setBackgroundResource(android.R.drawable.list_selector_background);
holder.profileLayout.setBackgroundResource(android.R.color.transparent);
}
}else{
holder.tweetLayout.setBackgroundResource(android.R.drawable.list_selector_background);
holder.profileLayout.setBackgroundResource(android.R.color.transparent);
}
return view;
}
public void refresh(ArrayList<Tweet> tweets) {
mTweets = tweets;
notifyDataSetChanged();
}
@Override
public void refresh() {
notifyDataSetChanged();
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/ui/module/TweetArrayAdapter.java
|
Java
|
asf20
| 5,626
|
package com.ch_linghu.fanfoudroid.ui.module;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.AbsListView;
import android.widget.ListView;
public class MyListView extends ListView implements ListView.OnScrollListener {
private int mScrollState = OnScrollListener.SCROLL_STATE_IDLE;
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
setOnScrollListener(this);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
boolean result = super.onInterceptTouchEvent(event);
if (mScrollState == OnScrollListener.SCROLL_STATE_FLING) {
return true;
}
return result;
}
private OnNeedMoreListener mOnNeedMoreListener;
public static interface OnNeedMoreListener {
public void needMore();
}
public void setOnNeedMoreListener(OnNeedMoreListener onNeedMoreListener) {
mOnNeedMoreListener = onNeedMoreListener;
}
private int mFirstVisibleItem;
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (mOnNeedMoreListener == null) {
return;
}
if (firstVisibleItem != mFirstVisibleItem) {
if (firstVisibleItem + visibleItemCount >= totalItemCount) {
mOnNeedMoreListener.needMore();
}
} else {
mFirstVisibleItem = firstVisibleItem;
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
mScrollState = scrollState;
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/ui/module/MyListView.java
|
Java
|
asf20
| 1,552
|
package com.ch_linghu.fanfoudroid.ui.module;
public interface IFlipper {
void showNext();
void showPrevious();
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/ui/module/IFlipper.java
|
Java
|
asf20
| 117
|
package com.ch_linghu.fanfoudroid.ui.module;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.SearchActivity;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.WriteActivity;
import com.ch_linghu.fanfoudroid.ui.base.Refreshable;
public class NavBar implements Widget {
private static final String TAG = "NavBar";
public static final int HEADER_STYLE_HOME = 1;
public static final int HEADER_STYLE_WRITE = 2;
public static final int HEADER_STYLE_BACK = 3;
public static final int HEADER_STYLE_SEARCH = 4;
private ImageView mRefreshButton;
private ImageButton mSearchButton;
private ImageButton mWriteButton;
private TextView mTitleButton;
private Button mBackButton;
private ImageButton mHomeButton;
private MenuDialog mDialog;
private EditText mSearchEdit;
/** @deprecated 已废弃 */
protected AnimationDrawable mRefreshAnimation;
private ProgressBar mProgressBar = null; // 进度条(横)
private ProgressBar mLoadingProgress = null; // 旋转图标
public NavBar(int style, Context context) {
initHeader(style, (Activity) context);
}
private void initHeader(int style, final Activity activity) {
switch (style) {
case HEADER_STYLE_HOME:
addTitleButtonTo(activity);
addWriteButtonTo(activity);
addSearchButtonTo(activity);
addRefreshButtonTo(activity);
break;
case HEADER_STYLE_BACK:
addBackButtonTo(activity);
addWriteButtonTo(activity);
addSearchButtonTo(activity);
addRefreshButtonTo(activity);
break;
case HEADER_STYLE_WRITE:
addBackButtonTo(activity);
break;
case HEADER_STYLE_SEARCH:
addBackButtonTo(activity);
addSearchBoxTo(activity);
addSearchButtonTo(activity);
break;
}
}
/**
* 搜索硬按键行为
*
* @deprecated 这个不晓得还有没有用, 已经是已经被新的搜索替代的吧 ?
*/
public boolean onSearchRequested() {
/*
* Intent intent = new Intent(); intent.setClass(this,
* SearchActivity.class); startActivity(intent);
*/
return true;
}
/**
* 添加[LOGO/标题]按钮
*
* @param acticity
*/
private void addTitleButtonTo(final Activity acticity) {
mTitleButton = (TextView) acticity.findViewById(R.id.title);
mTitleButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int top = mTitleButton.getTop();
int height = mTitleButton.getHeight();
int x = top + height;
if (null == mDialog) {
Log.d(TAG, "Create menu dialog.");
mDialog = new MenuDialog(acticity);
mDialog.bindEvent(acticity);
mDialog.setPosition(-1, x);
}
// toggle dialog
if (mDialog.isShowing()) {
mDialog.dismiss(); // 没机会触发
} else {
mDialog.show();
}
}
});
}
/**
* 设置标题
*
* @param title
*/
public void setHeaderTitle(String title) {
if (null != mTitleButton) {
mTitleButton.setText(title);
TextPaint tp = mTitleButton.getPaint();
tp.setFakeBoldText(true); // 中文粗体
}
}
/**
* 设置标题
*
* @param resource
* R.string.xxx
*/
public void setHeaderTitle(int resource) {
if (null != mTitleButton) {
mTitleButton.setBackgroundResource(resource);
}
}
/**
* 添加[刷新]按钮
*
* @param activity
*/
private void addRefreshButtonTo(final Activity activity) {
mRefreshButton = (ImageView) activity.findViewById(R.id.top_refresh);
mProgressBar = (ProgressBar) activity.findViewById(R.id.progress_bar);
mLoadingProgress = (ProgressBar) activity
.findViewById(R.id.top_refresh_progressBar);
mRefreshButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (activity instanceof Refreshable) {
((Refreshable) activity).doRetrieve();
} else {
Log.e(TAG, "The current view "
+ activity.getClass().getName()
+ " cann't be retrieved");
}
}
});
}
/**
* Start/Stop Top Refresh Button's Animation
*
* @param animate
* start or stop
* @deprecated use feedback
*/
public void setRefreshAnimation(boolean animate) {
if (mRefreshAnimation != null) {
if (animate) {
mRefreshAnimation.start();
} else {
mRefreshAnimation.setVisible(true, true); // restart
mRefreshAnimation.start(); // goTo frame 0
mRefreshAnimation.stop();
}
} else {
Log.w(TAG, "mRefreshAnimation is null");
}
}
/**
* 添加[搜索]按钮
*
* @param activity
*/
private void addSearchButtonTo(final Activity activity) {
mSearchButton = (ImageButton) activity.findViewById(R.id.search);
mSearchButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startSearch(activity);
}
});
}
// 这个方法会在SearchActivity里重写
protected boolean startSearch(final Activity activity) {
Intent intent = new Intent();
intent.setClass(activity, SearchActivity.class);
activity.startActivity(intent);
return true;
}
/**
* 添加[搜索框]
*
* @param activity
*/
private void addSearchBoxTo(final Activity activity) {
mSearchEdit = (EditText) activity.findViewById(R.id.search_edit);
}
/**
* 添加[撰写]按钮
*
* @param activity
*/
private void addWriteButtonTo(final Activity activity) {
mWriteButton = (ImageButton) activity.findViewById(R.id.writeMessage);
mWriteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// forward to write activity
Intent intent = new Intent();
intent.setClass(v.getContext(), WriteActivity.class);
v.getContext().startActivity(intent);
}
});
}
/**
* 添加[回首页]按钮
*
* @param activity
*/
@SuppressWarnings("unused")
private void addHomeButton(final Activity activity) {
mHomeButton = (ImageButton) activity.findViewById(R.id.home);
mHomeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// 动画
Animation anim = AnimationUtils.loadAnimation(v.getContext(),
R.anim.scale_lite);
v.startAnimation(anim);
// forward to TwitterActivity
Intent intent = new Intent();
intent.setClass(v.getContext(), TwitterActivity.class);
v.getContext().startActivity(intent);
}
});
}
/**
* 添加[返回]按钮
*
* @param activity
*/
private void addBackButtonTo(final Activity activity) {
mBackButton = (Button) activity.findViewById(R.id.top_back);
// 中文粗体
// TextPaint tp = backButton.getPaint();
// tp.setFakeBoldText(true);
mBackButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Go back to previous activity
activity.finish();
}
});
}
public void destroy() {
// dismiss dialog before destroy
// to avoid android.view.WindowLeaked Exception
if (mDialog != null) {
mDialog.dismiss();
mDialog = null;
}
mRefreshButton = null;
mSearchButton = null;
mWriteButton = null;
mTitleButton = null;
mBackButton = null;
mHomeButton = null;
mSearchButton = null;
mSearchEdit = null;
mProgressBar = null;
mLoadingProgress = null;
}
public ImageView getRefreshButton() {
return mRefreshButton;
}
public ImageButton getSearchButton() {
return mSearchButton;
}
public ImageButton getWriteButton() {
return mWriteButton;
}
public TextView getTitleButton() {
return mTitleButton;
}
public Button getBackButton() {
return mBackButton;
}
public ImageButton getHomeButton() {
return mHomeButton;
}
public MenuDialog getDialog() {
return mDialog;
}
public EditText getSearchEdit() {
return mSearchEdit;
}
/** @deprecated 已废弃 */
public AnimationDrawable getRefreshAnimation() {
return mRefreshAnimation;
}
public ProgressBar getProgressBar() {
return mProgressBar;
}
public ProgressBar getLoadingProgress() {
return mLoadingProgress;
}
@Override
public Context getContext() {
if (null != mDialog) {
return mDialog.getContext();
}
if (null != mTitleButton) {
return mTitleButton.getContext();
}
return null;
}
}
|
061304011116lyj-lyj
|
src/com/ch_linghu/fanfoudroid/ui/module/NavBar.java
|
Java
|
asf20
| 8,578
|