gson

Convert object to JSON in Android

 

5 down vote accepted

Most people are using gson: http://code.google.com/p/google-gson/

Gson gson = new Gson(); String json = gson.toJson(myObj); 

gson ignoring map entries with value=null
up vote 2 down vote favorite
share [g+] share [fb] share [tw]

Gson gson = new Gson();

Mapmap = new HashMap();
map.put(“a”,1);
map.put(“b”,null);

System.out.println(gson.toJson(map));; //prints {“a”:1}

how do I get it to include all entries? Thank you
java json gson
link|improve this question

asked Oct 13 ’10 at 12:47
m2o
387613

75% accept rate

feedback
1 Answer
active oldest votes
up vote 2 down vote accepted

http://sites.google.com/site/gson/gson-user-guide#TOC-Null-Object-Support

Gson gson = new GsonBuilder().serializeNulls().create();

PHP “===”与“==”区别

Php中三个等号与两个等号的区别:

==你知道吧,是比较两个值 ===也是一样的功能,但是===要求的比较严格 ==会在把两个值自动转换成同类型后再比较,而===在比较前不转换 当a=3时 a===3是成立的,a==”3.0″也成立,而a===”3.0″是不成立的。

dedecms图集上传图片提示FILEID和302解决办法

提示302错误原因swfupload在linux环境下session机制问题,解决方法如下:

下面的php代码粘贴到博客的时候单引号和双引号变为中文字符的了,注意修改下哈~!

在include/userlogin.class.php文件中的第二行session_start();前加上

if (isset($_POST["PHPSESSID"])) {

session_id($_POST["PHPSESSID"]);

} else if (isset($_GET["PHPSESSID"])) {

session_id($_GET["PHPSESSID"]);

}

提示FILEID的是由于utf-8的bom的问题,解决方法如下:

<?php
//remove the utf-8 boms
//by magicbug at gmail dot com
if (isset($_GET['dir'])){ //config the basedir
$basedir=$_GET['dir'];
}else{
$basedir = ‘.’;
}
$auto = 1;
checkdir($basedir);
function checkdir($basedir){
if ($dh = opendir($basedir)) {
while (($file = readdir($dh)) !== false) {
if ($file != ‘.’ && $file != ‘..’){
if (!is_dir($basedir.”/”.$file)) {
echo “filename: $basedir/$file “;
echo checkBOM(“$basedir/$file”).”
“;
}else{
$dirname = $basedir.”/”.$file;
checkdir($dirname);
}
}
}
closedir($dh);
}
}
function checkBOM ($filename) {
global $auto;
$contents = file_get_contents($filename);
$charset[1] = substr($contents, 0, 1);
$charset[2] = substr($contents, 1, 1);
$charset[3] = substr($contents, 2, 1);
if (ord($charset[1]) == 239 && ord($charset[2]) == 187 && ord($charset[3]) == 191) {
if ($auto == 1) {
$rest = substr($contents, 3);
rewrite ($filename, $rest);
return (“<font color=red>BOM found, automatically removed.</font>”);
} else {
return (“<font color=red>BOM found.</font>”);
}
}
else return (“BOM Not Found.”);
}
function rewrite ($filename, $data) {
$filenum = fopen($filename, “w”);
flock($filenum, LOCK_EX);
fwrite($filenum, $data);
fclose($filenum);
}
?>

保存为1.php,放在网站根目录访问一下这个文件就可以了。

如果出错的话,提示

PHP Fatal error: Allowed memory size of 134217728 bytes exhausted 请尝试使用以下方法:

<?php
//remove the utf-8 boms
//by magicbug at gmail dot com
if (isset($_GET['dir'])){ //config the basedir
$basedir=$_GET['dir'];
}else{
$basedir = ‘.’;
}
$auto = 1;
checkdir($basedir);
echo (”
<font color=green>completed!</font>
“);
function checkdir($basedir)
{
if ($dh = opendir($basedir))
{
while (($file = readdir($dh)) !== false)
{
if ($file != ‘.’ && $file != ‘..’)
{
if (!is_dir($basedir.”/”.$file))
{
//echo “filename: $basedir/$file “;
checkBOM(“$basedir/$file”);
}
else
{
$dirname = $basedir.”/”.$file;
checkdir($dirname);
}
}
}
closedir($dh);
}
}
function checkBOM ($filename) {
global $auto;
$contents = file_get_contents($filename,NULL,NULL,0,10);
$charset[1] = substr($contents, 0, 1);
$charset[2] = substr($contents, 1, 1);
$charset[3] = substr($contents, 2, 1);
if (ord($charset[1]) == 239 && ord($charset[2]) == 187 && ord($charset[3]) == 191) {
if ($auto == 1) {
//$rest = substr($contents, 3);
//rewrite ($filename, $rest);
echo ($filename.”——–”.”<font color=red>BOM found</font>
“);
} else {
//return (“<font color=red>BOM found.</font>”);
}
}
//else return (“BOM Not Found.”);
}
function rewrite ($filename, $data) {
$filenum = fopen($filename, “w”);
flock($filenum, LOCK_EX);
fwrite($filenum, $data);
fclose($filenum);
}
?>

检查带有bom的文件,进行手工修改

Android ListView 技巧 (一)

Android ListView 技巧 (一)
2011/03/10 19:09

关键字: Android ListView Header

最近使用OPhone SDK来开发一个应用程序。在使用的过程中,出现了一个问题,个人估计是Ophone底层framework的bug。但是没有底层的支持,苦于没有办法,所以只能自己绕过。

一:ListView Header的使用

在 各用控件的使用中,估计ListView是最常用的一个,各种各样的市场都使用ListView来显示数据。但是也有不使用ListView而使用 LiearLayout自己向里添加各种组件的(相信这种实现方式的市场的开发人员也不怎么样,会浪费大量的资源,使用更多的内存)。

以“以掌上应用汇”为例:

 

它在上面显示4个推荐的内容,下面使用一个个ITEM来显示各个应用程序。

使用过ListView开发的人都知道,在ListView外边是不能再嵌套ScrollView的,所以想要头部这种不同的结构显示出来,并且随着ListView的滚动而滚动其实是很简单的。但是网络上有很多种关于这样的讨论,如何的实现,实在不知道为什么。

首先是两种设计:

1,固定的头部,这种头部不随着ListView的滚动而滚动。

就像excel中A,B,C,D,E这样的列名,它们不会随着内容的滚动而滚动。好处当然是可以一直 的指示使用代表的内容是什么意义,坏处是会占用用户的操作空间。

2,不固定的头部,头部不随着ListView的滚动而滚动

就像下图中的,姓名,性别,年龄这样的列名,它他们会随着内容的滚动而变得不可见。它的好处和坏处正好和固定的反过来。

像上面的图中的“以掌上应用汇”的例子,它很明显不能使用固定的头部,因为设备的可视区域本来就小,而且头部占用的空间也多。

两种设计的实现:

1,固定的头部实现起来很简单,把View放在ListView的外边就可以,示例:

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”

android:layout_width=”fill_parent”  android:layout_height=”fill_parent” android:orientation=”vertical”>

<include layout=”@layout/fixed_header_view” />

<ListView android:id=”@id/android:list”  android:layout_width=”fill_parent”

android:layout_height=”wrap_content” />

<TextView android:id=”@id/android:empty”

android:layout_width=”fill_parent”

android:layout_height=”wrap_content”

android:text=”@string/empty_msg”/>

</LinearLayout>

2,不固定头部的实现,其实实现起来真的很简单。

在应用程序中把头部inflate出来,然后调用ListView的下面两个方法中的一个就可以(具体请参考API doc)

public void addHeaderView(View v);

public void addHeaderView(View v, Object data, boolean isSelectable);

就可以为ListView添加一个头部,它会随着ListView的滚动而滚动。但是要注意的是

2-1:addHeaderView必须得在setAdapter之前被调用

2-2: 在AdapterView.OnItemClickListener的public void onItemClick(AdapterView<?> parent, View view, int position,long id) 中,position中计算header的,就是说,你给ListView的setAdapter的数据会从headerCount开始计数,所以如果你 想在自己的Adapter中取数据,你需要减去headerCount。

示例:

// SOME CODE init ListView and setHeader

ListView listView = getListView();

View header = LayoutInflater.from(this).inflate(R.layout.scrolled_header_view, null);

// Do another init to set content for header and add event handler.

listView.addHeaderView(header);

listView.setAdapter(myAdapter);

在响应public void onItemClick(AdapterView<?> parent, View view, int position,long id)时

position -= listView.getHeaderViewsCount(); // 需要减去headerCount

MyItem item = myAdapter.getItem(position);

 

网 络上有关于header使用的介绍,大部分是想在ListView外添加一个ScrollView,可是这样的方案是不可行的。所以就有自己使用 ListView来添加各种View来实现,这些View必须被创建出来占用大量的宝贵资源,这样就无法使用ListView的好处,而且代码也不好维 护。

像这种只有一个View与其它项目不同的,可以使用header。因为ListView的状态是由系统来维护的,不但能节约代码,方便维护,而且能节约内存的使用。在下一节会介绍多种View在一个ListView中的实现。

TabActivity 返回键 dispatchKeyEvent

我们知道,在普通的Activity中可以重写onKeyDown(int keyCode, KeyEvent event)方法对手机按键进行监听,而当要监听的Activity为TabActivity时(其实ListActivity也一样),这个方法并不起作用。下面是解决办法:

今天就为这个事纠结了很久,正在开发的应用的首页是一个TabActivity,当用户按下返回键时会退出程序,而这可能是用户无意而为之的,所以当用户按下返回键时要给一个提示。常规方法,像上文说的,重写onKeyDown(int keyCode, KeyEvent event),根本不起作用;又发现SDK2.0以后新增了一个专门针对返回键的方法onBackPressed(),还是不起作用。google了很久,也没发现什么好的解决办法。只有自己动手了,打开SDK文档,仔细看了一下,发现有一个dispatchKeyEvent(KeyEvent event),一试果然管用,下面是一段示例代码,注意在if判断中要加一个event.getAction() == KeyEvent.ACTION_DOWN判断,因为按键有两个事件ACTION_DOWNACTION_UP,也就是按下和松开,如果不加这个判断,代码会执行两遍,而在下面的代码中就是弹两次AlertDialog。

 

 

public boolean dispatchKeyEvent(KeyEvent event) {

if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_BACK) { 

AlertDialog.Builder builder = new AlertDialog.Builder(context);

builder.setMessage(“您确定退出吗?”) .setTitle(“友情提示”) .setNegativeButton(“取消”, newDialogInterface.OnClickListener() { @Override

 public void onClick(DialogInterface arg0, int arg1) { arg0.cancel(); } }) .setPositiveButton(“确定”, newDialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { 

Main.this.finish();

}

}

);

AlertDialog alert = builder.create();

alert.show(); 

return false; }

 return super.dispatchKeyEvent(event);

};

UIControl触发事件

UIControl继承自UIView,有
addTarget:action:forControlEvents:方法来触发事件。
UIControl *myView = [[UIControl alloc]
initWithFrame:CGRectMake(10, 15, 160, 80)
];
[myView addTarget:self
action:@selector(changeLable:)
forControlEvents:UIControlEventTouchUpInside];//每一个view都会触发这个事件
-(void)changeLable:(id)sender{
for (UIControl *control in recvAddressCellArray) {
//如果view的个数不唯一,那么我们需要把它放在一个
NSMutableArray中,这里就是recvAddressCellArray
UIView *vi = (UIView*)control;//将UIControl类型强制转化为UIView类型,为了是让我们找到subviews上的控件
NSArray *sup = vi.subviews;//把subviews上的控件放在数组中
for (UILabel *lab in sup) {
[lab setTextColor:UIColorFromRGB(0x373737)];
}
}
}
一定要记住,每一次重新加载的地方要[recvAddressCellArray
removeAllObjects
];

在uinavigationbar添加返回按钮

UINavigationItem *item = [navigationBar.items objectAtIndex:0];
UINavigationItem *back = [[UINavigationItem alloc] initWithTitle:@”返回”];
NSArray *items = [[NSArray alloc] initWithObjects:back,item,nil];
[navigationBar setItems:items]; navigationBar.delegate=self;
使用到UINavigationBar的delegate:
- (BOOL)navigationBar:(UINavigationBar *)navigationBar
shouldPopItem:(UINavigationItem *)item{
[self goBack:nil];
return FALSE;
}

UIActionSheet的妙用(新浪发送消息后等待界面的设计)

//

//  PromptView.h

//  TabBarTest

//

//  Created by kimziv on 7/29/11.

//  Copyright 2011 __MyCompanyName__. All rights reserved.

//

#import <Foundation/Foundation.h>

@protocol PromptViewDelegate;

@interface PromptView : NSObject<UIActionSheetDelegate> {
UIActionSheet    *_promptView;
id<PromptViewDelegate>  _delegate;
}
@property(nonatomic,assign)id<PromptViewDelegate> delegate;

+ (PromptView *)sharedPromptView;
+ (void)setSharedDelegate:(id<PromptViewDelegate>)delegate;
- (void)showPromptView:(NSString *)promptText;
- (void)dismissPromptView;

@end

@protocol PromptViewDelegate <NSObject>

@optional
-(void)cancelButtonDidClicked:(id)sender;

@end

//

//  PromptView.m

//  TabBarTest

//

//  Created by kimziv on 7/29/11.

//  Copyright 2011 __MyCompanyName__. All rights reserved.

//

#import “PromptView.h”
#import “SynthesizeSingleton.h”

@implementation PromptView
@synthesize delegate=_delegate;
SYNTHESIZE_SINGLETON_FOR_CLASS(PromptView);

- (void)dealloc {
[_promptView release];
[super dealloc];
}

#pragma mark PromptView

- (void)createStatusView{
CGRect frame = CGRectMake(280, 10, 16, 16);
UIActivityIndicatorView* progressInd = [[UIActivityIndicatorView alloc] initWithFrame:frame];
[progressInd startAnimating];
progressInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;

_promptView = [[UIActionSheet alloc] initWithTitle:@”Connecting…” delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
_promptView.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
[_promptView addSubview:progressInd];

[progressInd release];

UIButton *cancelBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
cancelBtn.frame=CGRectMake(30, 10, 40, 20);
//UIButton *cancelBtn=[[UIButton alloc] initWithFrame:CGRectMake(20, 10, 50, 30)];
cancelBtn.titleLabel.font=[UIFont systemFontOfSize:12];
[cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
//[cancelBtn setBackgroundImage:[UIImage imageNamed:<#(NSString *)#>] forState:UIControlStateNormal];
cancelBtn.backgroundColor=[UIColor clearColor];
cancelBtn.alpha=0.5;
[cancelBtn addTarget:self action:@selector(cancelSend:) forControlEvents:UIControlEventTouchUpInside];
[_promptView addSubview:cancelBtn];
//[cancelBtn release];
}
-(IBAction)cancelSend:(id)sender{
[self dismissPromptView];
if ([_delegate respondsToSelector:@selector(cancelButtonDidClicked:)]) {
[_delegate cancelButtonDidClicked:sender];
}
}

- (void)showPromptView:(NSString *)statusText{
if(!_promptView)
{
[self createStatusView];
}

if(![_promptView superview])
[_promptView showInView:[[[[UIApplication sharedApplication] keyWindow] subviews] objectAtIndex:0]];

[_promptView setTitle:statusText];
}

- (void)dismissPromptView{
if([_promptView superview])
[_promptView dismissWithClickedButtonIndex:0 animated:YES];
if(_promptView)
{
[_promptView release];
_promptView = nil;
}
}

#pragma mark – UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{

}

+(void)setSharedDelegate:(id<PromptViewDelegate>)delegate{
[self sharedPromptView].delegate=delegate;
}

@end

//

//  SynthesizeSingleton.h

//  TabBarTest

//

//  Created by kimziv on 7/29/11.

//  Copyright 2011 __MyCompanyName__. All rights reserved.

//

#define SYNTHESIZE_SINGLETON_FOR_CLASS(classname)

static classname *shared##classname = nil;

+ (classname *)shared##classname

{

@synchronized(self)

{

if (shared##classname == nil)

{

shared##classname = [[self alloc] init];

}

}

return shared##classname;

}

+ (id)allocWithZone:(NSZone *)zone

{

@synchronized(self)

{

if (shared##classname == nil)

{

shared##classname = [super allocWithZone:zone];

return shared##classname;

}

}

return nil;

}

- (id)copyWithZone:(NSZone *)zone

{

return self;

}

- (id)retain

{

return self;

}

- (NSUInteger)retainCount

{

return NSUIntegerMax;

}

- (void)release

{

}

- (id)autorelease

{

return self;

}

带有placeholder的UITextView

  • UIPlaceHolderTextView.h
  • #import <Foundation/Foundation.h>
    
    @interface UIPlaceHolderTextView : UITextView {
        NSString *placeholder;
        UIColor *placeholderColor;
    
    @private
        UILabel *placeHolderLabel;
    }
    
    @property (nonatomic, retain) UILabel *placeHolderLabel;
    @property (nonatomic, retain) NSString *placeholder;
    @property (nonatomic, retain) UIColor *placeholderColor;
    
    -(void)textChanged:(NSNotification*)notification;
    
    @end
    
    
    
  • UIPlaceHolderTextView.m
  • #import "UIPlaceHolderTextView.h"
    
    @implementation UIPlaceHolderTextView
    
    @synthesize placeHolderLabel;
    @synthesize placeholder;
    @synthesize placeholderColor;
    
    - (void)dealloc
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        [placeHolderLabel release]; placeHolderLabel = nil;
        [placeholderColor release]; placeholderColor = nil;
        [placeholder release]; placeholder = nil;
        [super dealloc];
    }
    
    - (void)awakeFromNib
    {
        [super awakeFromNib];
        [self setPlaceholder:@""];
        [self setPlaceholderColor:[UIColor lightGrayColor]];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
    }
    
    - (id)initWithFrame:(CGRect)frame
    {
        if( (self = [super initWithFrame:frame]) )
        {
            [self setPlaceholder:@""];
            [self setPlaceholderColor:[UIColor lightGrayColor]];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
        }
        return self;
    }
    
    - (void)textChanged:(NSNotification *)notification
    {
        if([[self placeholder] length] == 0)
        {
            return;
        }
    
        if([[self text] length] == 0)
        {
            [[self viewWithTag:999] setAlpha:1];
        }
        else
        {
            [[self viewWithTag:999] setAlpha:0];
        }
    }
    
    - (void)drawRect:(CGRect)rect
    {
        if( [[self placeholder] length] > 0 )
        {
            if ( placeHolderLabel == nil )
            {
                placeHolderLabel = [[UILabel alloc] initWithFrame:CGRectMake(8,8,self.bounds.size.width - 16,0)];
                placeHolderLabel.lineBreakMode = UILineBreakModeWordWrap;
                placeHolderLabel.numberOfLines = 0;
                placeHolderLabel.font = self.font;
                placeHolderLabel.backgroundColor = [UIColor clearColor];
                placeHolderLabel.textColor = self.placeholderColor;
                placeHolderLabel.alpha = 0;
                placeHolderLabel.tag = 999;
                [self addSubview:placeHolderLabel];
            }
    
            placeHolderLabel.text = self.placeholder;
            [placeHolderLabel sizeToFit];
            [self sendSubviewToBack:placeHolderLabel];
        }
    
        if( [[self text] length] == 0 && [[self placeholder] length] > 0 )
        {
            [[self viewWithTag:999] setAlpha:1];
        }
    
        [super drawRect:rect];
    }
    
    @end
  • Reference URL:
  • http://stackoverflow.com/questions/1328638/placeholder-in-uitextview

如何实现圆角的UITextView

如题,代码如下
textView.layer.cornerRadius = 6;//角度可以自己调
textView.layer.masksToBounds = YES;

如果出现一下错误:

erro:request for member ‘cornerRadius’ in somenthing not a structure or union
erro:request for member ‘masksToBounds’ in somenthing not a structure or union

请先添加QuartzCore.framework

再在代码中#import <QuartzCore/QuartzCore.h>