我正在尝试从相机或图库中捕获图像并将其保存到php服务器(使用我的sql)。我附加了我的活动代码以及布局和错误日志。我在尝试时获取位图的NullPointerException传递到webservice.Image正确显示在图像视图中,只有问题是传递给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)
答案 0 :(得分:0)
我将您发布的代码复制到一个活动中,并注释掉与发布图像和处理JSON响应相关的语句。我在KitKat设备上运行活动,从库中选择图片并使用相机捕获图像。我无法重现崩溃。
堆栈跟踪指示当在AsyncTask的后台处理中执行此语句时,bitmap_cm
为空。
bitmap_cm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
您在帖子和评论中指出,当崩溃发生时,预期的图像在视图中可见。我无法理解这是怎么发生的。我希望当bitmap_cm
为null时,imageView将为空。
请注意,如果BitmapFactory.decodeFile()
无法解码文件,则Log
将返回null。您应该检查该调用的结果并处理失败案例。同时添加<ol reversed start="5">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
语句以报告处理状态。
答案 1 :(得分:0)
以前我正在检查编码本身是否有问题,当qbix能够运行相同的代码而没有错误..我已经清理了项目并重新生成所有项目和库,它工作正常..感谢你的帮助qbix