- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我在这个文件中有内存泄漏,我找不到确切位置,但我认为是周围的图像 --> (Bitmap bm = BitmapFactory.decodeFile(filename))
,我试过了许多不同的方法,但我无法让它工作。
package prod.vegs;
//All imports here but not need to write them all now :-)
public class ProductForm extends Activity {
private static int TAKE_PICTURE = 1;
private static int SELECT_PICTURE = 2;
//JSON Response node names
private static String KEY_SUCCESS = "success";
private static String ERROR_MSG = "error_msg";
private static String KEY_TYPES = "subtypes";
private static String TYPE_NAME = "name";
private static String TYPE_ID = "id_type";
private static String PRODUCT_ID = "id_product";
private JSONObject json;
private JSONParser jsonParser;
private String barcodeStr;
private String filename;
private int code;
private ProgressDialog dialog;
private TypeClass[] items;
private TypeClass[] sub_items;
//Declare assets objects
Spinner type;
Spinner subtype;
TextView errorMsg;
TextView description;
TextView name;
Button camera;
Button gallery;
Intent intent;
ImageView preview;
Bundle bundle;
LinearLayout errorMsgContainer;
Context context;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.product_form);
context = this;
Bundle b = getIntent().getExtras();
barcodeStr = b.getString("barcode");
jsonParser = new JSONParser();
dialog = new ProgressDialog(this);
dialog.setMessage(getString(R.string.loading));
dialog.setTitle(getString(R.string.progress));
dialog.setCancelable(true);
//Set assets
name = (TextView) findViewById(R.id.productName);
description = (TextView) findViewById(R.id.productDescription);
errorMsg = (TextView) findViewById(R.id.error_msg);
errorMsgContainer = (LinearLayout) findViewById(R.id.error_msg_container);
type = (Spinner) findViewById(R.id.productParentType);
subtype = (Spinner) findViewById(R.id.productType);
camera = (Button) findViewById(R.id.productCamera);
gallery = (Button) findViewById(R.id.productGallery);
preview = (ImageView) findViewById(R.id.productPreview);
filename = Environment.getExternalStorageDirectory() + String.format(getString(R.string.api_product_form_picture_file), barcodeStr);
Boolean fromScanner = b.getBoolean("scanner");
if (fromScanner == true) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setMessage(getString(R.string.insert_product));
alertbox.setPositiveButton(getString(R.string.yes),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg_1, int arg_num) {
final Functions function = new Functions();
List<NameValuePair> params = new ArrayList<NameValuePair>();
String url = String.format(getString(R.string.api_product_form_types_url), getString(R.string.api_url));
json = function.loadJSONUrl(url, params);
if(json != null){
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
JSONArray types = json.getJSONArray(KEY_TYPES);
items = convertJSONArray(types);
SpinAdapter listViewArrayAdapter = new SpinAdapter(context, android.R.layout.simple_spinner_item, items);
listViewArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
type.setAdapter(listViewArrayAdapter);
type.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
try {
String url = String.format(getString(R.string.api_subtypes_id_url), getString(R.string.api_url), ((TypeClass) type.getSelectedItem()).getId());
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json_subtypes = function.loadJSONUrl(url, params);
if (json_subtypes.getString(KEY_SUCCESS) != null) {
JSONArray subtypes = json_subtypes.getJSONArray(KEY_TYPES);
sub_items = convertJSONArray(subtypes);
SpinAdapter subTypeAdapter = new SpinAdapter(context, android.R.layout.simple_spinner_item, sub_items);
subTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
subtype.setAdapter(subTypeAdapter);
subtype.setPrompt("Selecciona la cateogría");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void onNothingSelected(AdapterView<?> args) {
//Auto-generated method stub
}
});
type.setPrompt("Selecciona la cateogría");
//camera action
camera.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
int timeMili = (int) (System.currentTimeMillis());
filename = Environment.getExternalStorageDirectory() + "/" + timeMili + ".jpg";
Uri output = Uri.fromFile(new File(filename));
intent.putExtra(MediaStore.EXTRA_OUTPUT, output);
code = TAKE_PICTURE;
startActivityForResult(intent, code);
}
});
//gallery action
gallery.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
code = SELECT_PICTURE;
startActivityForResult(intent, code);
}
});
//button of the form
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (!NetworkHelper.CheckNetworkStatus(view.getContext())) {
return;
}
bundle = new Bundle();
bundle.putString("barcode", barcodeStr.toString());
bundle.putString("name", name.getText().toString());
bundle.putString("description", description.getText().toString());
bundle.putString("type_id", ((TypeClass) subtype.getSelectedItem()).getId());
if (_checkFormValues()) {
new SendDataJSON().execute(view);
} else {
Toast.makeText( view.getContext(), getString(R.string.error_form_incomplete), Toast.LENGTH_LONG).show();
}
}
});
} else {
errorMsg.setText(json.getString(ERROR_MSG));
errorMsgContainer.setVisibility(LinearLayout.VISIBLE);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
}
}
}).setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Intent myIntent = new Intent(ProductForm.this, CaptureActivity.class);
startActivity(myIntent);
finish();
}
}).show();
} else {
finish();
}
}
class SendDataJSON extends AsyncTask<View, Void, View>{
@Override
protected View doInBackground(View... views) {
String url = String.format(getString(R.string.api_product_form_url),getString(R.string.api_url));
HttpPost httpPost = new HttpPost(url);
try {
// Add your data
MultipartEntity entity = new MultipartEntity();
File photo = new File(filename);
if (photo.exists()) {
//create the compressed image to send
//create the file to send the image
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (!sd.canWrite()) { sd = data; }
String destinationFolderPath = sd + "/" + getString(R.string.app_dir) + "/";
String destinationImageName= "photo_" + bundle.getString("barcode") + ".jpg";
//create the folder to store it
File destinationFolder = new File(destinationFolderPath);
if (!destinationFolder.exists()) {
destinationFolder.mkdirs();
}
File destination = new File(destinationFolder, destinationImageName);
FileOutputStream out = new FileOutputStream(destination);
Bitmap bm = BitmapFactory.decodeFile(filename);
int width = bm.getWidth();
int height = bm.getHeight();
int max_value = 1024;
int max = Math.max(width,height);
if (max > max_value) {
width = width * max_value / max;
height = height * max_value / max;
}
//Make the new image with the new size values
try {
Bitmap bm2 = Bitmap.createScaledBitmap(bm, width, height, true);
//Compress the image
bm2.compress(CompressFormat.JPEG, 75, out);
out.flush();
out.close();
destination = new File(destinationFolder, destinationImageName);
FileBody filePhoto = new FileBody(destination);
entity.addPart("image", filePhoto);
} catch (Exception e) {
Log.w(ProductForm.class.getSimpleName(), e);
}
}
SharedPreferences userSettings = getSharedPreferences("UserPreferences", Context.MODE_PRIVATE);
Charset chars = Charset.forName("UTF-8");
entity.addPart("barcode", new StringBody(bundle.getString("barcode"),chars));
entity.addPart("name", new StringBody(bundle.getString("name"),chars));
entity.addPart("description", new StringBody(bundle.getString("description"),chars));
entity.addPart("id_type", new StringBody(bundle.getString("type_id")));
entity.addPart("uid",new StringBody(userSettings.getString("uid", ""),chars));
httpPost.setEntity(entity);
HttpClient httpclient = new DefaultHttpClient();
httpclient.execute(httpPost);
} catch (IOException e) {
//
}
return views[0];
}
@Override
protected void onPreExecute() {
dialog.setMax(100);
dialog.setProgress(0);
dialog.show();
}
@Override
protected void onPostExecute(View view) {
//redirect to the product page
setContentView(R.layout.product_barcode);
String url = String.format(getString(R.string.api_product_barcode_url), getString(R.string.api_url), bundle.getString("barcode"));
new LoadJSONBarcode().execute(url);
}
}
//Send data to server and receive respond
private class LoadJSONBarcode extends AsyncTask<String, Void, JSONObject>{
@Override
protected JSONObject doInBackground(String... urls) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
json = new JSONObject();
json = jsonParser.getJSONFromUrl(urls[0], params);
return json;
}
@Override
protected void onPreExecute() {
dialog.setMax(100);
dialog.setProgress(0);
dialog.show();
}
@Override
protected void onPostExecute(JSONObject json) {
if (json != null) {
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
View view = findViewById(R.id.productBarcodeXML);
Intent myIntent = new Intent(view.getContext(), Product.class);
Bundle b = new Bundle();
b.putString("id", json.getString(PRODUCT_ID));
myIntent.putExtras(b);
view.getContext().startActivity(myIntent);
} else {
errorMsg.setText(json.getString(ERROR_MSG));
errorMsgContainer.setVisibility(LinearLayout.VISIBLE);
}
dialog.dismiss();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TAKE_PICTURE) {
if (data != null) {
if (data.hasExtra("data")) {
preview.setImageBitmap((Bitmap) data.getParcelableExtra("data"));
preview.setVisibility(ImageView.VISIBLE);
}
} else {
preview.setImageBitmap(BitmapFactory.decodeFile(filename));
preview.setVisibility(ImageView.VISIBLE);
new MediaScannerConnectionClient() {
private MediaScannerConnection msc = null; {
msc = new MediaScannerConnection(getApplicationContext(), this); msc.connect();
}
public void onMediaScannerConnected() {
msc.scanFile(filename, null);
}
public void onScanCompleted(String path, Uri uri) {
msc.disconnect();
}
};
}
} else if (requestCode == SELECT_PICTURE){
if (data != null){
Uri selectedImage = data.getData();
InputStream is;
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filename = cursor.getString(columnIndex);
cursor.close();
try {
is = getContentResolver().openInputStream(selectedImage);
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bitmap = BitmapFactory.decodeStream(bis);
preview.setImageBitmap(bitmap);
preview.setVisibility(ImageView.VISIBLE);
} catch (FileNotFoundException e) {
}
}
}
}
private TypeClass[] convertJSONArray(JSONArray jsonArray){
int len = jsonArray.length();
TypeClass[] t = new TypeClass[len];
if (jsonArray != null) {
for (int i=0;i<len;i++){
try {
JSONObject o = jsonArray.getJSONObject(i);
t[i] = new TypeClass();
t[i].setName(o.getString(TYPE_NAME));
t[i].setId(o.getString(TYPE_ID));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return t;
}
protected boolean _checkFormValues() {
boolean result = true;
if (name.getText().length() == 0) {
name.requestFocus();
result = false;
}
if (((TypeClass) subtype.getSelectedItem()).getId() == null){
subtype.requestFocus();
result = false;
}
return result;
}
}
错误日志
11-07 23:55:26.914: E/AndroidRuntime(15457): FATAL EXCEPTION: AsyncTask #3
11-07 23:55:26.914: E/AndroidRuntime(15457): java.lang.RuntimeException: An error occured while executing doInBackground()
11-07 23:55:26.914: E/AndroidRuntime(15457): at android.os.AsyncTask$3.done(AsyncTask.java:278)
11-07 23:55:26.914: E/AndroidRuntime(15457): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-07 23:55:26.914: E/AndroidRuntime(15457): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-07 23:55:26.914: E/AndroidRuntime(15457): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-07 23:55:26.914: E/AndroidRuntime(15457): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-07 23:55:26.914: E/AndroidRuntime(15457): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-07 23:55:26.914: E/AndroidRuntime(15457): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-07 23:55:26.914: E/AndroidRuntime(15457): at java.lang.Thread.run(Thread.java:864)
11-07 23:55:26.914: E/AndroidRuntime(15457): Caused by: java.lang.OutOfMemoryError: (Heap Size=35491KB, Allocated=27993KB)
11-07 23:55:26.914: E/AndroidRuntime(15457): at android.graphics.BitmapFactory.nativeDecodeFile(Native Method)
11-07 23:55:26.914: E/AndroidRuntime(15457): at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:373)
11-07 23:55:26.914: E/AndroidRuntime(15457): at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:443)
11-07 23:55:26.914: E/AndroidRuntime(15457): at prod.vegs.ProductForm$SendDataJSON.doInBackground(ProductForm.java:272)
11-07 23:55:26.914: E/AndroidRuntime(15457): at prod.vegs.ProductForm$SendDataJSON.doInBackground(ProductForm.java:1)
11-07 23:55:26.914: E/AndroidRuntime(15457): at android.os.AsyncTask$2.call(AsyncTask.java:264)
11-07 23:55:26.914: E/AndroidRuntime(15457): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-07 23:55:26.914: E/AndroidRuntime(15457): ... 4 more
最佳答案
位图是非常大的内存消耗者。将两个加载到内存中可能是个大问题。您应该考虑使用 BitmapFactory.Options当你解码一个新的位图时。此外,您不需要 bm2
。相反,将该行替换为:
bm = Bitmap.createScaledBitmap(bm, width, height, true);
最后,如果没有其他选择,您可以使用 AndroidManifest.xml 中的应用程序属性 android:largeHeap="true"
来增加应用程序的堆大小。不需要此选项 - 并且仅应考虑用于极其图形密集的应用程序。
编辑
您可能会发现另一个有助于优化位图使用的链接:http://developer.android.com/training/tv/optimizing-layouts-tv.html#HandleLargeBitmaps
关于android - 尝试将带有图像的表单发送到 PHP 服务器时 Android 中的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12548203/
说真的,你怎么能在不发疯的情况下处理所有这些异常呢?我是不是读了太多关于异常处理的文章或什么?我尝试重构了几次,但每次似乎都以更糟糕的结果告终。也许我应该承认确实会发生异常(exception)情况,
背景 两者 try/rescue和 try/catch是 Elixir 中的错误处理技术。根据 corresponding chapter在介绍指南中。 Errors can be rescued u
每当我尝试在 Raspberry PI 上运行此 python 脚本时,我都会遇到问题: import socket import sys # Create a TCP/IP socket sock
我想知道一些关于 PHP 的 try , catch声明。 让我们考虑以下示例。 abstract class ExceptionA extends Exception {} class Except
我的 laravel v5.4 项目中有两个模型,user 和 admin。 在 config/auth.php 中,我向守卫和提供者添加了管理员,如下所示: 'guards' => [ 'w
try: r = requests.get(url, params={'s': thing}) except requests.ConnectionError, e: print e
我有以下代码。 但是,它并不能捕获所有错误,而我仍然会收到“throw er;//未处理的'错误'事件”。 为什么是这样? app.post('/api/properties/zip/:zip/bed
问题与细节 我正在使用自定义错误处理,遇到的错误之一是“路径中的非法字符”。我有一个自定义函数,旨在通过路径字符串查找此类非法字符,并在找到它们时引发自定义错误。但是我发现,取决于非法字符,Test-
This question already has answers here: How do I catch a numpy warning like it's an exception (not j
我正在使用其他人的代码,但我不熟悉try/catch,因此我举了一个类似的小例子。在第11行上,如果我写了error(''),似乎没有发现错误并增加了索引j。但是,编写error(' ')或error
我在我的一个程序中遇到了这个问题,在这种情况下,尝试/异常(exception)的错误使程序变得更好,以防用户意外输入了他们不应该输入的内容。它仍然给我错误,我为为什么感到困惑。如果对我的问题确实很重
我在尝试TRY ... CATCH块时遇到问题。有人可以解释为什么以下代码无法执行我的sp吗? DECLARE @Result int SET @Result = 0 BEGIN TRY SE
我有一个相当大的 powershell 脚本,其中包含许多(20 多个)执行各种操作的函数。 现在所有代码实际上都没有任何错误处理或重试功能。如果某个特定的任务/功能失败,它就会失败并继续。 我想改进
为什么我尝试时需要导入 inputmismatchException catch(InputMismatchException e){ System.out.println("
我对此感到困惑 - 我为辅助方法编写了一个 try/catch 。它的目的是捕获任何无效输入(任何不是“男性”或“女性”的内容(没有特定情况)。如果输入无效,它将通知用户,然后让他们重试。如果有效,则
我有时会发现自己处于如下场景。尽可能简单地陈述问题 “有时我会创建一段代码,Java 让我将其包含在 try/catch 语句中。我没有使用 catch,所以我将其留空。为什么这是错误的?” boo
我有点困惑为什么当我不使用 Try block 时会出现 Try block 错误。 我在代码块底部附近收到错误通知。如果我不使用 try/catch,有人可以向我解释为什么会发生这种情况吗? 它是否
我已经盯着我的电脑两个小时了,我不知道我做错了什么。谁能帮助我看到光明? package blackjack; import java.util.Random; import java.util.Sc
我想将方法保存在 Enum 中,但 Class.getDeclaredMethod 抛出 NoSuchMethodException,那么我该如何处理呢?我的代码: public enum Car
这个问题已经有答案了: Executing multi-line statements in the one-line command-line (18 个回答) 已关闭 3 年前。 如何使用try.
我是一名优秀的程序员,十分优秀!