android服务器app,Android客户端与服务器端的json数据交互(很详细)

packagecom.gem.hsx.activity;

importjava.io.File;

importjava.io.FileInputStream;

importjava.io.FileNotFoundException;

importjava.io.InputStream;

importjava.util.ArrayList;

importjava.util.List;

importcom.gem.hsx.bean.User;

importcom.gem.hsx.json.WriteJson;

importcom.gem.hsx.operation.Operaton;

importandroid.app.Activity;

importandroid.app.AlertDialog;

importandroid.app.Dialog;

importandroid.app.ProgressDialog;

importandroid.content.DialogInterface;

importandroid.content.Intent;

importandroid.graphics.Bitmap;

importandroid.graphics.BitmapFactory;

importandroid.net.Uri;

importandroid.os.Bundle;

importandroid.os.Handler;

importandroid.os.Message;

importandroid.view.View;

importandroid.view.View.OnClickListener;

importandroid.view.View.OnFocusChangeListener;

importandroid.widget.Button;

importandroid.widget.EditText;

importandroid.widget.ImageView;

importandroid.widget.RadioButton;

importandroid.widget.Toast;

publicclassRegisterextendsActivity {

Button submit;

Button select;

EditText etusername;

EditText etpassword;

RadioButton ckman;

RadioButton ckwoman;

EditText etage;

ImageView imgphoto;

String str;

String filepath=null;

String jsonString=null;

ProgressDialog dialog;

privatestaticfinalintREQUEST_EX =1;

String username=null;

String password=null;

String sex=null;

String age=null;

@Override

protectedvoidonCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.register);

init();

//etusername.addTextChangedListener(new MyTextWatcher());

etusername.setOnFocusChangeListener(newEtusernameOnFocusChange());

select.setOnClickListener(newSelectOnclick());

submit.setOnClickListener(newSubmitOnclick());

}

privatevoidinit()

{

submit=(Button) findViewById(R.id.submit);

select=(Button) findViewById(R.id.select);

etusername=(EditText) findViewById(R.id.etusername);

etpassword=(EditText) findViewById(R.id.etpassword);

ckman=(RadioButton) findViewById(R.id.ckman);

ckwoman=(RadioButton) findViewById(R.id.ckwoman);

etage=(EditText) findViewById(R.id.etage);

imgphoto=(ImageView) findViewById(R.id.imgphoto);

dialog=newProgressDialog(Register.this);

dialog.setTitle("上传数据中");

dialog.setMessage("请稍等...");

}

//  private   class MyTextWatcher implements TextWatcher

//  {

//

//      public void afterTextChanged(Editable s) {

//           str=etusername.getText().toString().trim();

//           if (str==null||str.length()<=0)

//           {

//              etusername.setError("用户名不能为空");

//           }

//           else

//           {

//               new Thread(new Runnable() {

//

//                  public void run() {

//                       Operaton operaton=new Operaton();

//                       String result= operaton.checkusername("Check", str);

//                       Message message=new Message();

//                       message.obj=result;

//                       handler.sendMessage(message);

//                  }

//              }).start();

//

//

//            }

//      }

//      public void beforeTextChanged(CharSequence s, int start, int count,

//              int after) {

//

//      }

//

//      public void onTextChanged(CharSequence s, int start, int before,

//              int count) {

//

//      }

//

//  }

//  Handler handler=new Handler()

//  {

//      @Override

//      public void handleMessage(Message msg) {

//          String msgobj=msg.obj.toString();

//          if (msgobj=="该用户名可用")

//          {

//              etusername.setFocusable(false);

//          }

//          else

//          {

//              etusername.requestFocus();

//              etusername.setError(msgobj);

//          }

//          super.handleMessage(msg);

//      }

//  };

//

privateclassEtusernameOnFocusChangeimplementsOnFocusChangeListener

{

publicvoidonFocusChange(View v,booleanhasFocus) {

if(!etusername.hasFocus()) {

str=etusername.getText().toString().trim();

if(str==null||str.length()<=0)

{

etusername.setError("用户名不能为空");

}

else

{

newThread(newRunnable() {

//如果用户名不为空,那么将用户名提交到服务器上进行验证,看用户名是否存在,就像JavaEE中利用

//ajax一样,虽然你看不到但是它却偷偷摸摸做了很多

publicvoidrun() {

Operaton operaton=newOperaton();

String result= operaton.checkusername("Check", str);

System.out.println("result:"+result);

Message message=newMessage();

message.obj=result;

handler.sendMessage(message);

}

}).start();

}

}

}

}

Handler handler=newHandler()

{

@Override

publicvoidhandleMessage(Message msg) {

String msgobj=msg.obj.toString();

System.out.println(msgobj);

System.out.println(msgobj.length());

if(msgobj.equals("t")) {

etusername.requestFocus();

etusername.setError("用户名"+str+"已存在");

}

else

{

etpassword.requestFocus();

}

super.handleMessage(msg);

}

};

privateclassSelectOnclickimplementsOnClickListener

{

publicvoidonClick(View v) {

Intent intent = newIntent();

intent.putExtra("explorer_title",

getString(R.string.dialog_read_from_dir));

intent.setDataAndType(Uri.fromFile(newFile("/sdcard")),"*/*");

intent.setClass(Register.this, ExDialog.class);

startActivityForResult(intent, REQUEST_EX);

}

}

protectedvoidonActivityResult(intrequestCode,intresultCode,

Intent intent) {

if(resultCode == RESULT_OK) {

Uri uri = intent.getData();

filepath=uri.toString().substring(6);

System.out.println(filepath);

//用户的头像是不是图片格式

if(filepath.endsWith("jpg")||filepath.endsWith("png"))

{

File file=newFile(filepath);

try{

InputStream inputStream=newFileInputStream(file);

Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

imgphoto.setImageBitmap(bitmap);//如果是就将图片显示出来

} catch(FileNotFoundException e) {

e.printStackTrace();

}

submit.setClickable(true);

}

else

{

submit.setClickable(false);

alert();

}

}

}

privateclassSubmitOnclickimplementsOnClickListener

{

publicvoidonClick(View v) {

username=etusername.getText().toString().trim();

password=etpassword.getText().toString().trim();

if(ckman.isChecked()) {

sex="男";

}

else{

sex="女";

}

age=etage.getText().toString().trim();

if(age==null||age.length()<=0)

{

etage.requestFocus();

etage.setError("年龄不能为空");

return;

}

dialog.show();

newThread(newRunnable() {

publicvoidrun() {

Operaton operaton=newOperaton();

File file=newFile(filepath);

String photo=operaton.uploadFile(file, "ImgReciver");

//先进行图片上传的操作,然后服务器返回图片保存在服务器的路径,

System.out.println("photo---->"+photo);

System.out.println("sex:------>"+sex);

User user=newUser(username, password, sex, age,photo);

//构造一个user对象

List list=newArrayList();

list.add(user);

WriteJson writeJson=newWriteJson();

//将user对象写出json形式字符串

jsonString= writeJson.getJsonData(list);

System.out.println(jsonString);

String result= operaton.UpData("Register", jsonString);

Message msg=newMessage();

System.out.println("result---->"+result);

msg.obj=result;

handler1.sendMessage(msg);

}

}).start();

}

}

privatevoidalert()

{

Dialog dialog = newAlertDialog.Builder(this)

.setTitle("提示")

.setMessage("您选择的不是有效的图片")

.setPositiveButton("确定",

newDialogInterface.OnClickListener() {

publicvoidonClick(DialogInterface dialog,

intwhich) {

filepath = null;

}

})

.create();

dialog.show();

}

Handler handler1=newHandler()

{

@Override

publicvoidhandleMessage(Message msg) {

dialog.dismiss();

String msgobj=msg.obj.toString();

if(msgobj.equals("t"))

{

Toast.makeText(Register.this,"注册成功",0).show();

Intent intent=newIntent();

intent.setClass(Register.this, LoginRegisterActivity.class);

startActivity(intent);

}

else{

Toast.makeText(Register.this,"注册失败",0).show();

}

super.handleMessage(msg);

}

};

}