1. 程式人生 > >Android移動開發-多人線上測評記錄考生狀態例項

Android移動開發-多人線上測評記錄考生狀態例項

一個測評軟體,可以多個老師同時線上使用,怎樣控制各個老師不能同時對同一個學生進行考試呢?
1、服務端儲存正在考試的考生標識;
2、當某個老師選取了一些學生進行考試的時候,首先去服務端獲取這些考生哪些已經在考試了,然後與選取的考生相減,等到
還未考試的學生;

3、當這個老師不對這個學生進行考試或者已經對這個考生考結束了,則服務端需要把這個考生標識刪除。

RandomSkillFragment.java

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;

import com.wneng.evaluation.R;
import com.wneng.evaluation.activity.EvaluationActivity;
import com.wneng.evaluation.model.SimpleProject;
import com.wneng.evaluation.model.SimpleSkill;
import com.wneng.evaluation.model.SimpleStandards;
import com.wneng.evaluation.model.SimpleUser;
import com.wneng.evaluation.util.DefaultContants;
import com.wneng.evaluation.util.DialogUtil;
import com.wneng.evaluation.util.FileUtils;
import com.wneng.evaluation.util.JsonHelper;
import com.wneng.evaluation.util.StringUtil;
import com.wneng.evaluation.util.SystemMessage;
import com.wneng.evaluation.view.SkillAdapter;
import com.wneng.evaluation.view.UserAdapter;
import com.wneng.evaluation.widgets.CustomDialog;

public class RandomSkillFragment extends BaseFragment {

	private GridView randomedGridview;
	private GridView gvStudentList;
	private UserAdapter studentAdapter;
	private List<SimpleUser> randomUsers = new ArrayList<SimpleUser>();
	private SkillAdapter skillRandomedAdapter;
	private Button btnReRandomStudent;
	private Button btnNotRandomStudent;
	private EvaluationActivity evalActivity;
	private Context context;
    private SkillAdapter skillAdapter;
    private List<SimpleSkill> skills = new ArrayList<SimpleSkill>();
    private SimpleSkill selectedSkill;
    private List<SimpleProject> selectedProjects;
    private LinearLayout llNotRandomed;
    private LinearLayout llRandomed;
    private List<SimpleUser> selStudents = new ArrayList<SimpleUser>();//選擇的學生
    private List<SimpleUser> selStudentsToEval = new ArrayList<SimpleUser>();//要考試的學生
    private List<String> evaluationingUserIds = new ArrayList<String>();//正在考試的考生ID
    private List<String> toEvaluationUserIds = new ArrayList<String>();//將要去考試的考生ID
    private int canNotEvalCount;//不能考的數量
	
   	final Handler cwjHandler = new Handler();

   	/**
   	 * 更新技能列表
   	 */
	final Runnable mUpdateResults = new Runnable() {
		public void run() {
			skillAdapter.notifyDataSetChanged();
			DialogUtil.stopProgressDialog();
		}
	};

   	/**
   	 * 跳轉到抽取考生頁面
   	 */
	final Runnable mUpdateUIResults = new Runnable() {
		public void run() {
			evalActivity.setTabSelection(1);
			DialogUtil.stopProgressDialog();
		}
	};

   	/**
   	 * 為考生抽取了技能,跳轉到考試頁面
   	 */
	final Runnable mUpdateEvalUIResults = new Runnable() {
		public void run() {
			skillRandomedAdapter.notifyDataSetChanged();
			for (SimpleUser selectedUser : selStudentsToEval) {
				evalActivity.userId = selectedUser.getUserId();
				evalActivity.setTabSelection(3);
			}
		}
	};

	/**
	 * 提示是否進行考試
	 */
	final Runnable mUpdateIsEvalUIResults = new Runnable() {
		public void run() {
			selStudentsToEval = new ArrayList<SimpleUser>();//清空要考試的學生
			StringBuffer tipSb = new StringBuffer();
			if(!StringUtil.isNullOrEmpty(evaluationingUserIds) && evaluationingUserIds.size() > 0){
				List<SimpleUser> studentsEvaluationing = new ArrayList<SimpleUser>();
				Set<String> userIdSet = new HashSet<String>();
				for (SimpleUser simpleUser : selStudents) {
					for (String str : evaluationingUserIds) {
						if(str.equals(simpleUser.getUserId())) {
							studentsEvaluationing.add(simpleUser);
							userIdSet.add(str);
							break;
						}
					}
				}
				for (SimpleUser simpleUser : selStudents) {
					if(userIdSet.add(simpleUser.getUserId())) {
						selStudentsToEval.add(simpleUser);
						toEvaluationUserIds.add(simpleUser.getUserId());
					}
				}
				if(studentsEvaluationing.size() > 0){
					int i = 0;
					for (SimpleUser simpleUser : studentsEvaluationing) {
						if(i == 0){
							tipSb.append("考生:");
						}
						i++;
						tipSb.append(simpleUser.getUserName());
						tipSb.append(",");
					}
					tipSb.append("正在考試,\n");
				}
			} else {
				selStudentsToEval = selStudents;
			}
			if(StringUtil.isNullOrEmpty(tipSb)){
				tipSb.append("現在要給選擇的考生進行考試嗎?");
			}else{
				tipSb.append("現在要給剩下的考生進行考試嗎?");				
			}
			showIsEvaluation(evalActivity, tipSb.toString(), "提示", "確定");
			DialogUtil.stopProgressDialog();
		}
	};

   	/**
   	 * 更新抽取了的技能列表
   	 */
	public final Runnable mRandomResults = new Runnable() {
		public void run() {
			skillRandomedAdapter = new SkillAdapter(context, skills);
			randomedGridview.setAdapter(skillRandomedAdapter);
			skillRandomedAdapter.notifyDataSetChanged();
			llNotRandomed.setVisibility(View.GONE);
			llRandomed.setVisibility(View.VISIBLE);
		}
	};

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
        View randomSkillLayout = inflater.inflate(R.layout.random_skill_fragment, container, false);  
        llNotRandomed = (LinearLayout)randomSkillLayout.findViewById(R.id.ll_not_randomed);
        llNotRandomed.setVisibility(View.GONE);
        llRandomed = (LinearLayout)randomSkillLayout.findViewById(R.id.ll_randomed);
        context = getActivity().getApplicationContext();
        
        evalActivity = (EvaluationActivity)getActivity();
        
		DialogUtil.startProgressDialog(evalActivity, getString(R.string.load));

		String filePath = getString(R.string.file_path) + "user/randomData.json";
		String list = FileUtils.readFile(filePath);
		if(StringUtil.isNullOrEmpty(list)){
			llRandomed.setVisibility(View.GONE);
			llNotRandomed.setVisibility(View.VISIBLE);
		} else {
			llRandomed.setVisibility(View.VISIBLE);
		}
        analysisStudentData(list, DefaultContants.LIST_RANDOM_STUDENT);

        randomedGridview = (GridView) randomSkillLayout.findViewById(R.id.gv_randomed_skills);
    	skillRandomedAdapter = new SkillAdapter(context, skills);
        randomedGridview.setAdapter(skillRandomedAdapter);
        randomedGridview.setOnItemClickListener(new GridView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View itemView, int position, long arg3) {
				DialogUtil.startProgressDialog(evalActivity, getString(R.string.load));
				selectedSkill = skills.get(position);
				if(!StringUtil.isNullOrEmpty(selectedSkill.getUsers()) && selectedSkill.getUsers().size() > 0){
					View llStudentList = LayoutInflater.from(context).inflate(R.layout.random_student_list, null);
	            	//載入考生列表
	            	gvStudentList = (GridView)llStudentList.findViewById(R.id.gv_to_choose_students);
	            	studentAdapter = new UserAdapter(context, selectedSkill.getUsers(), DefaultContants.LIST_CHOOSE_STUDENT);
	            	gvStudentList.setAdapter(studentAdapter);
	            	showStudentListView(evalActivity, llStudentList, "選擇考生", "確定");
				} else {
		        	DialogUtil.showMessage(evalActivity, "該技能下不存在考生。", true);
		        	DialogUtil.stopProgressDialog();
				}
			}
		});
        //重新抽取
        btnReRandomStudent = (Button) randomSkillLayout.findViewById(R.id.btn_re_random_student);
        btnReRandomStudent.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String filePath = getString(R.string.file_path) + "evaluation/isStartEval.json";
	            String isStart = FileUtils.readFile(filePath);
	            if(!StringUtil.isNullOrEmpty(isStart) && DefaultContants.STARTED_EVAL.equals(isStart)){
	            	DialogUtil.showError(evalActivity, "有考生在考試,不能重新抽取。", false);
	            	return;
	            }else{
	            	DialogUtil.startProgressDialog(evalActivity, getString(R.string.load));
	            	cwjHandler.post(mUpdateUIResults);
	            }
			}
		});
        btnNotRandomStudent = (Button) randomSkillLayout.findViewById(R.id.btn_not_random_student);
        btnNotRandomStudent.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String filePath = getString(R.string.file_path) + "evaluation/isStartEval.json";
	            String isStart = FileUtils.readFile(filePath);
	            if(!StringUtil.isNullOrEmpty(isStart) && DefaultContants.STARTED_EVAL.equals(isStart)){
	            	DialogUtil.showError(evalActivity, "有考生在考試,不能重新抽取。", false);
	            	return;
	            }else{
	            	DialogUtil.startProgressDialog(evalActivity, getString(R.string.load));
	            	cwjHandler.post(mUpdateUIResults);
	            }
			}
		});
        return randomSkillLayout;  
    }
    
    /**
     * 解析資料
     * @param resp
     * @param type 1-開始獲取的,2-隨機抽取的
     */
	public void analysisStudentData(String resp, String type) {
		try {
			Log.d("RandomSkillFragment--File",resp);
			if(StringUtil.isNullOrEmpty(resp)){
				return;
			}
			JSONObject result = new JSONObject(resp);
			if (result.has("list")) {
				JSONArray jobList = result.getJSONArray("list");
				int length = jobList.length();
				randomUsers = new ArrayList<SimpleUser>();
				skills = new ArrayList<SimpleSkill>();
				Set<String> skillIds = new HashSet<String>();
				for(int i = 0; i < length; i++){
					JSONObject oj = jobList.getJSONObject(i);
					SimpleUser su = new SimpleUser(oj.getString("userId").trim(),
							oj.getString("userName").trim(),
							oj.getString("realName").trim(),
							oj.getString("mobile").trim()
							);
					if (DefaultContants.LIST_RANDOM_STUDENT.equals(type)){
						JSONObject jsonObject = oj.getJSONObject("skill");
						SimpleSkill ss = new SimpleSkill(jsonObject.getString("skillId"), jsonObject.getString("skillName"));
						if(skillIds.add(ss.getSkillId())){
							skills.add(ss);
						}
						su.setSkill(ss);
						randomUsers.add(su);
					}
				}
				for (SimpleSkill simpleSkill : skills) {
					List<SimpleUser> sus = new ArrayList<SimpleUser>();
					for (SimpleUser sUser : randomUsers) {
						SimpleSkill ss = sUser.getSkill();
						if(simpleSkill.getSkillId().equals(ss.getSkillId())){
							sus.add(sUser);
						}
					}
					simpleSkill.setUsers(sus);
				}
			}
			DialogUtil.stopProgressDialog();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
    
    /**
     * 解析資料
     * @param resp
     * @param type 1-開始獲取的,2-隨機抽取的
     */
	public void analysisProjectData(String resp) {
		try {
			Log.d("RandomSkillFragment--projects",resp);
			if(StringUtil.isNullOrEmpty(resp)){
				return;
			}
			JSONObject result = new JSONObject(resp);
			if (result.has("list")) {
				JSONArray jobList = result.getJSONArray("list");
				int length = jobList.length();
				selectedProjects = new ArrayList<SimpleProject>();
				for(int i = 0; i < length; i++){
					JSONObject oj = jobList.getJSONObject(i);
					SimpleProject project = new SimpleProject(oj.getString("id").trim(),
							oj.getString("name").trim(),
							oj.getString("required").trim(),
							oj.getString("score").trim(),
							oj.getString("skillId").trim()
							);
					selectedProjects.add(project);
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 彈出考生供教師選擇
	 * @param context
	 * @param msg
	 */
	public void showStudentListView(Context context, View view, String title, String btnText) {
		builder = new CustomDialog.Builder(context);
		builder.setTitle(title);
		builder.setContentView(view);
		builder.setModel(true);
		builder.setPositiveButton(btnText,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						List<SimpleUser> students = selectedSkill.getUsers();
						List<SimpleUser> sels = new ArrayList<SimpleUser>();//選中的考生 可能>6
						for (SimpleUser simpleUser : students) {
							if(simpleUser.isChecked()){
								sels.add(simpleUser);
							}
						}
						int size = sels.size();
						if(size < 1){
							DialogUtil.showMessage(evalActivity, "請選擇考生。", false);
							return;
						}
				        //獲取這是第幾個考生
				        int n = FileUtils.getFileCount(getString(R.string.file_path) + "evaluation/user");
				        size = sels.size();
				        int length = n + size;
				        canNotEvalCount = length - 6;
				        if(canNotEvalCount > 0){
							DialogUtil.showMessage(evalActivity, "最多6人能同時測評,已有"+n+"人在測評,本次選擇"+size+"人,請去除"+canNotEvalCount+"人,再進行測評。", false);
							return;
				        }
				        selStudents = sels;
						StringBuffer sb = new StringBuffer();
						for (SimpleUser simpleUser : sels) {
							sb.append(simpleUser.getUserId());
							sb.append(",");
						}
						String userIdsStr = "";
						if(sb.length() > 0){
							userIdsStr = sb.substring(0, sb.length() - 1);
						}
						final String userIds = userIdsStr;
						new Thread(new Runnable() {
							@SuppressWarnings({ "rawtypes", "unchecked" })
							@Override
							public void run() {
								try {
									//獲取該技能的專案
									String scriptName = "/evaluation!getProjectList.do";;
									Map<String, Object> params = new HashMap<String, Object>();
									params.put("openKey", SystemMessage.getString("openKey"));
									params.put("openId", SystemMessage.getString("openId"));
									params.put("skillId", selectedSkill.getSkillId());
									String filePath = getString(R.string.file_path) + "skill/"+selectedSkill.getSkillId()+"-projectData.json";
									String fileContent = FileUtils.readFile(filePath);
									String resp = null;
									if(StringUtil.isNullOrEmpty(fileContent)){
										resp = sdk.api(scriptName, params);		
								        FileUtils.saveFile(filePath, resp);											
									} else {
										resp = fileContent;
									}
									analysisProjectData(resp);
									//獲取評分標準
									if(!StringUtil.isNullOrEmpty(selectedProjects)){
										params.remove("skillId");
										scriptName = "/evaluation!getStandardsList.do";
										for (SimpleProject sp : selectedProjects) {
											params.put("projectId", sp.getId());
											filePath = getString(R.string.file_path) + "skill/"+sp.getId()+"-standardData.json";
									        String list = FileUtils.readFile(filePath);
									        if(StringUtil.isNullOrEmpty(list)){
									        	list = sdk.api(scriptName, params);
												FileUtils.saveFile(filePath, list);
									        }
											//解析standard
									        Map map = JsonHelper.parseToObject(list, Map.class);
									        List<SimpleStandards> standards = new ArrayList<SimpleStandards>();
									        List<Map> mStandards = (List<Map>)map.get("list");
								    		for (Map map2 : mStandards) {
								    			SimpleStandards ss = new SimpleStandards(map2.get("id").toString(), map2.get("name").toString(), map2.get("minusScore").toString(), map2.get("projectId").toString());
								    			standards.add(ss);
								    		}
								    		sp.setStandards(standards);
										}
									}
									//獲取正在考試的考生
									scriptName = "/evaluation!setUserStatus.do";
									params.put("userIds", userIds);
									params.put("operateType", "add");
									params.remove("projectId");
									resp = sdk.api(scriptName, params);
									if(StringUtil.isNullOrEmpty(resp)){
										DialogUtil.showMessage(evalActivity, "伺服器異常,請稍後再試。", false);
										DialogUtil.stopProgressDialog();
										return;
									} else {
										JSONObject result = new JSONObject(resp);
										if (result.has("userIds")) {
											String evaluationUserIds = result.getString("userIds").trim();
											if(!StringUtil.isNullOrEmpty(evaluationUserIds)){
												evaluationingUserIds = new ArrayList<String>();
												String[] userIdStr = evaluationUserIds.split(",");
												for (int i = 0; i < userIdStr.length; i++) {
													evaluationingUserIds.add(userIdStr[i]);
												}
											}else{
												evaluationingUserIds = new ArrayList<String>();
											}
										}
									}
									//彈出框考試提示框
									cwjHandler.post(mUpdateIsEvalUIResults);
								}catch (Exception e) {
									DialogUtil.stopProgressDialog();
									e.printStackTrace();
								}
						}}).start();
						dialog.dismiss();
						// 設定你的操作事項
					}
				});
        builder.setNegativeButton("取消",  
                new android.content.DialogInterface.OnClickListener() {  
                    public void onClick(DialogInterface dialog, int which) {  
            			DialogUtil.stopProgressDialog();
                        dialog.dismiss();  
                    }
                });
		builder.create().show();
	}
	
	/**
	 * 彈出是否馬上進行考試
	 * @param context
	 * @param msg
	 */
	public void showIsEvaluation(Context context, String msg, String title, String btnText) {
		builder = new CustomDialog.Builder(context);
		builder.setTitle(title);
		builder.setMessage(msg);
		builder.setPositiveButton(btnText,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,
							int which) {
						if(selStudentsToEval.size() < 1){
							DialogUtil.showMessage(evalActivity, "剛剛選擇的考生已經在其他老師那進行測評了,請重新選擇考生。", false);
							return;
						}
						//儲存考試記錄
						String filePath = getString(R.string.file_path) + "evaluation/isStartEval.json";
				        FileUtils.saveFile(filePath, DefaultContants.STARTED_EVAL);
				        //儲存UserId
				        filePath = getString(R.string.file_path) + "evaluation/userId.json";
				        String uIds = FileUtils.readFile(filePath);
				        for (SimpleUser selectedUser : selStudentsToEval) {
					        if(StringUtil.isNullOrEmpty(uIds)){
					        	uIds = selectedUser.getUserId();
					        }else {
					        	uIds = uIds + "," + selectedUser.getUserId();
					        }
					        Map<String, Object> userEval = new  HashMap<String, Object>();
							selectedSkill.setTotalScore("100");
					        userEval.put("user", selectedUser.getUser());
					        userEval.put("skill", selectedSkill.getSkill());
					        userEval.put("projects", selectedProjects);
							String fp = getString(R.string.file_path) + "evaluation/user/"+ selectedUser.getUserId()+"-eval.json";
							FileUtils.saveFile(fp, JsonHelper.parseToJson(userEval));
						}
				        FileUtils.saveFile(filePath, uIds);
		                cwjHandler.post(mUpdateEvalUIResults);
						dialog.dismiss();
					}
				});
        builder.setNegativeButton("取消",  
                new android.content.DialogInterface.OnClickListener() {  
                    public void onClick(DialogInterface dialog, int which) {
                    	new Thread(new Runnable() {
							@SuppressWarnings({ "rawtypes", "unchecked" })
							@Override
							public void run() {
								try {
			                    	//若取消,就刪除伺服器上剛剛新增的userIds
			                    	String scriptName = "/evaluation!setUserStatus.do";
									Map<String, Object> params = new HashMap<String, Object>();
									params.put("openKey", SystemMessage.getString("openKey"));
									params.put("openId", SystemMessage.getString("openId"));
									String uIds = "";
									for (String str : toEvaluationUserIds) {
										if(StringUtil.isNullOrEmpty(uIds)){
								        	uIds = str;
								        }else {
								        	uIds = uIds + "," + str;
								        }
									}
									params.put("userIds", uIds);
									params.put("operateType", "delete");
									resp = sdk.api(scriptName, params);
			            			DialogUtil.stopProgressDialog();
			                        dialog.dismiss();  
		                        }catch (Exception e) {
									DialogUtil.stopProgressDialog();
									e.printStackTrace();
								}
							}}).start();
                    }
                });
		builder.create().show();
	}
	
}