Я пытаюсь отправить объект json
и несколько данных String в asynctask
для связи с api
. Я использую следующий код и в этом могу передать только String
значений (все значения, которые я передаю из активности, - Strings
).Передача объекта json классу asynctask из класса активности
Я знаю, как создать объект, и я его уже создал. Я хочу знать, как передать объект JSON
и другие строки сразу.
Может ли кто-нибудь помочь мне с этим.
Любая помощь будет высоко оценена.
Эти данные я хочу перейти к AsyncTask,
активность,
new GetAllDiscountsAsyncTask(getBaseContext(),
new OnTaskCompleted() {
@Override
public void onTaskCompleted(JSONArray responseJson) {
System.out.println("GetAllDiscountsAsyncTask");
Intent i = new Intent(getApplicationContext(),
CardPromotionListActivity.class);
}
}).execute(CartItemEntitys, OrderID, OutletCode,
equiredDate, Total);
AsyncTask класс
public class GetAllDiscountsAsyncTask extends AsyncTask<String, Integer, JSONArray> {
private OnTaskCompleted listener;
private JSONArray responseJson = null;
private Context contxt;
private Activity activity;
String email;
public GetAllDiscountsAsyncTask(Context context, OnTaskCompleted listener) {
// API = apiURL;
this.contxt = context;
this.listener = listener;
}
// async task to accept string array from context array
@Override
protected JSONArray doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
JSONObject requestJson = null;
DefaultHttpClient httpClient = null;
HttpPost httpPost = null;
StringEntity requestString = null;
ResponseHandler<String> responseHandler = null;
Log.i("CardNo", "0");
Log.i("CartItemEntity", params[0]);
Log.i("DiscountCode", "0");
Log.i("OrderID", params[1]);
Log.i("OutletCode", params[2]);
Log.i("PayCode", "0");
Log.i("PhoneNo", "0");
Log.i("RequiredDate", params[3]);
Log.i("Total", params[4]);
try {
path = "http://203.94.69.162:3331/ItemService.svc/GetAllDiscounts";
new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
// set the API request
request = new HashMap<String, String>();
request.put(new String("CardNo"), "0");
request.put(new String("CartItemEntity"), params[0]);
request.put(new String("DiscountCode"), "0");
request.put(new String("OrderID"), params[1]);
request.put(new String("OutletCode"), params[2]);
request.put(new String("PayCode"), "0");
request.put(new String("PhoneNo"), "4545");
request.put(new String("RequiredDate"), params[3]);
request.put(new String("Total"), params[4]);
request.entrySet().iterator();
// Store locations in JSON
requestJson = new JSONObject(request);
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(path);
requestString = new StringEntity(requestJson.toString());
// sets the post request as the resulting string
httpPost.setEntity(requestString);
httpPost.setHeader("Content-type", "application/json");
// Handles the response
responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
responseJson = new JSONArray(response);
System.out.println("*****JARRAY*****" + responseJson.length());
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
responseJson = new JSONArray(response);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return responseJson;
}
@Override
protected void onPostExecute(JSONArray result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
listener.onTaskCompleted(responseJson);
}
}
Json Объект, в деятельности класса
На данный момент я преобразовать это в String, и отправить его в AsyncTask, но я хочу, чтобы отправить без преобразования,
JSONObject jsonObj = new JSONObject();
jsonObj.put("MainMenuCode",item.getMainMenuCode());
jsonObj.put("Price", item.getPrice());
jsonObj.put("Quantity", product.getQuantity());
jsonObj.put("SubMenuCode",item.getSubMenuCode());
String a = jsonObj.toString();
CartIddtemEntityList.add(a);
CartItemEntitys = CartIddtemEntityList.toString();
где находится объект JSON, что вам нужно пройти? –
, так что вам нужно передать jsonObj на webservice, что вы используете! это то, о чем вы просите? –
да, но у меня есть один объект json и 8 строк для отправки, как показано на снимке экрана в моем вопросе. –