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.
Related
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 tried more and more and nothing is worked.Last i used sharedPreferences.but that not relevant to me...Please help me to replace the sharedPreferences..
my MainActivity is
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.CancellationSignal;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
TextView textView,textView2;
String[] name=new String[100];
String[] id=new String[100];
String[] names=null;
String[] idg=new String[100];
String[] ids=null;
int i;
int len;
ArrayList<NewsItem> listData;
int size;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Fetch().execute();
SharedPreferences sharedPreferences = getSharedPreferences("local", 0);
SharedPreferences.Editor editor=sharedPreferences.edit();
size = sharedPreferences.getInt("array_size", 0);
ids = new String[size];
names = new String[size];
for(i=0; i<size; i++){
ids[i]=sharedPreferences.getString("array1_" + i, null);
names[i]=sharedPreferences.getString("array2_" + i, null);
}
editor.clear();
editor.commit();
listData = getListData();
final ListView listView = (ListView) findViewById(R.id.custom_list);
listView.setAdapter(new CustomListAdapter(this, listData));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
NewsItem newsData = (NewsItem) listView.getItemAtPosition(position);
Toast.makeText(MainActivity.this, "Selected :" + " " + newsData, Toast.LENGTH_LONG).show();
}
});
//textView=(TextView)findViewById(R.id.textView);
//textView2=(TextView)findViewById(R.id.textView2);
}
class Fetch extends AsyncTask<String,String,Void>{
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream is = null ;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Fetching data...");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialogInterface) {
dialogInterface.cancel();
}
});
}
#Override
protected Void doInBackground(String... params) {
String url_select = "http://andrinfo.comli.com/rimgid.php";
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_SHORT).show();
}
});
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
//read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
}
is.close();
result=sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
// ambil data dari Json database
try {
JSONArray Jarray = new JSONArray(result);
len = Jarray.length();
for(i=0;i<Jarray.length();i++)
{
JSONObject Jasonobject = null;
Jasonobject = Jarray.getJSONObject(i);
//get an output on the screen
id[i] ="http://developer.andrinfo.comli.com/img/"+ Jasonobject.getInt("id")+".jpg";
name[i] = Jasonobject.getString("name");
SharedPreferences sharedPreferences=getSharedPreferences("local",0);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putInt("array_size", len);
for(int i=0;i<len; i++) {
editor.putString("array1_" + i, id[i]);
editor.putString("array2_" + i, name[i]);
}
editor.apply();
drac d=new drac();
//d.exe(id,name,len);
}
this.progressDialog.dismiss();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
private ArrayList<NewsItem> getListData() {
ArrayList<NewsItem> listMockData = new ArrayList<NewsItem>();
String[] images = getResources().getStringArray(R.array.images_array);
String[] headlines = getResources().getStringArray(R.array.headline_array);
for (i = 0; i < size; i++) {
NewsItem newsData = new NewsItem();
newsData.setUrl(ids[i]);
newsData.setHeadline(names[i]);
newsData.setReporterName("Price");
newsData.setDate("May 26, 2015, 1:35PM");
listMockData.add(newsData);
}
return listMockData;
}
class drac{
public void exe(String[] ids, String[] idg,int size)
{
for (i = 0; i < size; i++) {
Toast.makeText(getApplicationContext(), ""+ids[i], Toast.LENGTH_SHORT).show();
}}}
}
And the PROBLEM IS IN MainActivity.java
See http://developer.android.com/intl/es/reference/android/os/AsyncTask.html. Especially the part with the result.
onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
Finally I solved by using volley library thanks for the response.
below is my mainactivity java code
i have a json file which returns the foll values
[{"COMPONENT":"xxxx","FLAG":"T","SAMPLINGPOINT":"dddd"},{"COMPONENT":"yyyyy","FLAG":"F","SAMPLINGPOINT":"ggggg"},{"COMPONENT":"xxxx","FLAG":"F","SAMPLINGPOINT":"dddd"},{"COMPONENT":"xxxx","FLAG":"T","SAMPLINGPOINT":"dddd"}]
On display if the json value FLAG:T then the listview color should be red else if FLAG:F then green...any help??
package com.webservice1;
import android.app.Activity;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ListView;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.view.View;
import org.json.JSONArray;
import org.json.JSONObject;
//import org.json.JSONArray;
import org.json.JSONException;
//import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
public class MainActivity extends Activity {
String TAG = "Response";
TextView responseText;
Button bt;
EditText celcius;
String getCel;
SoapPrimitive resultString;
String color, item;
String str = "<font color=\"%s\">%s</font>";
//private static final String name = "ID_NUMERIC";
// private static final String test = "TEST";
private static final String component = "COMPONENT";
// private static final String units = "UNITS";
private static final String value = "VALUE";
private static final String flag = "FLAG";
//private static final String color = "color";
//private static final String samplingpoint = "SAMPLINGPOINT";
JSONArray Response = null;
String jsonObject_string ;
String jArray;
ListView list;
TextView vers;
TextView name;
TextView flg;
TextView api;
ListAdapter adapter;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
public void calculate() {
String SOAP_ACTION = "";
String METHOD_NAME = "";
String NAMESPACE = "";
String URL = "";
try {
SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
Request.addProperty("SmapleID", getCel);
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapEnvelope.dotNet = true;
soapEnvelope.setOutputSoapObject(Request);
HttpTransportSE transport = new HttpTransportSE(URL);
transport.call(SOAP_ACTION, soapEnvelope);
resultString = (SoapPrimitive) soapEnvelope.getResponse();
//Log.i(TAG, "Result SmapleID: " + resultString);
} catch (Exception ex) {
Log.e(TAG, "Error: " + ex.getMessage());
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ListView list = (ListView) findViewById(R.id.list);
responseText = (TextView) findViewById(R.id.responseText);
bt = (Button) findViewById(R.id.bt);
celcius = (EditText) findViewById(R.id.cel);
list = (ListView) findViewById(R.id.list);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getCel = celcius.getText().toString();
AsyncCallWS task = new AsyncCallWS();
task.execute();
}
});
}
private class AsyncCallWS extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
}
#Override
protected String doInBackground(String... params) {
Log.i(TAG, "doInBackground");
calculate();
return null;
}
#Override
protected void onPostExecute(String result) {
//calculate();
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,R.layout.list_child,new String[] {component, value, flag, color }, new int[] {R.id.name, R.id.vers, R.id.flg});
list.setAdapter(adapter);
oslist.clear();
// Making a request to url and getting response
String data = "";
String data1 = "";
String data2 = "";
String data3 = "";
String data4 = "";
String data5 = "";
String jsonStr = resultString.toString();
//Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try
{
JSONArray jArray = new JSONArray(jsonStr);
for(int i=0;i<jArray.length();i++){
JSONObject json_obj = jArray.getJSONObject(i);
// String name = json_obj.getString("ID_NUMERIC");
// String test = json_obj.getString(" TEST");
String component = json_obj.getString("COMPONENT");
//String units = json_obj.getString("UNITS");
String value = json_obj.getString("VALUE");
String flag = json_obj.getString("FLAG");
if ("F".equalsIgnoreCase(flag));{
color = "red";
}
//data = name;
// data1 = test + ", ";
data2 = component;
// data3 = units;
data4 = value;
data = flag;
HashMap<String, String> map = new HashMap<String, String>();
map.put("COMPONENT", data2);
map.put("VALUE", data4);
map.put("FLAG", data);
oslist.add(map);
}
}catch (JSONException e) {
// handle exception
}
}
// return null;
}
}}
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
Hi (fresher to andorid)
I'm developing an android application which will use the webservice which should accept 1 parameter from the user and based on that the value is fetched datas from DB(sql server 2008) and bind that to android:LISTVIEW.
Without using the parameter my android application is working fine.But when i altered my webserservice to accept parameter and call it in android it is not displaying the result based on the given value instead of that it displays all values.
Here is my webservice code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class JService : System.Web.Services.WebService
{
public JService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public void Cargonet(string jobno)
{
try
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSConstr"].ToString());
SqlCommand cmd = new SqlCommand();
//cmd.CommandText = "SELECT id,name,salary,country,city FROM EMaster where age = '" + jobno + "'";
cmd.CommandText = "SELECT [Id] as Id,[Status] as status ,[DateTime] as DateTime FROM [Attendance].[dbo].[cargo] WHERE JobNo= '" + jobno + "' ";
DataSet ds = new DataSet();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand.Connection = con;
da.Fill(dt);
con.Close();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataRow rs in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, rs[col].ToString().Trim());
}
rows.Add(row);
}
this.Context.Response.ContentType = "application/json; charset=utf-8";
this.Context.Response.Write(serializer.Serialize(new { Cargo = rows }));
}
catch (Exception ex)
{
//return errmsg(ex);
}
}
}
Here is my android code(Main.java):
package com.example.cargotracking;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
ListView list;
TextView Id;
TextView Status;
TextView DateTime;
Button Btngetdata;
String JobNo;
EditText editText1;
ArrayList<HashMap<String, String>> CargoTracklist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://ip/testing/TrackId.asmx/Cargonet";
//JSON Node Names
private static final String TAG_CargoTrack = "Cargo";
private static final String TAG_Id = "Id";
private static final String TAG_Status = "Status";
private static final String TAG_DateTime = "DateTime";
JSONArray Cargo = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CargoTracklist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.button1);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
Status = (TextView)findViewById(R.id.textView2);
Id= (TextView)findViewById(R.id.textView1);
DateTime = (TextView)findViewById(R.id.textView3);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
// List params = new ArrayList();
params.add(new BasicNameValuePair("JobNo","01"));
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url,params);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
Cargo = json.getJSONArray(TAG_CargoTrack);
for(int i = 0; i < Cargo.length(); i++){
JSONObject c = Cargo.getJSONObject(i);
// Storing JSON item in a Variable
String Status = c.getString(TAG_Status);
String Id = c.getString(TAG_Id);
String DateTime = c.getString(TAG_DateTime);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_Status, Status);
map.put(TAG_Id, Id);
map.put(TAG_DateTime, DateTime);
CargoTracklist.add(map);
list=(ListView)findViewById(R.id.listView1);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, CargoTracklist,
R.layout.listview,
new String[] { TAG_Status,TAG_Id, TAG_DateTime }, new int[] {
R.id.textView2,R.id.textView1, R.id.textView3});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+CargoTracklist.get(+position).get("Id"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Here is my json parser code:
package com.example.cargotracking;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
//public JSONObject getJSONFromUrl(String url, List params) {
public JSONObject getJSONFromUrl(String url, List<BasicNameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
please help me to resolve this.
Thanks in advance