这是填写详细资料页的整个代码:
涉及调用系统相册和拍照的实现,是通过:
1.一个图片的点击事件来触发一个AlertDialog
2.AlertDialog 两个选项:拍照和相册选择
3.点击不同的选项,触发不同的事件(拍照和相册)
4.onActivityResult方法设置返回对象的处理事件
package com.anjoyo.teacher.activity;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.anjoyo.model.User;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import com.anjoyo.net.AsyncHttpClient;
import com.anjoyo.net.JsonHttpResponseHandler;
import com.anjoyo.net.RequestParams;
import com.anjoyo.teacher.utils.Env;
import com.anjoyo.utils.RequestParamesUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils.StringSplitter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.Toast;
/**设计文档:P.4详细资料输入页 ---周韬*/
public class DetailsStudentAty extends Activity {
AsyncHttpClient ahClient;
AsyncHttpClient client = new AsyncHttpClient();
String reson;// 判断上传文件是否成功
String filename;// 上传相片、声音文件成功后返回的文件名
RadioGroup group_sex;
RadioButton man, women;
EditText nameEditText;
LinearLayout linear;
String nameValue,provinceValue,cityValue ,genderValue,avatar;
Button submitButton;
ImageView headPortraitButton;
Spinner sp_province, sp_city, sp_grade;
Context context;
ArrayAdapter<String> adapter;
ArrayAdapter<String> adapter2;
private static final int PHOTO_PICKED_WITH_DATA = 3021;
private static final int CAMERA_WITH_DATA = 3023;
private String[]dataProvince= new String[] { "北京", "上海", "哈尔滨" };
private String[] dataCity = new String[] { "海淀区", "朝阳区", "东城区", "西城区" };
private String[][] pandc = new String[][] {
{ "海淀区", "朝阳区", "东城区", "西城区" },
{ "浦东", "浦西", "浦南", "浦北" },
{ "齐齐哈尔", "牡丹江", "大庆", "伊春", "双鸭山", "鹤岗", "鸡西", "佳木斯", "七台河", "黑河",
"绥化", "大兴安岭" } };
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.write_student_information);
getView();
setListener();
}
private void getView() {
headPortraitButton = (ImageView) findViewById(R.id.bt_touxiang);// 更换头像
submitButton = (Button) findViewById(R.id.Button_tijiao);// 提交
sp_province = (Spinner) findViewById(R.id.p);
sp_city = (Spinner) findViewById(R.id.c);
nameEditText = (EditText) findViewById(R.id.xiangxi_name);
group_sex = (RadioGroup) findViewById(R.id.group);
man = (RadioButton) findViewById(R.id.man);
women = (RadioButton) findViewById(R.id.women);
sp_grade=(Spinner) findViewById(R.id.spinner);
}
private void setListener() {
headPortraitButton.setOnClickListener(headPortrait);
submitButton.setOnClickListener(submit);
sp_grade.setOnItemSelectedListener(grade_0);
sp_province.setOnItemSelectedListener(province);
group_sex.setOnCheckedChangeListener(group_0);
/** Spinner省市二级联动 */
context = this;
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, dataProvince);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp_province.setAdapter(adapter);
sp_province.setOnItemSelectedListener(province);
adapter2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, dataCity);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp_city.setAdapter(adapter2);
}
/** Spinner适配 二级联动*/
private OnItemSelectedListener province = new OnItemSelectedListener() {
public void onItemSelected(AdapterView parent, View v, int position,
long id) {
int pos = sp_province.getSelectedItemPosition();
adapter2 = new ArrayAdapter<String>(context,
android.R.layout.simple_spinner_item, pandc[pos]);
sp_city.setAdapter(adapter2);
}
public void onNothingSelected(AdapterView arg0) {
}
};
/** 更换头像 */
private OnClickListener headPortrait=new OnClickListener() {
@Override
public void onClick(View v) {
final CharSequence[] items = { "相册", "拍照" };
AlertDialog dlg = new AlertDialog.Builder(DetailsStudentAty.this)
.setTitle("选择图片")
.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
// 这里item是根据选择的方式,
if (item == 1) {
//拍照
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
} else {
//相册
Intent intent=new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX",128);
intent.putExtra("outputY", 128);
intent.putExtra("return-data", true);
startActivityForResult(intent, 0);
}
}
}).create();
dlg.show();
}
};
/**拍照的onActivityResult方法*/
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
String sdStatus = Environment.getExternalStorageState();
if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
Log.v("TestFile",
"SD card is not avaiable/writeable right now.");
return;
}
Bundle bundle = data.getExtras();
Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据,并转换为Bitmap图片格式
FileOutputStream b = null;
String timeString = System.currentTimeMillis() + "";
String fileName = Env.tempFileDir + timeString + ".jpg";
try {
b = new FileOutputStream(fileName);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
b.flush();
b.close();
} catch (IOException e) {
e.printStackTrace();
}
}
headPortraitButton.setImageBitmap(bitmap);// 将图片显示在ImageView里
headPortraitButton.setTag(fileName);
}
}
protected void doCropPhoto(Bitmap data){
Intent intent = getCropImageIntent(data);
startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
}
public static Intent getCropImageIntent(Bitmap data) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
intent.putExtra("data", data);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 128);
intent.putExtra("outputY", 128);
intent.putExtra("return-data", true);
return intent;
}
/**向服务器提交图片*/
public void sendPic() {
String filePath = (String)headPortraitButton.getTag();
File file = new File(filePath);
if (file.exists() && file != null) {
RequestParams requestParams = new RequestParams();
requestParams.put("token", User.currentUser.token);
requestParams.put("file_type", "avatar");
requestParams.put("resize", "128x128");
try {
requestParams.put("uploads", file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
client.post("http://shishuo.sinaapp.com/upload.php?" + "token="
+ User.currentUser.token + "&file_type=avatar",
requestParams, new JsonHttpResponseHandler() {
@Override
public void onFailure(Throwable error, String content) {
super.onFailure(error, content);
}
@Override
public void onSuccess(JSONObject response) {
super.onSuccess(response);
try {
reson = response.getString("result");
if (reson.equals("success")) {
filename = response.getString("filename");
Toast.makeText(DetailsStudentAty.this, "向服务器提交图片成功!",Toast.LENGTH_LONG).show();
submitInformation();
}
else{
Toast.makeText(DetailsStudentAty.this, "向服务器提交图片失败!",Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFinish() {
super.onFinish();
}
@Override
public void onStart() {
super.onStart();
}
});
}
}
/** 提交 */
private OnClickListener submit=new OnClickListener() {
@Override
public void onClick(View v) {
final ProgressDialog rd = ProgressDialog.show(
DetailsStudentAty.this, "正在提交", "请稍候...");
new Thread() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
} finally {
rd.dismiss();
}
}
}.start();
sendPic();
// submitInformation();
}
};
/** 男女單選 */
private OnCheckedChangeListener group_0=new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == man.getId()) // 获得性别
{
String gender = man.getText().toString();
} else {
String gender = women.getText().toString();
}
}
};
/**年级*/
private OnItemSelectedListener grade_0=new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
};
/**向服务器提交该页所有信息*/
private void submitInformation() {
ahClient = new AsyncHttpClient();
Intent intent =getIntent();
String tokenString =User.currentUser.token;
String nameValue = nameEditText.getEditableText().toString();// 或得输入框的名字
String provinceValue = sp_province.getSelectedItem().toString();// 获得省的值
String cityValue = sp_city.getSelectedItem().toString();// 获得城市的值
String gender;// 或得性别
String avatarValue=filename;// 获得照片
String gradeValue=sp_grade.getSelectedItem().toString();// 获得年级
RequestParams requestParams = new RequestParams();
requestParams.put("task", "UpdateStudentProfile");
requestParams.put("token", tokenString);
requestParams.put("name", nameValue);
requestParams.put("gender", genderValue);
requestParams.put("avatar", filename);
requestParams.put("province", provinceValue);
requestParams.put("city", cityValue);
requestParams.put("grade", gradeValue);
ahClient.post("http://shishuo.sinaapp.com/apis.php", requestParams,
new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONObject response) {
super.onSuccess(response);
JSONObject job = response;
String result = null;
try {
result = job.getString("result");
if (result.equals("success")) {
Toast.makeText(DetailsStudentAty.this, "上传该界面信息成功!",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(DetailsStudentAty.this,
MenuActivity.class);
startActivity(intent);
}
if (result.equals("fail")) {
Toast.makeText(DetailsStudentAty.this,
"上传该界面信息失败!" + response.toString(),
Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable error, String content) {
super.onFailure(error, content);
}
@Override
public void onFinish() {
super.onFinish();
}
@Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
});
}
}