Android客户端与服务器端的json数据交互,主要是通过json形式的数据交互,就是json的写入和解析。

 先看效果图,我最讨厌讲东西,一个图没有的。


算了,看来我不是写博客的材料,写不下去了,要排版之类的麻烦,大家还是直接去下载源码,里面有大量的注视,应该能看懂。 下载地址:源码下载地址


登录界面:很传统的随便做了一下:

android 服务器到客户端 android与服务器端数据交互_Text


用的是android4.0的,别人说这样的EditText很有科技感。


注册界面:

android 服务器到客户端 android与服务器端数据交互_android_02

也是很传统的,文本框之类的 。


下面看看包名,类名图。(忙着和比人聊天了,差点忘了) 现在继续

客户端的:

android 服务器到客户端 android与服务器端数据交互_android 服务器到客户端_03


服务器端的:

android 服务器到客户端 android与服务器端数据交互_java_04


下面贴上客户端的代码:

LoginRegisterActivity.java

package com.gem.hsx.activity;

import com.gem.hsx.operation.Operaton;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

//此为主activity的实现登录的。在android2.3以后,android规定了主activity不允许在主线程中做一些耗时较多的
//操作,包括网络的操作,主要是减少应用程序停止响应的问题。下面注释掉的部分是网上找到的方法,加上之后就可以在主线程中
//进行联网操作了,但是本人采用了线程的操作,未采用该方法
public class LoginRegisterActivity extends Activity {
	Button login;
	Button register;
	EditText etusername;
	EditText etpassword;
	String username;
	String password;
	ProgressDialog p;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

//		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()       
//		.detectDiskReads()       
//		.detectDiskWrites()       
//		.detectNetwork()   // or .detectAll() for all detectable problems       
//		.penaltyLog()       
//		.build());       
//		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()       
//		.detectLeakedSqlLiteObjects()    
//		.penaltyLog()       
//		.penaltyDeath()       
//		.build());   



		init();
		register.setOnClickListener(new RegisterOnclick());
		login.setOnClickListener(new LoginOnclick());
	}
	private void init() 
	{
		etusername=(EditText) findViewById(R.id.etusername);
		etpassword=(EditText) findViewById(R.id.etpassword);
		login=(Button) findViewById(R.id.login);
		register=(Button) findViewById(R.id.register);
		p=new ProgressDialog(LoginRegisterActivity.this);
		p.setTitle("登录中");
		p.setMessage("登录中,马上就好");
	}
	private class RegisterOnclick implements OnClickListener
	{
		public void onClick(View v) {
			Intent intent=new Intent();
			intent.setClass(LoginRegisterActivity.this, Register.class);
			startActivity(intent);
		}

	}
	private class LoginOnclick implements OnClickListener
	{
		public void onClick(View arg0) {
			username=etusername.getText().toString().trim();
			if (username==null||username.length()<=0) 
			{		
				etusername.requestFocus();
				etusername.setError("对不起,用户名不能为空");
				return;
			}
			else 
			{
				username=etusername.getText().toString().trim();
			}
			password=etpassword.getText().toString().trim();
			if (password==null||password.length()<=0) 
			{		
				etpassword.requestFocus();
				etpassword.setError("对不起,密码不能为空");
				return;
			}
			else 
			{
				password=etpassword.getText().toString().trim();
			}
			p.show();
			new Thread(new Runnable() {

				public void run() {
					Operaton operaton=new Operaton();
					String result=operaton.login("Login", username, password);				
					Message msg=new Message();
					msg.obj=result;
					handler.sendMessage(msg);
				}
			}).start();

		}
	}	
	Handler handler=new Handler(){
		@Override
		public void handleMessage(Message msg) {
			String string=(String) msg.obj;
			p.dismiss();
			Toast.makeText(LoginRegisterActivity.this, string, 0).show();
			super.handleMessage(msg);
		}	
	};
	
}




Register.java

package com.gem.hsx.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import com.gem.hsx.bean.User;
import com.gem.hsx.json.WriteJson;
import com.gem.hsx.operation.Operaton;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Toast;


public class Register extends Activity {
	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;
	private static final int REQUEST_EX = 1;
	String username=null;
	String password=null;
	String sex=null;
	String age=null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register);
		init();
		//etusername.addTextChangedListener(new MyTextWatcher());
		etusername.setOnFocusChangeListener(new EtusernameOnFocusChange());
		select.setOnClickListener(new SelectOnclick());
		submit.setOnClickListener(new SubmitOnclick());
	}
	private void init()
	{
		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=new ProgressDialog(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);
	//		}	
	//	};
	//	
	private class EtusernameOnFocusChange implements OnFocusChangeListener
	{
		public void onFocusChange(View v, boolean hasFocus) {
			if (!etusername.hasFocus()) {
				str=etusername.getText().toString().trim();
				if (str==null||str.length()<=0) 
				{
					etusername.setError("用户名不能为空");
				}
				else 
				{	
					new Thread(new Runnable() {
                 //如果用户名不为空,那么将用户名提交到服务器上进行验证,看用户名是否存在,就像JavaEE中利用
				//ajax一样,虽然你看不到但是它却偷偷摸摸做了很多
						public void run() {
							Operaton operaton=new Operaton();
							String result= operaton.checkusername("Check", str);
							System.out.println("result:"+result);
							Message message=new Message();
							message.obj=result;
							handler.sendMessage(message);
						}
					}).start();
				}
			}
		}
	}
	Handler handler=new Handler()
	{
		@Override
		public void handleMessage(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);
		}	
	};
	private class SelectOnclick implements OnClickListener
	{
		public void onClick(View v) {

			Intent intent = new Intent();
			intent.putExtra("explorer_title",
					getString(R.string.dialog_read_from_dir));
			intent.setDataAndType(Uri.fromFile(new File("/sdcard")), "*/*");
			intent.setClass(Register.this, ExDialog.class);
			startActivityForResult(intent, REQUEST_EX);
		}
	}
	protected void onActivityResult(int requestCode, int resultCode,
			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=new File(filepath);
				try {
					InputStream inputStream=new FileInputStream(file);
					Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
					imgphoto.setImageBitmap(bitmap);//如果是就将图片显示出来
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
				submit.setClickable(true);
			}
			else
			{
				submit.setClickable(false);
				alert();
			}

		}
	}

	private class SubmitOnclick implements OnClickListener
	{
		public void onClick(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();
			new Thread(new Runnable() {

				public void run() {

					Operaton operaton=new Operaton();
					File file=new File(filepath);
					String photo=operaton.uploadFile(file, "ImgReciver");
					//先进行图片上传的操作,然后服务器返回图片保存在服务器的路径,
					System.out.println("photo---->"+photo);
					System.out.println("sex:------>"+sex);
					User user=new User(username, password, sex, age,photo);
					//构造一个user对象
					List<User> list=new ArrayList<User>();
					list.add(user);
					WriteJson writeJson=new WriteJson();
					//将user对象写出json形式字符串
					jsonString= writeJson.getJsonData(list);
                    System.out.println(jsonString); 
					String result= operaton.UpData("Register", jsonString);
					Message msg=new Message();
					System.out.println("result---->"+result);
					msg.obj=result;
					handler1.sendMessage(msg);
				}
			}).start();

		}
	}
	private void alert()
	{
		Dialog dialog = new AlertDialog.Builder(this)
		.setTitle("提示")
		.setMessage("您选择的不是有效的图片")
		.setPositiveButton("确定",
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,
					int which) {
				filepath = null;
			}
		})
		.create();
		dialog.show();
	}
	Handler handler1=new Handler()
	{
		@Override
		public void handleMessage(Message msg) {
			dialog.dismiss();
			String msgobj=msg.obj.toString();
			if(msgobj.equals("t"))
			{
				Toast.makeText(Register.this, "注册成功", 0).show();
				Intent intent=new Intent();
				intent.setClass(Register.this, LoginRegisterActivity.class);
				startActivity(intent);
			}
			else {
				Toast.makeText(Register.this, "注册失败", 0).show();
			}
			super.handleMessage(msg);
		}	
	};
}


ExDialog.java




package com.gem.hsx.activity;


import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;


import com.gem.hsx.activity.R;
//由于安卓模拟器里面没有文件浏览器,所以构建一个文件浏览器的对话框 主要是dialog和listview配合
//此是一个简单的浏览器主要目的是选择文件后获取文件的路径,借鉴了一些其他人的文件浏览器的写法
public class ExDialog extends ListActivity {
	private List<Map<String, Object>> mData;
	private String mDir = "/sdcard";


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);


		Intent intent = this.getIntent();
		Bundle bl = intent.getExtras();
		String title = bl.getString("explorer_title");
		Uri uri = intent.getData();
		mDir = uri.getPath();


		setTitle(title);
		mData = getData();
		MyAdapter adapter = new MyAdapter(this);
		setListAdapter(adapter);


		WindowManager m = getWindowManager();
		Display d = m.getDefaultDisplay();
		LayoutParams p = getWindow().getAttributes();
		p.height = (int) (d.getHeight() * 0.8);
		p.width = (int) (d.getWidth() * 0.95);
		getWindow().setAttributes(p);
	}


	private List<Map<String, Object>> getData() {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = null;
		File f = new File(mDir);
		File[] files = f.listFiles();


		if (!mDir.equals("/sdcard")) {
			map = new HashMap<String, Object>();
			map.put("title", "返回上一级目录/");
			map.put("info", f.getParent());
			map.put("img", R.drawable.ex_folder);
			list.add(map);
		}
		if (files != null) {
			for (int i = 0; i < files.length; i++) {
				map = new HashMap<String, Object>();
				map.put("title", files[i].getName());
				map.put("info", files[i].getPath());
				if (files[i].isDirectory())
					map.put("img", R.drawable.ex_folder);
				else
					map.put("img", R.drawable.ex_doc);
				list.add(map);
			}
		}
		return list;
	}


	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Log.d("MyListView4-click", (String) mData.get(position).get("info"));
		if ((Integer) mData.get(position).get("img") == R.drawable.ex_folder) {
			mDir = (String) mData.get(position).get("info");
			mData = getData();
			MyAdapter adapter = new MyAdapter(this);
			setListAdapter(adapter);
		} else {
			finishWithResult((String) mData.get(position).get("info"));
		}
	}


	public final class ViewHolder {
		public ImageView img;
		public TextView title;
		public TextView info;
	}


	public class MyAdapter extends BaseAdapter {
		private LayoutInflater mInflater;


		public MyAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}


		public int getCount() {
			return mData.size();
		}


		public Object getItem(int arg0) {
			return null;
		}


		public long getItemId(int arg0) {
			return 0;
		}


		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.listview, null);
				holder.img = (ImageView) convertView.findViewById(R.id.img);
				holder.title = (TextView) convertView.findViewById(R.id.title);
				//	holder.info = (TextView) convertView.findViewById(R.id.info);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}


			holder.img.setBackgroundResource((Integer) mData.get(position).get(
			"img"));
			holder.title.setText((String) mData.get(position).get("title"));
			//holder.info.setText((String) mData.get(position).get("info"));
			return convertView;
		}
	}


	private void finishWithResult(String path) {
		Bundle conData = new Bundle();
		conData.putString("results", "Thanks Thanks");
		Intent intent = new Intent();
		intent.putExtras(conData);
		Uri startDir = Uri.fromFile(new File(path));
		intent.setDataAndType(startDir,
		"vnd.android.cursor.dir/lysesoft.andexplorer.file");
		setResult(RESULT_OK, intent);
		finish();
	}
};

JsonUtil.java


package com.gem.hsx.json;


import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;




public class JsonUtil {
	public List<?> StringFromJson (String jsondata)
	{     
		Type listType = new TypeToken<List<?>>(){}.getType();
		Gson gson=new Gson();
		ArrayList<?> list=gson.fromJson(jsondata, listType);
		return list;


	}
}
package com.gem.hsx.json;

import java.util.List;
import com.google.gson.Gson;

public class WriteJson {
	/*
	 * 通过引入gson jar包 写入 json 数据
	 */
	public String getJsonData(List<?> list)
	{
//此处要注意,时常会出现说找不到Gson类的情况,这时我们只需要将导入的包和系统提供换换顺序就行了
		Gson gson=new Gson();//利用google提供的gson将一个list集合写成json形式的字符串
		String jsonstring=gson.toJson(list);
		return jsonstring;
	}
	/*
	 * 当然如果不用gson也可以用传统的方式进行写入json数据或者利用StringBuffer拼字符串 写成json字符串形式
	 */
}