I am trying to make an English Dictionary using the Oxford API. I made this according to docs and resources found on the web. But I got this issue "org.json.JSONException: No value for senses" and I don't why. Wherever I looked I couldn't find reason of this issue. I'll give you my MainActivity and request class. Can anyone help me?
MainActiviy:
package com.alitalhacoban.english_dictionary;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
TextView textView;
EditText editText;
private String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
editText = findViewById(R.id.editText);
url = dictionaryEntries();
}
public void find(View view){
MyDictionaryRequest myDictionaryRequest = new MyDictionaryRequest(this);
myDictionaryRequest.execute(url);
}
private String dictionaryEntries() {
final String language = "en-gb";
final String word = "Ace";
final String fields = "pronunciations";
final String strictMatch = "false";
final String word_id = word.toLowerCase();
return "https://od-api.oxforddictionaries.com:443/api/v2/entries/" + language + "/" + word_id + "?" + "fields=" + fields + "&strictMatch=" + strictMatch;
}
}
Request class:
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class MyDictionaryRequest extends AsyncTask<String, Integer, String> {
Context context;
MyDictionaryRequest(Context context) {
this.context = context;
}
final String app_id = "127ae33f";
final String app_key = "e42c0fccfe30223fb9ec02e12ae8c8a9";
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestProperty("app_id", app_id);
urlConnection.setRequestProperty("app_key", app_key);
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
return stringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
String def = "";
try {
JSONObject js = new JSONObject(result);
JSONArray results = js.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject lentries = results.getJSONObject(i);
JSONArray la = lentries.getJSONArray("lexicalEntries");
for (int j = 0; j < la.length(); j++) {
JSONObject entries = la.getJSONObject(j);
JSONArray e = entries.getJSONArray("entries");
for (int k = 0; k < e.length(); k++) {
JSONObject senses = e.getJSONObject(k);
JSONArray s = senses.getJSONArray("senses");
JSONObject d = e.getJSONObject(0);
JSONArray de = d.getJSONArray("definitions");
def = de.getString(0);
}
}
}
Log.e("def", def);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
try to validate the "senses" with senses.has("senses") before use it and then parse it with optjsonarray or optjsonobject for this type and check this key or check at backend side from where what value getting in json response.
I'm trying to pass the matchday to the URL for the Http connection. I know I can't get a value from the EditText in the doInBackground method so I thought to get the value in the onPreExecute method. Of I then add the variable to the URL, the program doesn't recognise the String. I saw on StackOverflow you need to add the parameters in the execute method but I don't really have got that part of the explanation.
Does anyone have an idea how to add the matchday to the URL, entered in the EditText matchdayText?
Thanks in advance!
Rob Nickmans
CODE:
package ga.rndevelopment.footballpronostics;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
EditText matchdayText;
TextView responseView;
ProgressBar progressBar;
static final String API_KEY = "HIDDEN";
static final String API_URL = "http://api.football-data.org/v2/competitions/PL/matches/?matchday=";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
responseView = findViewById(R.id.responseView);
matchdayText = findViewById(R.id.matchdayText);
progressBar = findViewById(R.id.progressBar);
Button queryButton = findViewById(R.id.queryButton);
queryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new FetchData().execute();
}
});
}
class FetchData extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
responseView.setText("");
String matchDay = matchdayText.getText().toString();
String apiUrl = API_URL + matchDay;
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(apiUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.addRequestProperty("X-Auth-Token", API_KEY);
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
} finally {
urlConnection.disconnect();
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
#Override
protected void onPostExecute(String response) {
if (response == null) {
response = "THERE WAS AN ERROR";
}
progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
}
}
}
First Create the connection using URL Connection.There by create
buffer writer and pass the all requested data in one single String
buffer variable there by it will take to concern URL and along with
Requested parameter and its values. Please go Through this Below
sample Example
URL url = new URL("give your URL ");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
final StringBuilder reqstData = new StringBuilder(100);
reqstData.append("&userId=").append(userId);
reqstData.append("&roleId=").append(roleId);
reqstData.append("&userName=").append(userName);
out.write(reqstData);
out.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
I am having a problem.
I can't figure out why the following code won't work.
It's a simple app that sends a GET request to some php fragment that supposed to insert a row in a table.
I can't understand why it doesn't work.
Please help.
java:
package com.example.michael.biyum;
import android.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
final AlertDialog alertDialog = alertDialogBuilder.create();
Button startBtn = (Button) findViewById(R.id.btn);
final TextView t = (TextView) findViewById(R.id.hello);
startBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://www.chatty.co.il/biyum.php?q=mkyong");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
Toast.makeText(getApplicationContext(),"GET:"+current,Toast.LENGTH_LONG).show();
System.out.print(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
});
}
}
php:
<?php
require('connect.inc.php');
$update_offline="INSERT INTO offline_waiters (user_partner,mail,chat_room) VALUES(0,'gavno','gavno')";
$query_run= mysqli_query($conn,$update_offline);
echo "new";
?>
It's a simple test that should enter a new row in my table.
When I make the request manualy via a browser it works fine.
Once again please help me understand where is the problem.
You need to get the network operation off of the main thread.
I just got this working and tested using an AsyncTask:
class MyAsyncTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
StringBuilder result = new StringBuilder();
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://www.chatty.co.il/biyum.php?q=mkyong");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
result.append(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return result.toString();
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(),"GET:"+result,Toast.LENGTH_LONG).show();
}
}
Just execute the AsyncTask from your click listener:
startBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
new MyAsyncTask().execute();
});
Result in the Toast:
This is what I essentially want to do, but can't. I want the value of urlData and size to be updated from the inner class functions. The app is crashing by giving a Null Pointer Exception at the line where I try to access these variables from the CreateTextView() function.
package edu.ahduni.seas.gyapak;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import org.json.JSONException;
import org.json.JSONArray;
import org.json.JSONObject;
import android.util.Log;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public ArrayList<Data> urlData; //Culprit 1
public int size; //no. of dirs + files, Culprit 2
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void parseJSON() throws JSONException {
ParseActivity parse = new ParseActivity();
String url = "RDovQWNhZGVtaWMvU2FuamF5IENoYXVkaGFyeQ==";
parse.execute(url);
CreateTextView();
Log.e("RETURNING JSON","RETURNING");
}
public void CreateTextView() {
TextView text = (TextView) findViewById(R.id.text);
text.setText(Integer.toString(size));
Button myButton = new Button(this);
if(urlData==null) //workaround for crash
return;
myButton.setText(urlData.get(0).getName());
LinearLayout ll = (LinearLayout)findViewById(R.id.textlayout);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
}
class ParseActivity extends AsyncTask<String, Void, ArrayList<Data>> {
InputStream is = null;
JSONArray jObj = null;
String json = "";
#Override
public void onPostExecute(ArrayList<Data> data) {
size = data.size(); //here!
}
#Override
protected ArrayList<Data> doInBackground(String... params) {
final String BASE_URL = "http://111.93.66.162/json/main.php?f=" + params[0];
HttpURLConnection urlConnection;
// Making HTTP request
try {
Log.e("OPENING: ", "URL");
URL url = new URL(BASE_URL);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
is = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (is == null) {
// Nothing to do.
return null;
}
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = in.readLine()) != null) {
buffer.append(line + "\n");
Log.e("JSON: ", line);
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
is.close();
json = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
try {
return getData(json);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public ArrayList<Data> getData(String jsonString) throws JSONException {
// try parse the string to a JSON object
final String EXT = "ext";
final String PATH = "path";
final String NAME = "name";
try {
jObj = new JSONArray(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
urlData = new ArrayList<Data>();
for (int i=0;i<jObj.length();i++) {
JSONObject obj = jObj.getJSONObject(i);
String ext = obj.getString(EXT);
String path = obj.getString(PATH);
String name = obj.getString(NAME);
urlData.add(new Data(ext,path,name)); //and here!
}
return urlData;
}
}
}
The inner class is not static, so it needs an instance of the enclosing class to be instantiated. Like so:
public class abcd {
static int x;
public static void main(String[] args) {
abcd o = new abcd(); // Create instance of abcd called 'o'
abcd.efgh o2 = o.new efgh(); // Use instance 'o' to create an instance of efgh
System.out.println(x); // 0
o2.ok();
System.out.println(x); // 5
}
class efgh {
public void ok() {
x = 5;
}
}
}
I have made one activity. In that I have to use one asynctask for api. So in that asynctask my url will be dynamically generated based on some number. I have tried as below, but it's not the proper way. Can anybody show me how I can make this url?
my sample url is: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
my try is:
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);
}
}
}
Make sure if you use a builder helper class like that you initialize it before the loop.
That said, UriBuilder is a perfect solution for your problem, it's a helper class for building or manipulating url's.
Below is an example for you:
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();
You can use Spring Android Rest Template
http://projects.spring.io/spring-android/
You can create a class with your request representation and if it is a post request you can send it as below.
/* user Registration screen */
public UserAccount registerUser(UserAccount user) {
final String url = Util.BASE_URL + "/user/register";
RestTemplate restTemplate = new RestTemplate();
restTemplate
.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
restTemplate.getMessageConverters().add(
new MappingJackson2HttpMessageConverter());
ResponseEntity<UserAccount> responseEntity = restTemplate.exchange(url,
HttpMethod.POST, new HttpEntity<UserAccount>(user,
jsonReqAndResHeaders()), UserAccount.class);
return responseEntity.getBody();
}
The above shown is the code we use to register a User. Created a UserAccount class populated it with data and sent it to the server using a POST request.
This is similar to your scenario, you can create an Order class populate all the data and just hit the server url as shown above.
If you should use a GET request and prepare a URL, but for long urls like yours its always best to go with POST.
Hope this helps. Thanks