我是来问问题的 请大神帮我看下代码 有那些地方会造成内存溢出 如果解决可以在问答栏目拿到我的悬赏,望笑纳
import android.annotation.SuppressLint; import android.app.Activity; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.king.photo.activity.AlbumActivity; import com.king.photo.activity.GalleryActivity; import com.king.photo.util.Bimp; import com.king.photo.util.ImageItem; import com.king.photo.util.PublicWay; import com.king.photo.util.Res; import com.lidroid.xutils.HttpUtils; import com.lidroid.xutils.exception.HttpException; import com.lidroid.xutils.http.RequestParams; import com.lidroid.xutils.http.ResponseInfo; import com.lidroid.xutils.http.callback.RequestCallBack; import com.lidroid.xutils.http.client.HttpRequest; import com.lidroid.xutils.http.client.HttpRequest.HttpMethod; import com.lxn.guardianangle.R; import com.lxn.guardianangle.application.Dapplication; import com.lxn.guardianangle.bean.Contact; import com.lxn.guardianangle.utils.ActivityManager; import com.lxn.guardianangle.utils.PicUtils; import com.lxn.guardianangle.utils.TitleUtil; import com.lxn.guardianangle.view.CustomProgress; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; public class ReleaseHomeWork extends Activity { private GridView noScrollgridview; private Spinner mySpinner; private List<String> list = new ArrayList<String>(); private ArrayAdapter<String> adapter; private GridAdapter adapter1; private List<String> IDlist = new ArrayList<String>(); private String classid; private CustomProgress dialog; private Context mContext; private EditText ed_title, ed_content; private View parentView; private PopupWindow pop = null; private LinearLayout ll_popup; private Bitmap bimap; StringBuilder builder = new StringBuilder(); String bmUrls = ""; int falg1; int a = 0; private Handler handler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 3: if (Bimp.tempSelectBitmap.size() == a) { a = 0; releaseMessage(); return; } String path = Bimp.tempSelectBitmap.get(a).getImagePath(); if (path == null) { Bitmap bm = Bimp.tempSelectBitmap.get(a).getBitmap(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, stream); if (bm != null) { final File tempFile = new File(getCacheDir(), "temp.png"); try { byte[] dataBytes = stream.toByteArray(); FileOutputStream fileOut = new FileOutputStream(tempFile); fileOut.write(dataBytes); fileOut.close(); stream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (tempFile.exists()) { falg1 = 0; final String pic_path = tempFile.getPath(); String targetPath = getTempDirectoryPath() + "compressPic.jpg"; //调用压缩图片的方法,返回压缩后的图片path final String compressImage = PicUtils.compressImage(pic_path, targetPath, 50); final File compressedPic = new File(compressImage); if (compressedPic.exists()) { uploadPics(compressedPic); } else {//直接上传 uploadPics(tempFile); } ++a; } } } if (path != null) { falg1 = 1; String targetPath = getTempDirectoryPath() + "compressPic.jpg"; //调用压缩图片的方法,返回压缩后的图片path final String compressImage = PicUtils.compressImage(path, targetPath, 50); final File compressedPic = new File(compressImage); if (compressedPic.exists()) { uploadPics(compressedPic); } else {//直接上传 uploadPics(new File(path)); } } ++a; break; } } }; @Override protected void onSaveInstanceState(Bundle outState) { if (photoUri == null) { } else { outState.putString("uri", photoUri.toString()); } outState.putString("file_path", mCurrentPhotoPath); super.onSaveInstanceState(outState); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { photoUri = Uri.parse(savedInstanceState.getString("uri")); if (savedInstanceState != null) { mCurrentPhotoPath = savedInstanceState.getString("file_path"); } super.onRestoreInstanceState(savedInstanceState); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityManager.getInstance().addActivity(this); parentView = LayoutInflater.from(this).inflate(R.layout.activity_releasemessage, null); setContentView(parentView); new TitleUtil(this).setTitle("发布作业").setOnLeftClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }).setRightTxt("确定").setOnRightTextClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog = CustomProgress.show(mContext, "正在上传", false, null); builder = new StringBuilder(); Message message = new Message(); message.what = 3; handler.sendMessage(message); } }); Bimp.tempSelectBitmap.clear(); Res.init(this); bimap = Resousetobit( R.drawable.icon_addpic_unfocused); mContext = this; initView(); getClassList(); Init(); bimap.recycle(); } private Bitmap Resousetobit(int resource) { BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inPreferredConfig = Bitmap.Config.ARGB_8888; opt.inPurgeable = true; opt.inInputShareable = true; InputStream is = getResources().openRawResource(resource); return BitmapFactory.decodeStream(is, null, opt); } private void uploadPics(File file) {//final String bmPaths HttpUtils utils = new HttpUtils(); RequestParams params = new RequestParams(); params.addBodyParameter("name", file);//new File(bmPaths) params.addBodyParameter("file_paths", "avatars/reply");//new File(bmPaths) utils.send(HttpRequest.HttpMethod.POST, Contact.uploadPics, params, new RequestCallBack<String>() { @Override public void onSuccess( ResponseInfo<String> objectResponseInfo) { JSONObject jsonObject; try { jsonObject = new JSONObject( objectResponseInfo.result); String rcode = jsonObject.getString("status"); if ("200".equals(rcode)) { System.out.println("------" + jsonObject.toString()); JSONObject jsonObject1 = jsonObject .getJSONObject("result"); try { bmUrls = jsonObject1.getString("thumb"); builder.append(bmUrls + ","); /* * Toast.makeText(getApplicationContext(), * "保存成功", Toast.LENGTH_SHORT) .show(); */ if (falg1 == 0) { } else { Message message = new Message(); message.what = 3; handler.sendMessage(message); } } catch (JSONException e) { e.printStackTrace(); } } else { dialog.dismiss(); dialog = null; Toast.makeText( getApplicationContext(), "上传图片失败", Toast.LENGTH_SHORT).show(); } } catch (JSONException e1) { e1.printStackTrace(); } } @Override public void onFailure(HttpException e, String s) { dialog = null; dialog.dismiss(); Toast.makeText(getApplicationContext(), "上传图片失败", Toast.LENGTH_SHORT).show(); } }); } private String getTempDirectoryPath() { return System.getProperty("java.io.tmpdir"); } private void initView() { ed_title = (EditText) findViewById(R.id.ed_title); ed_content = (EditText) findViewById(R.id.ed_content); mySpinner = (Spinner) findViewById(R.id.spinner); //下拉菜单的子项点击事件 mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { classid = IDlist.get(position); } @Override public void onNothingSelected(AdapterView<?> parent) { // TODO 自动生成的方法存根 } }); /* 下拉菜单弹出的内容选项触屏事件处理 */ mySpinner.setOnTouchListener(new Spinner.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub /** * */ return false; } }); /* 下拉菜单弹出的内容选项焦点改变事件处理 */ mySpinner.setOnFocusChangeListener(new Spinner.OnFocusChangeListener() { public void onFocusChange(View v, boolean hasFocus) { // TODO Auto-generated method stub } }); } int sta; //添加数据 private void getClassList() { HttpUtils util = new HttpUtils(); RequestParams params = new RequestParams(); params.addBodyParameter("u_id", Dapplication.userId); util.send(HttpMethod.POST, Contact.Teacherclasslist, params, new RequestCallBack<String>() { @Override public void onSuccess(ResponseInfo<String> arg0) { // TODO Auto-generated method stub // getData(); try { JSONObject jobj = new JSONObject(arg0.result); if (jobj.optInt("status") == 200) { JSONObject data = jobj.optJSONObject("result"); sta = data.optInt("error"); switch (sta) { case 0: JSONArray subject = data .optJSONArray("class_list"); for (int i = 0; i < subject.length(); i++) { JSONObject obj = (JSONObject) subject .get(i); list.add(obj.optString("class_name")); IDlist.add(obj.optString("c_id")); } // getStudentList(IDlist.get(0)); adapter = new ArrayAdapter<String>(mContext, android.R.layout.select_dialog_item, list); // 第三步:为适配器设置下拉列表下拉时的菜单样式。 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // 第四步:将适配器添加到下拉列表上 mySpinner.setAdapter(adapter); break; case 1: Toast.makeText(getApplicationContext(), data.optString("errmsg"), Toast.LENGTH_SHORT).show(); return; case 2: Toast.makeText(getApplicationContext(), data.optString("errmsg"), Toast.LENGTH_SHORT).show(); return; default: break; } } else { Toast.makeText(getApplicationContext(), "登录失败,请检查用户名密码是否匹配", Toast.LENGTH_SHORT).show(); return; } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void onFailure(HttpException arg0, String arg1) { // TODO Auto-generated method stub Toast.makeText(getApplicationContext(), "请检查网络连接", Toast.LENGTH_SHORT) .show(); } }); } @Override protected void onResume() { super.onResume(); //重新显示页面时刷新拍照或者选择的图片列表 adapter1.notifyDataSetChanged(); } //发布作业 private void releaseMessage() { HttpUtils util = new HttpUtils(); RequestParams params = new RequestParams(); params.addBodyParameter("t_id", Dapplication.Tid); params.addBodyParameter("u_id", Dapplication.userId); params.addBodyParameter("class_id", classid); if (ed_title.getText().toString().equals("")) { Toast.makeText(getApplicationContext(), "请先输入标题", Toast.LENGTH_SHORT).show(); dialog.dismiss(); return; } else { params.addBodyParameter("title", ed_title.getText().toString()); } if (ed_content.getText().toString().equals("") && builder.length() == 0) { Toast.makeText(getApplicationContext(), "请先输入文字或者上传图片", Toast.LENGTH_SHORT).show(); dialog.dismiss(); return; } params.addBodyParameter("sub_title", ed_content.getText().toString()); if (builder.length() > 0) { String builder1 = builder.substring(0, builder.length() - 1) + ""; params.addBodyParameter("attr", builder1); } else { params.addBodyParameter("attr", ""); } util.send(HttpMethod.POST, Contact.releaseHomework, params, new RequestCallBack<String>() { @Override public void onSuccess(ResponseInfo<String> arg0) { builder=null; dialog.dismiss(); // TODO Auto-generated method stub // getData(); try { JSONObject jobj = new JSONObject(arg0.result); if (jobj.optInt("status") == 200) { JSONObject data = jobj.optJSONObject("result"); sta = data.optInt("error"); switch (sta) { case 0: finish(); break; case 1: Toast.makeText(getApplicationContext(), data.optString("errmsg"), Toast.LENGTH_SHORT).show(); break; case 2: Toast.makeText(getApplicationContext(), data.optString("errmsg"), Toast.LENGTH_SHORT).show(); break; default: break; } finish(); } else { Toast.makeText(getApplicationContext(), "登录失败,请检查用户名密码是否匹配", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void onFailure(HttpException arg0, String arg1) { dialog.dismiss(); // TODO Auto-generated method stub Toast.makeText(getApplicationContext(), "请检查网络连接", Toast.LENGTH_SHORT) .show(); } }); } //初始化图片选择或者拍照的popupwindow public void Init() { pop = new PopupWindow(ReleaseHomeWork.this); View view = getLayoutInflater().inflate(R.layout.item_popupwindows, null); ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup); pop.setWidth(LayoutParams.MATCH_PARENT); pop.setHeight(LayoutParams.WRAP_CONTENT); pop.setBackgroundDrawable(new BitmapDrawable()); pop.setFocusable(true); pop.setOutsideTouchable(true); pop.setContentView(view); RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent); Button bt1 = (Button) view .findViewById(R.id.item_popupwindows_camera); Button bt2 = (Button) view .findViewById(R.id.item_popupwindows_Photo); Button bt3 = (Button) view .findViewById(R.id.item_popupwindows_cancel); parent.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub pop.dismiss(); ll_popup.clearAnimation(); } }); bt1.setOnClickListener(new OnClickListener() { public void onClick(View v) { photo(); pop.dismiss(); ll_popup.clearAnimation(); } }); bt2.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent = new Intent(ReleaseHomeWork.this, AlbumActivity.class); startActivity(intent); overridePendingTransition(R.anim.activity_translate_in, R.anim.activity_translate_out); pop.dismiss(); ll_popup.clearAnimation(); } }); bt3.setOnClickListener(new OnClickListener() { public void onClick(View v) { pop.dismiss(); ll_popup.clearAnimation(); } }); noScrollgridview = (GridView) findViewById(R.id.noScrollgridview1); noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT)); adapter1 = new GridAdapter(ReleaseHomeWork.this); adapter1.update(); noScrollgridview.setAdapter(adapter1); noScrollgridview.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { if (arg2 == Bimp.tempSelectBitmap.size()) { ll_popup.startAnimation(AnimationUtils.loadAnimation(ReleaseHomeWork.this, R.anim.activity_translate_in)); pop.showAtLocation(parentView, Gravity.BOTTOM, 0, 0); } else { Intent intent = new Intent(ReleaseHomeWork.this, GalleryActivity.class); intent.putExtra("position", "1"); intent.putExtra("ID", arg2); startActivity(intent); } } }); } //选择图片或者拍照的适配器 @SuppressLint("HandlerLeak") public class GridAdapter extends BaseAdapter { private LayoutInflater inflater; private int selectedPosition = -1; private boolean shape; public boolean isShape() { return shape; } public void setShape(boolean shape) { this.shape = shape; } public GridAdapter(Context context) { inflater = LayoutInflater.from(context); } public void update() { // loading(); } public int getCount() { if (Bimp.tempSelectBitmap.size() == 9) { return 9; } return (Bimp.tempSelectBitmap.size() + 1); } public Object getItem(int arg0) { return null; } public long getItemId(int arg0) { return 0; } public void setSelectedPosition(int position) { selectedPosition = position; } public int getSelectedPosition() { return selectedPosition; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { convertView = inflater.inflate(R.layout.item_published_grida, parent, false); holder = new ViewHolder(); holder.image = (ImageView) convertView .findViewById(R.id.item_grida_image); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } if (position == Bimp.tempSelectBitmap.size()) { holder.image.setImageBitmap(BitmapFactory.decodeResource( getResources(), R.drawable.icon_addpic_unfocused)); if (position == 9) { holder.image.setVisibility(View.GONE); } } else { holder.image.setImageBitmap(Bimp.tempSelectBitmap.get(position).getBitmap()); } return convertView; } public class ViewHolder { public ImageView image; } Handler handler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 1: adapter1.notifyDataSetChanged(); break; } super.handleMessage(msg); } }; // public void loading() { // thread= new MyThread(); // thread.start(); // } // } // public class MyThread extends Thread { // // public void run(){ // while (true) { // if (Bimp.max == Bimp.tempSelectBitmap.size()) { // Message message = new Message(); // message.what = 1; // handler.sendMessage(message); // break; // } else { // Bimp.max += 1; // Message message = new Message(); // message.what = 1; // handler.sendMessage(message); // if (Bimp.max >= 9) { // break; // } // } // } // } } public String getString(String s) { String path = null; if (s == null) return ""; for (int i = s.length() - 1; i > 0; i++) { s.charAt(i); } return path; } protected void onRestart() { adapter1.update(); super.onRestart(); } private static final int CAMERA_REQUEST_CODE = 3; private static final int TAKE_PICTURE = 0x000001; String filename = ""; Uri photoUri = null; //拍照方法 public void photo() { Intent intentFromCapture = new Intent( MediaStore.ACTION_IMAGE_CAPTURE); // 判断存储卡是否可以用,可用进行存储 if (hasSdcard()) { intentFromCapture.putExtra( MediaStore.EXTRA_OUTPUT, Uri.fromFile(createImageFile())); } startActivityForResult(intentFromCapture, CAMERA_REQUEST_CODE); } /** * 检查设备是否存在SDCard的工具方法 */ private boolean hasSdcard() { String state = Environment.getExternalStorageState(); // 有存储的SDCard return state.equals(Environment.MEDIA_MOUNTED); } protected String getAbsoluteImagePath(Uri uri) { // can post image String[] proj = {MediaStore.Images.Media.DATA}; Cursor cursor = managedQuery(uri, proj, // Which columns to return null, // WHERE clause; which rows to return (all rows) null, // WHERE clause selection arguments (none) null); // Order-by clause (ascending by name) int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); cursor.close(); return cursor.getString(column_index); } String mCurrentPhotoPath; //以mCurrentPhotoPath为路劲创建文件 private File createImageFile() { File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); File image = null; try { image = File.createTempFile( generateFileName(), /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ); } catch (IOException e) { e.printStackTrace(); } mCurrentPhotoPath = image.getAbsolutePath(); return image; } //根据当前时间新建一个文件名 private String generateFileName() { String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; return imageFileName; } protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case TAKE_PICTURE: if (Bimp.tempSelectBitmap.size() < 9 && resultCode == RESULT_OK) { String path = ""; Cursor cursor = null; if (photoUri != null) { String[] proj = {MediaStore.Images.Media.DATA}; cursor = managedQuery(photoUri, proj, null, null, null); int column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); path = cursor.getString(column_index); cursor.close(); } try { ImageItem takePhoto = new ImageItem(); takePhoto.setImagePath(path); Bimp.tempSelectBitmap.add(takePhoto); } catch (Exception e) { e.printStackTrace(); } } break; case CAMERA_REQUEST_CODE: if (Bimp.tempSelectBitmap.size() < 9 && resultCode == RESULT_OK) { if (hasSdcard()) { ImageItem takePhoto = new ImageItem(); takePhoto.setImagePath(mCurrentPhotoPath); Bimp.tempSelectBitmap.add(takePhoto); } else { Toast.makeText(getApplicationContext(), "未找到存储卡,无法存储照片!", Toast.LENGTH_SHORT).show(); } } break; } } }