gpt4 book ai didi

java - 如何通过动态使用android中的方法建立一个字符串url?

转载 作者:行者123 更新时间:2023-11-29 21:09:32 25 4
gpt4 key购买 nike

我做了一个 Activity 。因为我必须为 api 使用一个异步任务。所以在那个异步任务中,我的 url 将根据一些数字动态生成。我试过如下,但这不是正确的方法。谁能告诉我如何制作这个网址?

我的示例网址是: http://yehki.epagestore.in/app_api/order.php?customer_id=41&address_id=31&products[0][productName]=rt&products[0][product_id]=41&products[0][quantity]=2&products[0][unit]=1&products[0][unitPrice]=400&products[1][productName]=rt&products[1][product_id]=40&products[1][quantity]=2&products[1][unit]=1&products[1][unitPrice]=400

我的尝试是:

 package com.epe.yehki.ui;

import java.lang.reflect.Array;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.R.string;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Paint.Join;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.epe.yehki.adapter.CartAdapter;
import com.epe.yehki.backend.BackendAPIService;
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 CartPlaceOrderActivity extends Activity {
private ProgressDialog pDialog;

Button confirm, shipping;
RelativeLayout rl_adress;
TextView product_name;
String proName;
TextView tv_adress;
TextView tv_select_adres;
EditText qty;
String order_id;
EditText price;
TextView tv_subtotal;
JSONArray carts = null;
ListView cart_list;
String myUrl;
private CartAdapter cartContent;
JSONObject jsonObj;
ArrayList<HashMap<String, String>> cartList;
HashMap<String, String> cartProduct;

TextView tv_total;
ArrayAdapter<String> adapter;
String method;
ImageView back;
RadioGroup rd;
String add_id;
RadioButton yes, no;
Double min_qty, min_agree_prc, max_agree_prc, min_agree_qty, max_agree_qty, max_price, min_price;
String placeOrderurl, pro_desc;
String unit_id;
String min_qty_unit_name;
String subtotal, total;
ArrayList<HashMap<String, String>> productList;
Intent i;
String unit;
String pro_id;
JSONArray jArryCompleteOrder = null;
JSONArray jArryPayeeKey = null;
JSONArray jArryProductId = null;
JSONArray jArryOrderProId = null;
ArrayList<String> completeOrderArray = null;
ArrayList<String> payeeKeyArray = null;
ArrayList<String> productIdArray = null;
ArrayList<String> orderProductIdArray = null;
String shipCity, shipCountry, shipoAddress, shipTime;

@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_cart_place_order);

// FINDINLG IDS...!!
qty = (EditText) findViewById(R.id.et_qty);
price = (EditText) findViewById(R.id.et_price);
rl_adress = (RelativeLayout) findViewById(R.id.btn_adress);
product_name = (TextView) findViewById(R.id.tv_product_name);
tv_adress = (TextView) findViewById(R.id.tv_adress);
tv_select_adres = (TextView) findViewById(R.id.tv_select_adress);
tv_total = (TextView) findViewById(R.id.tv_total);
tv_subtotal = (TextView) findViewById(R.id.tv_subtotal);
back = (ImageView) findViewById(R.id.iv_back);
confirm = (Button) findViewById(R.id.btn_confirm);

yes = (RadioButton) findViewById(R.id.yes);
no = (RadioButton) findViewById(R.id.no);
productList = new ArrayList<HashMap<String, String>>();
cart_list = (ListView) findViewById(R.id.cart_list);
cartList = new ArrayList<HashMap<String, String>>();
completeOrderArray = new ArrayList<String>();
productIdArray = new ArrayList<String>();
orderProductIdArray = new ArrayList<String>();
payeeKeyArray = new ArrayList<String>();
new GetCartList().execute();

// SELECT ADDRESS CLICK EVENT..!
rl_adress.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {

i = new Intent(CartPlaceOrderActivity.this, AddressListActivity.class);
startActivityForResult(i, 1);
}
});

back.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
confirm.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
if (!tv_adress.getText().toString().equals("") && tv_adress.getText().toString() != null) {

new GetPlaceOrder().execute();
System.out.println("::::::::::::PLACE ORDER API CALLED::::::::::");

}

else {
Utils.showCustomeAlertValidation(CartPlaceOrderActivity.this, "Please select adress", "Yehki", "Ok");
}
}

});

}

// GETTING ADDRESS VALUES FROM ADDESSlIST ACTIVITY...
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent i) {

if (resultCode == 2 && requestCode == 1) {
add_id = i.getStringExtra(Const.TAG_ADDRESS_SHIPPING_ID);
Pref.setValue(CartPlaceOrderActivity.this, Const.PREF_ADRESS_ID, add_id);
i.getStringExtra(Const.TAG_ADDRESS_BUYER);
Pref.setValue(CartPlaceOrderActivity.this, Const.PREF_ADDRESS_BUYER, i.getStringExtra(Const.TAG_ADDRESS_BUYER));
shipCity = i.getStringExtra(Const.TAG_ADDRESS_CITY);
shipoAddress = i.getStringExtra(Const.TAG_ADDRESS_STATE);
shipCountry = i.getStringExtra(Const.TAG_ADRESS_COUNTRY);
shipTime = i.getStringExtra(Const.TAG_SHIP_TIME);
i.getStringExtra(Const.TAG_ADDRESS_TELEPHONE);
i.getStringExtra(Const.TAG_ADDRESS_FAX);

try {
if (!i.getStringExtra(Const.TAG_ADDRESS_BUYER).equals("") && i.getStringExtra(Const.TAG_ADDRESS_BUYER) != null) {
tv_adress.setVisibility(View.VISIBLE);
tv_adress.setText(i.getStringExtra(Const.TAG_ADDRESS_BUYER) + "\n" + i.getStringExtra(Const.TAG_ADDRESS_CITY) + "\n" + i.getStringExtra(Const.TAG_ADDRESS_STATE) + "\n"
+ i.getStringExtra(Const.TAG_ADRESS_COUNTRY) + "\n" + i.getStringExtra(Const.TAG_ADDRESS_TELEPHONE) + "\n" + i.getStringExtra(Const.TAG_ADDRESS_FAX) + "");
tv_select_adres.setVisibility(View.GONE);
System.out.println(":::::::::::::::::::VALUES::::::::::::::::::" + i.getStringExtra(Const.TAG_ADDRESS_BUYER));
} else {
tv_adress.setVisibility(View.GONE);
tv_select_adres.setVisibility(View.VISIBLE);

}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

// GETTING ORDER ID AND PALCE ORDER CONFIRAMATION CALL.....FOR WEBvIEW OR
// WHAT...........!!!
private class GetPlaceOrder extends AsyncTask<Void, Void, Void> {

@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog

pDialog = new ProgressDialog(CartPlaceOrderActivity.this);
pDialog.setCancelable(false);
pDialog.show();
System.out.println("==========inside preexecute===================");

/*
* FUNCTION FOR MAKING REQUEST URL...!!!
*/

}

void prepareURL() {
Uri.Builder builder = new Uri.Builder();
builder.scheme("http").authority("yehki.epagestore.in").appendPath("app_api").appendPath("order.php")
.appendQueryParameter("customer_id", Pref.getValue(CartPlaceOrderActivity.this, Const.PREF_CUSTOMER_ID, "")).appendQueryParameter("address_id", add_id);

for (int i = 0; i < carts.length(); i++) {
builder.appendQueryParameter("products[" + i + "][productName]", cartProduct.get(Const.TAG_PRODUCT_NAME));
builder.appendQueryParameter("products[" + i + "][productId]", cartList.get(i).get(Const.TAG_PRODUCT_ID));

// and so on...
}

String myUrl = builder.build().toString();
System.out.println("::::::::::::::::URL PRODUCT NAMER::::::::::::::" + myUrl);
}

void makeURL() {
StringBuilder sb = new StringBuilder();
String query = "http://yehki.epagestore.in/app_api/order.php?customer_id=" + Pref.getValue(CartPlaceOrderActivity.this, Const.PREF_CUSTOMER_ID, "") + "&address_id=" + add_id;
sb.append(query);

for (int i = 0; i < carts.length(); i++) {
sb.append(("&products[" + i + "][productName]=" + cartList.get(i).get((Const.TAG_PRODUCT_NAME))));
sb.append(("&products[" + i + "][product_id]=" + cartList.get(i).get((Const.TAG_PRODUCT_ID))));
sb.append(("&products[" + i + "][quantity]=" + cartList.get(i).get((Const.TAG_QUANTITY))));

sb.append(("&products[" + i + "][unit]=" + cartList.get(i).get((Const.TAG_UNIT))));
sb.append(("&products[" + i + "][unitPrice]=" + cartList.get(i).get((Const.TAG_RETAIL_PRICE))));
}

myUrl = sb.toString();
myUrl = Uri.encode(myUrl);
System.out.println("::::::::::::::::URL PRODUCT NAMER::::::::::::::" + myUrl);

}

@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
BackendAPIService sh = new BackendAPIService();

makeURL();

System.out.println("::::::::::::::::My place order url:::::::::::" + myUrl);

// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(myUrl, BackendAPIService.POST);

Log.d("Response: ", "> " + jsonStr);
System.out.println("=============MY RESPONSE FOR PLACEORDER>>==========" + jsonStr);

if (jsonStr != null) {
try {

JSONObject jsonObj = new JSONObject(jsonStr);

order_id = jsonObj.getString(Const.TAG_ORDER_ID);
Pref.setValue(CartPlaceOrderActivity.this, Const.PREF_ORDER_ID, order_id);
System.out.println("::::::::::::::::::MY order ID::::::::::::::::;++++++++++++++>>>>>>>>>>> " + order_id);

// FOR ORDER COMPLETION TIME....!!!
if (jsonObj.has(Const.TAG_COMPLETE_ORDER_TIME)) {
jArryCompleteOrder = jsonObj.getJSONArray(Const.TAG_COMPLETE_ORDER_TIME);
if (jArryCompleteOrder != null && jArryCompleteOrder.length() != 0) {
for (int i = 0; i < jArryCompleteOrder.length(); i++) {
jArryCompleteOrder.getString(i);
System.out.println("::::::::::::::COMPLETETION ORDER TI,E INSIDE JSON>>>>>>>>>" + jArryCompleteOrder.getString(i));

completeOrderArray.add(jArryCompleteOrder.getString(i));
}
}
}

// FOR PAYEE KEY...!!!
if (jsonObj.has(Const.TAG_PAYEE_KEY)) {
jArryPayeeKey = jsonObj.getJSONArray(Const.TAG_PAYEE_KEY);
if (jArryPayeeKey != null && jArryPayeeKey.length() != 0) {
for (int i = 0; i < jArryPayeeKey.length(); i++) {
jArryPayeeKey.getString(i);
System.out.println("::::::::::::::PAYEE KEY INSIDE JSON>>>>>>>>>" + jArryPayeeKey.getString(i));

payeeKeyArray.add(jArryPayeeKey.getString(i));
}
}
}

// FOR PRODUCT IDS......!!!
if (jsonObj.has(Const.TAG_PRODUCT_ID)) {
jArryProductId = jsonObj.getJSONArray(Const.TAG_PRODUCT_ID);
if (jArryProductId != null && jArryProductId.length() != 0) {
for (int i = 0; i < jArryProductId.length(); i++) {
String pro_id = jArryProductId.getString(i);
System.out.println("::::::::::::::PRTODUCT ID INSIDE JSON>>>>>>>>>" + jArryProductId.getString(i));

productIdArray.add(jArryProductId.getString(i));
System.out.println(":::::MY length::::::" + productIdArray.size());
}
}

// FOR ORDER PRODUCT IDS......!!!
if (jsonObj.has(Const.TAG_ORDER_PRODUCT_ID)) {
jArryOrderProId = jsonObj.getJSONArray(Const.TAG_ORDER_PRODUCT_ID);
if (jArryOrderProId != null && jArryOrderProId.length() != 0) {
for (int i = 0; i < jArryOrderProId.length(); i++) {
jArryOrderProId.getString(i);
System.out.println("::::::::::::::ORDER PRODUCT KEY INSIDE JSON>>>>>>>>>" + jArryOrderProId.getString(i));

orderProductIdArray.add(jArryCompleteOrder.getString(i));
System.out.println(":::::MY length::::::" + orderProductIdArray.size());
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");

}
return null;
}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);

// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
// String webView = "";

i = new Intent(CartPlaceOrderActivity.this, PaymentOptionActivity.class);
i.putExtra(Const.TAG_ORDER_ID, order_id);
startActivity(i);
finish();

}
}

// GET CART lIST PRODUCT PLACE ORDER.........!!!
private class GetCartList extends AsyncTask<Void, Void, Void> {

@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CartPlaceOrderActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();

}

@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
String cartUrl = Const.API_CART_LIST + "?customer_id=" + Pref.getValue(CartPlaceOrderActivity.this, Const.PREF_CUSTOMER_ID, "");
BackendAPIService sh = new BackendAPIService();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(cartUrl, BackendAPIService.GET);

Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {

jsonObj = new JSONObject(jsonStr);
total = jsonObj.getString(Const.TAG_TOTAL);

// Getting JSON Array node
if (jsonObj.has(Const.TAG_PRO_LIST)) {

carts = jsonObj.getJSONArray(Const.TAG_PRO_LIST);
if (carts != null && carts.length() != 0) {
// looping through All Contacts

for (int i = 0; i < carts.length(); i++) {
JSONObject c = carts.getJSONObject(i);

String proId = c.getString(Const.TAG_PRODUCT_ID);
String proName = c.getString(Const.TAG_PRODUCT_NAME);
String wPrice = c.getString(Const.TAG_WHOLESALE_PRICE);
String rPrice = c.getString(Const.TAG_RETAIL_PRICE);
String qty = c.getString(Const.TAG_QUANTITY);
String subTotal = c.getString(Const.TAG_SUBTOTAL);
String unit_id = c.getString("unit_id");

String proimg = Const.API_HOST + "/" + c.getString(Const.TAG_PRODUCT_IMG);
cartProduct = new HashMap<String, String>();

cartProduct.put(Const.TAG_PRODUCT_ID, proId);
cartProduct.put(Const.TAG_PRODUCT_NAME, proName);
cartProduct.put(Const.TAG_PRODUCT_IMG, proimg);
cartProduct.put(Const.TAG_WHOLESALE_PRICE, wPrice);
cartProduct.put(Const.TAG_RETAIL_PRICE, rPrice);
cartProduct.put(Const.TAG_QUANTITY, qty);
cartProduct.put(Const.TAG_SUBTOTAL, subTotal);
cartProduct.put(Const.TAG_TOTAL, total);
cartProduct.put(Const.TAG_UNIT, unit_id);
cartList.add(cartProduct);

}
}
}

} 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();

cartContent = new CartAdapter(CartPlaceOrderActivity.this, cartList);
cart_list.setAdapter(cartContent);
tv_total.setText("Total:" + total);

}

}

}

最佳答案

确保您是否使用像在循环之前初始化它那样的构建器帮助程序类。

也就是说,UriBuilder是您问题的完美解决方案,它是用于构建或操作 url 的辅助类。

下面是一个例子:

Uri.Builder builder = new Uri.Builder();
builder.scheme("http")
.authority("yehki.epagestore.in")
.appendPath("app_api")
.appendPath("order.php")
.appendQueryParameter("customer_id", customer_id)
.appendQueryParameter("address_id", address_id);

for (int i = 0; i < carts.length(); i++) {
builder.appendQueryParameter("products["+i+"][productName]", cartList.get(i).get((Const.TAG_PRODUCT_NAME)));
builder.appendQueryParameter("products["+i+"][productId]", cartList.get(i).get((Const.TAG_PRODUCT_ID)));
builder.appendQueryParameter("products["+i+"][quantity]", cartList.get(i).get((Const.TAG_QUANTITY)));
builder.appendQueryParameter("products["+i+"][unit]", cartList.get(i).get((Const.TAG_UNIT)));
builder.appendQueryParameter("products["+i+"][unitPrice]", cartList.get(i).get((Const.TAG_RETAIL_PRICE)));

}

String myUrl = builder.build().toString();

关于java - 如何通过动态使用android中的方法建立一个字符串url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23403949/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com