極客匿名プロジェクトAPP学習


***
このプロジェクトは非常に簡単に内容を学び、技術を運用します.
1.すべてドキュメントの要求によって、開発プロジェクトを規範化し、一歩一歩の機能効果を実現する.
2.MD 5ツールの使用
3.URLConnectionはネットワーク接続を行い、パッケージ化する.
4.AsyncTask非同期タスクの使用
5.連絡先を取得し、JSON変換を行う.
6.キャッシュの使用
7.adapterの使用
プロジェクトClientとServerおよびドキュメントのダウンロードアドレス:http://download.csdn.net/detail/itjavawfc/8553795
一)キャッシュ使用:
public static final String KEY_TOKEN="token";
	//  token
	public static String getCachedToken(Context context){
		return context.getSharedPreferences(APP_ID, Context.MODE_PRIVATE).getString(KEY_TOKEN, null);
	}
	
	public static void cacheToken(Context context,String token){
		Editor e=context.getSharedPreferences(APP_ID, Context.MODE_PRIVATE).edit();
		e.putString(KEY_TOKEN, token);
		e.commit();
	}
	
	//      
	public static String getCachedPhoneNum(Context context){
		return context.getSharedPreferences(APP_ID, Context.MODE_PRIVATE).getString(KEY_PHONE_NUM, null);
	}
	
	public static void cachePhoneNum(Context context,String phoneNum){
		Editor e=context.getSharedPreferences(APP_ID, Context.MODE_PRIVATE).edit();
		e.putString(KEY_TOKEN, phoneNum);
		e.commit();
	}
二)AsyncTask非同期タスクの使用とNetConnectionパッケージのURLConnection
public class NetConnection {
	public NetConnection(final String url,final HttpMethod method,final SuccessCallback successCallback,final FailCallback failCallback,final String ... kvs){
		new AsyncTask<Void, Void, String>() {
			@Override
			protected String doInBackground(Void... params) {
				StringBuffer paramsStr=new StringBuffer();
				for(int i=0;i<kvs.length;i+=2){
					paramsStr.append(kvs[i]).append("=").append(kvs[i+1]).append("&");
				}
				paramsStr.substring(0, paramsStr.length()-2);
				try {
					URLConnection uc;
			        //            
					switch(method){
					case POST:
						uc=new URL(url).openConnection();
						uc.setDoOutput(true);
						BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(uc.getOutputStream(),Config.CHARSET));
						bw.write(paramsStr.toString());
						bw.flush();
						break;
					default:
						uc=new URL(url+"?"+paramsStr.toString()).openConnection();	
					    break;
					}
					
					System.out.println("Request url:"+uc.getURL());
					System.out.println("Request data:"+paramsStr);
					//    
					BufferedReader br=new BufferedReader(new InputStreamReader(uc.getInputStream(), Config.CHARSET));
					String line=null;
					StringBuffer result=new StringBuffer();
					while((line=br.readLine())!=null){
						result.append(line);
					}
					
					System.out.println("Result:"+result.toString());
					return result.toString();
				
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return null;
			}
			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);
				if(result!=null){
					if(successCallback!=null){
						successCallback.onSuccess(result);
					}
				}else{
					if(failCallback!=null){
						failCallback.onFail();
					}
				}
			}
		}.execute();
	}
	
	public static interface SuccessCallback{
		void onSuccess(String result);
	}
	public static interface FailCallback{
		void onFail();
	}

}
パッケージ・クラスを使用して、ネットワークからデータを取得します.
public class UploadContacts {
	public UploadContacts(String phone_md5,String token,String contacts,final SuccessCallback successCallback,final FailCallback failCallback){
		new NetConnection(Config.SERVER_URL, HttpMethod.POST, new NetConnection.SuccessCallback() {
			@Override
			public void onSuccess(String result) {
				try {
					JSONObject obj=new JSONObject(result);
				    switch(obj.getInt(Config.KEY_STATUS)){
				    case Config.RESULT_STATUS_SUCCESS:
							if(successCallback!=null){
								successCallback.onSuccess();
							}
				    	break;
				    case Config.RESULT_STATUS_INVALID_TOKEN:
				    	if(failCallback!=null){
							failCallback.onFail(Config.RESULT_STATUS_INVALID_TOKEN);
						}
				    	break;
				    default:
				    	if(failCallback!=null){
							failCallback.onFail(Config.RESULT_STATUS_FAIL);
						}
				    	break;
				    }
				} catch (JSONException e) {
					e.printStackTrace();
					if(failCallback!=null){
						failCallback.onFail(Config.RESULT_STATUS_FAIL);
					}
				}
				
			}
		}, new NetConnection.FailCallback() {
			@Override
			public void onFail() {
				if(failCallback!=null){
					failCallback.onFail(Config.RESULT_STATUS_FAIL);
				}
			}
		}, Config.KEY_ACTION,Config.ACTION_UPLOAD_CONTACTS,Config.KEY_PHONE_MD5,phone_md5,Config.KEY_TOKEN,token,Config.KEY_CONTACTS,contacts);
	}
	
	public static interface SuccessCallback{
		void onSuccess();
	}
	
	public static interface FailCallback{
		void onFail(int errorCode);
	}

}

三)連絡先を読み取る【一般項目にある小さな機能】:
public class MyContacts {
	public static String getContactsJSONString(Context context){
		Cursor c=context.getContentResolver().query(Phone.CONTENT_URI, null, null, null, null);
		String phoneNum;
		JSONArray jsonArr=new JSONArray();
		JSONObject jsonObj;
		
		while(c.moveToNext()){
			phoneNum=c.getString(c.getColumnIndex(Phone.NUMBER));
			
			if(phoneNum.charAt(0)=='+'&&phoneNum.charAt(1)=='8'&&
					phoneNum.charAt(2)=='6'){
				
			}
			jsonObj=new JSONObject();
			try {
				jsonObj.put(Config.KEY_PHONE_MD5, MD5Tool.md5(phoneNum));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			jsonArr.put(jsonObj);
		}
		System.out.println(jsonArr.toString());
		return jsonArr.toString();
	}
}

四)Adapterの作成:データの追加と削除の方法、Contextの取得方法があり、非常に役に立ちます.
public class AtyMessageCommentListAdapter extends BaseAdapter {
	private Context context;
	public Context getContext() {
		return context;
	}
	
	public AtyMessageCommentListAdapter(Context context) {
		
		this.context=context;
	}
	
	private List<Comment> comments=new ArrayList<Comment>();
	
	@Override
	public int getCount() {
		return comments.size();
	}

	@Override
	public Object getItem(int position) {
		
		return comments.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		if(convertView==null){
			convertView=LayoutInflater.from(getContext()).inflate(R.layout.aty_comments_list_cell, null);
			convertView.setTag(new ListCell((TextView)convertView.findViewById(R.id.tvCellLabel)));
		}
		ListCell lc=(ListCell) convertView.getTag();
		
		Comment comment=(Comment) getItem(position);
		
		lc.getTvCellLabel().setText(comment.getContent());
		
		return convertView;
	}
	
	public void addAll(List<Comment> data){
		comments.addAll(data);
		notifyDataSetChanged();
	}
	
	public void clear(){
		comments.clear();
		notifyDataSetChanged();
	}
	
	private static class ListCell{
		private TextView tvCellLabel;

		public ListCell(TextView tvCellLabel){
			this.tvCellLabel=tvCellLabel;
			
		}
		public TextView getTvCellLabel() {
			return tvCellLabel;
		}
	}

}