我有一个活动,因为我有一个用于调用api的asynctask,因为我发布了一些数据,一切都没有图像,但是当我尝试将图像发送到url时,它会停止,例外,请看到我的代码并解决我,请保存meplease ,,谢谢 的 mycode.java
package com.epe.yehki.ui;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.epe.yehki.adapter.BuyingRequestAdapter;
import com.epe.yehki.adapter.QuoteAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.uc.Header;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Pref;
import com.epe.yehki.util.Utils;
import com.example.yehki.R;
public class BuyingreqActivity extends Activity implements OnClickListener {
Button viewReq, postReq;
EditText productName;
TextView productCategory;
TextView expTime;
TextView productDesc;
TextView estOrderQty;
ImageView proImg;
Button send;
Uri selectedImage;
ImageView iv_fav_menu;
private static int RESULT_LOAD_IMAGE = 1;
private int flag = 1;
ScrollView scr_post;
FileInputStream imageInFile;
RelativeLayout scr_view;
Intent cropIntent;
byte[] imageBytes;
byte[] byteArray;
RelativeLayout quote_view;
private ProgressDialog pDialog;
String viewURL, postURL;
String encodedImage;
JSONObject jsonObj;
String quote_id, buyerID;
String id, name;
JSONArray requestes = null;
JSONArray quotes = null;
ArrayList<HashMap<String, String>> reqList;
ArrayList<HashMap<String, String>> queList;
private BuyingRequestAdapter buyingRequestContent;
private QuoteAdapter quoteAdapter;
RelativeLayout rl_botm;
ListView lv;
String imageDataString;
Header header;
Calendar dateandtime;
private static final int PICK_FROM_CAMERA = 100;
private static final int PICK_FROM_GALLERY = 200;
private static final int PICK_FROM_CATEGORY = 300;
final int CATEGORY_SELECT = 2;
private Uri picUri;
int la, lo;
final int CAMERA_CAPTURE = 1;
private static String fileName;
Intent in = null;
ListView quoteList;
private String imagePath;
private Uri imageUri;
String buyer_request_id, reqID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_buying_request);
InitializeView();
productCategory.setOnClickListener(this);
send.setOnClickListener(this);
expTime.setOnClickListener(this);
proImg.setOnClickListener(this);
dateandtime = Calendar.getInstance(Locale.US);
send.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new postBuyingReqList().execute();
}
});
header.back.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
reqList = new ArrayList<HashMap<String, String>>();
queList = new ArrayList<HashMap<String, String>>();
viewReq.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
flag = 2;
reqList.clear();
iv_fav_menu.setBackgroundResource(R.drawable.tab_two_fav);
callGetQuoteListAsyncTask();
scr_view.setVisibility(View.VISIBLE);
quote_view.setVisibility(View.GONE);
rl_botm.setVisibility(View.GONE);
scr_post.setVisibility(View.GONE);
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
in = new Intent(getApplicationContext(), BuyingRequestDetailActivity.class);
// getting ProductId from the tag...
String buyReqID = reqList.get(position).get(Const.TAG_BUYING_REQUEST_ID);
System.out.println(":::::::::::::::;;THE INTENT FOR THE resuest DETIALS ACTIVITY=================" + buyReqID);
in.putExtra(Const.TAG_BUYING_REQUEST_ID, buyReqID);
in.putExtra(Const.TAG_QUOTE_ID, quote_id);
System.out.println("::::::::::::Buyer Id and Request Id::::::::;" + buyReqID + " ====>" + quote_id);
startActivity(in);
}
});
quoteList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
in = new Intent(getApplicationContext(), QuoteDetailActivity.class);
// getting ProductId from the tag...
reqID = queList.get(position).get(Const.TAG_BUYING_REQUEST_ID);
quote_id = queList.get(position).get(Const.TAG_QUOTE_ID);
System.out.println(":::::::::::::::;;THE INTENT FOR THE resuest DETIALS ACTIVITY=================" + reqID);
in.putExtra(Const.TAG_BUYING_REQUEST_ID, reqID);
in.putExtra(Const.TAG_QUOTE_ID, quote_id);
System.out.println("::::::::::::Buyer Id and Request Id::::::::;" + reqID + " ====>" + quote_id);
startActivity(in);
}
});
postReq.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
flag = 1;
iv_fav_menu.setBackgroundResource(R.drawable.tab_one_fav);
quote_view.setVisibility(View.GONE);
scr_post.setVisibility(View.VISIBLE);
rl_botm.setVisibility(View.VISIBLE);
scr_view.setVisibility(View.GONE);
}
});
}
@Override
public void onClick(View v) {
Intent i;
switch (v.getId()) {
case R.id.tv_pro_cat:
i = new Intent(BuyingreqActivity.this, ProCategoryActivity.class);
startActivityForResult(i, 10);
break;
case R.id.tv_pro_exp_tym:
DatePickerDailog dp = new DatePickerDailog(BuyingreqActivity.this, dateandtime, new DatePickerDailog.DatePickerListner() {
@Override
public void OnDoneButton(Dialog datedialog, Calendar c) {
datedialog.dismiss();
dateandtime.set(Calendar.YEAR, c.get(Calendar.YEAR));
dateandtime.set(Calendar.MONTH, c.get(Calendar.MONTH));
dateandtime.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH));
expTime.setText(new SimpleDateFormat("yyyy-MM-dd").format(c.getTime()));
}
@Override
public void OnCancelButton(Dialog datedialog) {
// TODO Auto-generated method stub
datedialog.dismiss();
}
});
dp.show();
break;
/*
* case R.id.btn_send: new postBuyingReqList().execute();
*
* break;
*/
case R.id.iv_img:
i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
break;
}
}
void InitializeView() {
iv_fav_menu = (ImageView) findViewById(R.id.iv_fav_menu);
viewReq = (Button) findViewById(R.id.btn_view);
postReq = (Button) findViewById(R.id.btn_post);
scr_post = (ScrollView) findViewById(R.id.scr_post);
scr_view = (RelativeLayout) findViewById(R.id.scr_view);
quote_view = (RelativeLayout) findViewById(R.id.quote_view);
quoteList = (ListView) findViewById(R.id.quote_list);
lv = (ListView) findViewById(R.id.req_list);
rl_botm = (RelativeLayout) findViewById(R.id.rl_botm);
header = (Header) findViewById(R.id.headerBuying);
header.title.setText("Post Buying Request");
proImg = (ImageView) findViewById(R.id.iv_img);
productName = (EditText) findViewById(R.id.et_pro_name);
productCategory = (TextView) findViewById(R.id.tv_pro_cat);
expTime = (TextView) findViewById(R.id.tv_pro_exp_tym);
productDesc = (EditText) findViewById(R.id.et_pro_desc);
estOrderQty = (TextView) findViewById(R.id.et_est_qty);
send = (Button) findViewById(R.id.btn_send);
}
/*
* getting buying request list...!!!
*/
private class GetBuyingReqList extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(BuyingreqActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
String query = "?customer_id=" + Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "");
query = query.replace(" ", "%20");
viewURL = Const.API_BUYING_REQUEST_LIST + query;
BackendAPIService sh = new BackendAPIService();
System.out.println(":::::::::::::::::::ADDRESS URL:::::::::::::::::" + viewURL);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(viewURL, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.has(Const.TAG_BUYING_REQUEST)) {
System.out.println("::::::::::::::::true::::::::::::::::" + jsonObj.has(Const.TAG_ADDRESS_LIST));
requestes = jsonObj.getJSONArray(Const.TAG_BUYING_REQUEST);
if (requestes != null && requestes.length() != 0) {
// looping through All Contacts
System.out.println(":::::::::::FLAG IN SUB:::::::::::" + flag);
for (int i = 0; i < requestes.length(); i++) {
JSONObject c = requestes.getJSONObject(i);
String buyer_request_id = c.getString(Const.TAG_BUYING_REQUEST_ID);
System.out.println(":::::::::::::::MY buying request:::::::::::::" + buyer_request_id);
String subject = c.getString(Const.TAG_PRODUCT_NAME);
String date_modified = c.getString(Const.TAG_DATE_MODIFIED);
String expired_date = c.getString(Const.TAG_EXPIRY_DATE);
String quote_count = c.getString(Const.TAG_QUOTE_COUNT);
String buying_request_status = c.getString(Const.TAG_BUYING_REQUEST_STATUS);
HashMap<String, String> request = new HashMap<String, String>();
request.put(Const.TAG_BUYING_REQUEST_ID, buyer_request_id);
request.put(Const.TAG_PRODUCT_NAME, subject);
request.put(Const.TAG_DATE_MODIFIED, date_modified);
request.put(Const.TAG_EXPIRY_DATE, expired_date);
request.put(Const.TAG_QUOTE_COUNT, quote_count);
request.put(Const.TAG_BUYING_REQUEST_STATUS, buying_request_status);
reqList.add(request);
System.out.println("::::::::::::::::REQUEST IDS::::::::::::" + buyer_request_id);
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
*
* */
buyingRequestContent = new BuyingRequestAdapter(BuyingreqActivity.this, reqList);
lv.setAdapter(buyingRequestContent);
}
}
public void callGetQuoteListAsyncTask() {
new GetBuyingReqList().execute();
}
/*
* getting qoute List...!!!
*/
public class GetQuoteList extends AsyncTask<String, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
queList.clear();
pDialog = new ProgressDialog(BuyingreqActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
scr_post.setVisibility(View.GONE);
scr_view.setVisibility(View.GONE);
quote_view.setVisibility(View.VISIBLE);
pDialog.show();
}
@Override
protected Void doInBackground(String... arg0) {
// String query = "?customer_id=" +
// Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "")
// + "&buyer_request_id=23";
String reqID = arg0[0];
String query = "?customer_id=" + Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "") + "&buyer_request_id=" + reqID;
query = query.replace(" ", "%20");
viewURL = Const.API_QUOTE_RECIEVED + query;
BackendAPIService sh = new BackendAPIService();
System.out.println(":::::::::::::::::::ADDRESS URL:::::::::::::::::" + viewURL);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(viewURL, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.has(Const.TAG_BUYING_REQUEST)) {
System.out.println("::::::::::::::::true::::::::::::::::" + jsonObj.has(Const.TAG_ADDRESS_LIST));
requestes = jsonObj.getJSONArray(Const.TAG_BUYING_REQUEST);
if (requestes != null && requestes.length() != 0) {
// looping through All Contacts
System.out.println(":::::::::::FLAG IN SUB:::::::::::" + flag);
for (int i = 0; i < requestes.length(); i++) {
JSONObject c = requestes.getJSONObject(i);
buyerID = c.getString(Const.TAG_BUYING_REQUEST_ID);
System.out.println(":::::::::::::::MY buying request:::::::::::::" + buyerID);
String product_name = c.getString(Const.TAG_PRODUCT_NAME);
String quote_id = c.getString(Const.TAG_QUOTE_ID);
String supplier_name = c.getString(Const.TAG_SUPPLIER_NAME);
String status = c.getString(Const.TAG_STATUS);
HashMap<String, String> quote = new HashMap<String, String>();
quote.put(Const.TAG_BUYING_REQUEST_ID, buyerID);
quote.put(Const.TAG_PRODUCT_NAME, product_name);
quote.put(Const.TAG_QUOTE_ID, quote_id);
quote.put(Const.TAG_EXPIRY_DATE, supplier_name);
quote.put(Const.TAG_QUOTE_COUNT, status);
queList.add(quote);
System.out.println(":::::::::::::Buyer request ID:" + buyerID);
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
*
* */
quoteAdapter = new QuoteAdapter(BuyingreqActivity.this, queList);
quoteList.setAdapter(quoteAdapter);
}
}
// ============================
/*
* post Buying Request api()...!!!
*/
public String encodeUTF(String str) {
try {
byte[] utf8Bytes = str.getBytes("UTF-8");
String encodedStr = new String(utf8Bytes, "UTF-8");
return encodedStr;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return str;
}
private class postBuyingReqList extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(BuyingreqActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
String profileImgEncoded = null;
if (byteArray != null) {
profileImgEncoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
/*
* profileImgEncoded = profileImgEncoded.replace('/',
* '%').replace(':', '%').replace('?', '%').replace('#',
* '%').replace('[', '%').replace(']', '%').replace('@',
* '%').replace('!', '%') .replace('$', '%').replace('&',
* '%').replace('(', '%').replace(')', '%').replace('*',
* '%').replace('+', '%').replace(',', '%').replace(':',
* '%').replace('=', '%');
*/
// (":/?#[]@!$&’()*+,;=")
// String(jo.getString("name").getBytes("ISO-8859-1"), "UTF-8");
profileImgEncoded = encodeUTF(profileImgEncoded);
System.out.println("::::::::::::::::::Encoded Image::::::::::" + profileImgEncoded);
postURL = Const.API_BUYING_REQUEST + "?customer_id=" + Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "") + "&product_name=" + productName.getText().toString().trim()
+ "&category_id=" + id + "&expire_time=" + expTime.getText().toString() + "&detail_desc=" + productDesc.getText().toString().trim() + "&esti_ordr_qty="
+ estOrderQty.getText().toString().trim() + "&esti_ordr_qty_unit=1&filename=imagefilename&image=" + profileImgEncoded;
// Creating service handler class instance
/* postURL = postURL.replace(" ", "%20"); */
System.out.println(":::::::::::::::::::post buying request URL:::::::::::::::::" + postURL);
BackendAPIService sh = new BackendAPIService();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(postURL, BackendAPIService.POST);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.get("status").equals("success")) {
System.out.println(":::::::::::::::::POSTED::::::::::::::::::::::::");
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
Utils.showCustomeAlertValidation(BuyingreqActivity.this, "Request Posted", "Yehki", "OK");
clearViews();
/**
* Updating parsed JSON data into ListView
*
* */
}
}
void clearViews() {
productName.setText("");
productDesc.setText("");
estOrderQty.setText("");
expTime.setText("Expiration Time");
proImg.setImageResource(R.drawable.noimage);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
cursor.close();
proImg.setImageBitmap(bitmap);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byteArray = stream.toByteArray();
// String picturePath contains the path of selected Image
}
if (requestCode == 10) {
if (resultCode == RESULT_OK) {
id = data.getStringExtra("ID");
name = data.getStringExtra("NAME");
System.out.println("::::::::::::::::::On activity result:::::::::::" + id + "==========" + name);
productCategory.setText(name);
}
if (resultCode == RESULT_CANCELED) {
// Write your code if there's no result
}
}
}
}