使用Web服务的位图图像的NullPointerException



我试图从相机或从画廊捕获图像,并将其保存到php服务器(使用我的sql)。我已经附上了我的活动代码和布局和错误日志。当我试图传递到webservice时,我得到了位图的NullPointerException。图像在图像视图中正确显示,唯一的问题是当传递给webservice时。

public class PhotoIntentActivity extends Activity {
    private static String MedicineURL = AppConfig.URL_MEDICINE;
    private ProgressDialog dialog;
    public Bitmap bitmap_cm;
    ImageView viewImage;
    Button btnUpload;
    Button btnSubmit; 
    Button btnCancel;
    TextView psttxtOcrResult;   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photo);
        btnUpload=(Button)findViewById(R.id.btnSelectPhoto);
        viewImage=(ImageView)findViewById(R.id.viewImage);        
        btnSubmit = (Button) findViewById(R.id.Submit);
        btnCancel = (Button) findViewById(R.id.btnCancel);
        psttxtOcrResult=(TextView)findViewById(R.id.txtOcrResult); 
        btnUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectImage();
            }
        });
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dialog = ProgressDialog.show(PhotoIntentActivity.this, "Uploading",
                            "Please wait...", true);
                new ImageUploadTask().execute();
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewImage.setImageResource(0);
                psttxtOcrResult.setText("");
                btnSubmit.setVisibility(View.GONE); 
            }
        });
        //..set visible false 
        btnSubmit.setVisibility(View.GONE);
        btnCancel.setVisibility(View.GONE);
        psttxtOcrResult.setVisibility(View.GONE);       
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds options to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
      private void selectImage() {
        final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
        AlertDialog.Builder builder = new AlertDialog.Builder(PhotoIntentActivity.this);
        builder.setTitle("Take Photo!");
        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (options[item].equals("Take Photo"))
                {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                    startActivityForResult(intent, 1);
                }
                else if (options[item].equals("Choose from Gallery"))
                {
                    Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, 2);
                    /*Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent,
                            "Complete action using"), 2); */                   
                }
                else if (options[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                File f = new File(Environment.getExternalStorageDirectory().toString());
                for (File temp : f.listFiles()) {
                    if (temp.getName().equals("temp.jpg")) {
                        f = temp;
                        break;
                    }
                }
                try {
                    Bitmap bitmap;
                    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
                    bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),bitmapOptions); 
                    bitmap_cm=bitmap;
                    viewImage.setImageBitmap(bitmap);
                    btnSubmit.setVisibility(View.VISIBLE); 
                    btnCancel.setVisibility(View.VISIBLE);
                    String path = android.os.Environment
                            .getExternalStorageDirectory()
                            + File.separator
                            + "Phoenix" + File.separator + "default";
                    f.delete();
                    OutputStream outFile = null;
                    File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");                 
                    try {
                        outFile = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                        outFile.flush();
                        outFile.close();                                               
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (requestCode == 2) {
                Uri selectedImage = data.getData();
                String[] filePath = { MediaStore.Images.Media.DATA };
                Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
                c.moveToFirst();
                int columnIndex = c.getColumnIndex(filePath[0]);
                String picturePath = c.getString(columnIndex);
                c.close();
                Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
                bitmap_cm=thumbnail;
                btnSubmit.setVisibility(View.VISIBLE); 
                btnCancel.setVisibility(View.VISIBLE);
                Log.w("path of image from gallery......******************.........", picturePath+"");
                viewImage.setImageBitmap(thumbnail);
            }
        }
    } 
    class ImageUploadTask extends AsyncTask<Void, Void, String> {
        @SuppressWarnings("deprecation")
        @Override
        protected String doInBackground(Void... unsued) {
            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpContext localContext = new BasicHttpContext();
                HttpPost httpPost = new HttpPost(MedicineURL + "?tag=post_scan_img");
                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bitmap_cm.compress(CompressFormat.JPEG, 100, bos);
                byte[] data = bos.toByteArray();
                entity.addPart("returnformat", new StringBody("json"));
                entity.addPart("Photo", new ByteArrayBody(data,"myImage.jpg"));
                //entity.addPart("pharmacy", new StringBody(spinnerPharmacies.getSelectedItem().toString()));
                entity.addPart("pharmacy", new StringBody("walgreen"));
                httpPost.setEntity(entity);
                HttpResponse response = httpClient.execute(httpPost,localContext);
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(
                                response.getEntity().getContent(), "UTF-8"));
                String sResponse = reader.readLine();
                return sResponse;
            } catch (Exception e) {
                if (dialog.isShowing())
                    dialog.dismiss();
                    //Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
                    Log.e(e.getClass().getName(), e.getMessage(), e);
                return null;
            }
            // (null);
        }
        @Override
        protected void onProgressUpdate(Void... unsued) {
        }
        @Override
        protected void onPostExecute(String sResponse) {
            try {
                if (dialog.isShowing())
                    dialog.dismiss();
                if (sResponse != null) {
                    JSONObject JResponse = new JSONObject(sResponse);
                    int success = JResponse.getInt("success");
                    String message = JResponse.getString("error");
                    if (success == 0) {
                        Toast.makeText(getApplicationContext(), message,
                                Toast.LENGTH_LONG).show();
                    } else {
                        //caption.setText("");
                        psttxtOcrResult.setVisibility(View.VISIBLE);
                        JSONObject json_med = JResponse.getJSONObject("_out_put");                      
                    }
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(),
                        e.getMessage(),
                        Toast.LENGTH_LONG).show();
                Log.e(e.getClass().getName(), e.getMessage(), e);
            }
        }
    }
}

布局:

<ScrollView 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/bg_comn_dark"  >
<LinearLayout               
          android:id="@+id/LinearLayout1"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:orientation="vertical"
           >
  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    style="@style/HeaderStyle"
    android:text="@string/str_capt_cmi" />
  <View style="@style/Divider"/>
<Button
        android:id="@+id/btnSelectPhoto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@style/ButtonStyle"
        android:text="Capture Now" 
        android:layout_marginTop="20dp"  />  
 <ImageView 
    android:id="@+id/viewImage" 
    android:layout_width="wrap_content"
    android:layout_height="200dp"
    android:background="@color/white"
    android:padding ="5dp"
    />

<Button 
    android:id="@+id/Submit"
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    style="@style/ButtonStyle"
    android:layout_marginTop="10dip"            
    android:text="@string/str_submit" />

    <Button
        android:id="@+id/btnCancel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        style="@style/ButtonStyle"
        android:text="Cancel" />        

<TextView
    android:id="@+id/txtOcrResult"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"   
    android:padding ="10dp"    
     /> 
 </LinearLayout> 
 </ScrollView>
错误日志:

07-14 11:51:15.316: E/java.lang.NullPointerException(1732): Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
07-14 11:51:15.316: E/java.lang.NullPointerException(1732): java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
07-14 11:51:15.316: E/java.lang.NullPointerException(1732):     at com.example.simplifimed.PhotoIntentActivity$ImageUploadTask.doInBackground(PhotoIntentActivity.java:224)
07-14 11:51:15.316: E/java.lang.NullPointerException(1732):     at com.example.simplifimed.PhotoIntentActivity$ImageUploadTask.doInBackground(PhotoIntentActivity.java:1)
07-14 11:51:15.316: E/java.lang.NullPointerException(1732):     at android.os.AsyncTask$2.call(AsyncTask.java:292)
07-14 11:51:15.316: E/java.lang.NullPointerException(1732):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-14 11:51:15.316: E/java.lang.NullPointerException(1732):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
07-14 11:51:15.316: E/java.lang.NullPointerException(1732):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
07-14 11:51:15.316: E/java.lang.NullPointerException(1732):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
07-14 11:51:15.316: E/java.lang.NullPointerException(1732):     at java.lang.Thread.run(Thread.java:818)

我复制了您发布到活动中的代码,并注释了与发布图像和处理JSON响应相关的语句。我在一台KitKat设备上运行了这个活动,从图片库中选择了一些照片,并用相机拍摄了照片。我无法重新创建崩溃。

堆栈跟踪表明,当此语句在AsyncTask的后台处理中执行时,bitmap_cm为空。

bitmap_cm.compress(Bitmap.CompressFormat.JPEG, 100, bos);

您在您的帖子和评论中指出,当崩溃发生时,预期的图像在视图中可见。我不明白怎么会发生这种事。我希望当bitmap_cm为null时,imageView将为空。

注意,BitmapFactory.decodeFile()将返回null,如果它不能解码文件。您应该检查调用的结果并处理失败情况。还可以添加Log语句来报告处理的状态。

以前我正在检查编码本身是否有问题,当qbix能够运行相同的代码而没有错误…我已经清理了项目并再次重建所有项目和库,它工作得很好。感谢qbix

的帮助

最新更新