In my android i have got a response from Json but i want to get that Json value in Integer variable in android.In Jsonarray a i have got my value.So please help me for this. I have return that integer value in "MenuNameFromAndroid" function.
protected class AsyncMenuname extends
AsyncTask<MenunameSendFrom, JSONObject, JSONObject> {
JSONObject jsonObj = null;
#Override
protected JSONObject doInBackground(MenunameSendFrom... params) {
RestAPI api = new RestAPI();
try {
jsonObj = api.MenuNameFromAndroid(params[0].getMenuname());
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncCreateUser", e.getMessage());
}
return jsonObj;
}
#Override
protected void onPostExecute(JSONObject objects) {
try {
//JSONArray jsonArray = objects.getJSONArray("Value");
String string = null;
JSONArray a = objects.getJSONArray("Value");
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(TwoList.this, "Successfully inserted...", Toast.LENGTH_LONG).show();
}
}
In this function i have got a response of JSON object
public JSONObject MenuNameFromAndroid(String getMenuname) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface","RestAPI");
o.put("method", "MenuNameFromAndroid");
p.put("getMenuname",mapObject(getMenuname));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
And This is function that I have return float value. That float value i want to get in android
float menuId = 0;
public float MenuNameFromAndroid(string getMenuname)
{
if (dbConnection.State.ToString() == "Closed")
{
dbConnection.Open();
}
menuId = db.getDb_Value("select menu_id From menu where m_name='" + getMenuname + "'");
dbConnection.Close();
return menuId;
}
Related
hello i am trying to use a POST method of volley to get a string something like this
{"Date":"01-04-2017","PartyName":"Customer3","Supplier":"Supplier2",
"Items":[{"ItemNo":0,"ItemName":"a","Quantity":100,"DueDate":"01-04-
2017","Price":80,"Amount":80000}]}
here is my code:
JSONObject singleorder= new JSONObject();
try {
singleorder.put("Date",Get_date);
singleorder.put("PartyName",Get_partyname);
singleorder.put("Supplier", Get_supplier);
JSONArray arr = singleorder.getJSONArray("Items");
for(int i=0;i<arr.length();i++){
JSONObject obj = arr.getJSONObject(i);
//obj.put("ItemNo",Get_itemno);
obj.put("ItemName",Get_itemname);
obj.put("Quantity",Get_quantity);
obj.put("Price",Get_price);
obj.put("Amount",Get_amount);
}
//JSONArray item = new JSONArray("Items");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
when i run my code it, doesnt take the Array "item". it gives me the error:
org.sjon.JSONException:No value for Items.
where i am doing wrong?
JSONObject singleorder= new JSONObject();
try {
singleorder.put("Date",Get_date);
singleorder.put("PartyName",Get_partyname);
singleorder.put("Supplier", Get_supplier);
int loopSize = Get_No_items(); //Or just initialize it as 1 in your particular case
JSONArray arr = new JSONArray();
for(int i=0;i<loopSize;i++){
JSONObject obj = new JSONObject();
//obj.put("ItemNo",Get_itemno);
obj.put("ItemName",Get_itemname);
obj.put("Quantity",Get_quantity);
obj.put("Price",Get_price);
obj.put("Amount",Get_amount);
arr.put(obj);
}
singleorder.put("Items", arr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Do something like this, it will be more error-free
class A implements Serializable{
private String name;
private B addresses[];
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public B[] getAddresses() {
return addresses;
}
public void setAddresses(B[] addresses) {
this.addresses = addresses;
}}
class B implements Serializable{
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
And finally
{A a = new A();
a.setName("abc");
B addresses[] = new B[1];
addresses[0] = new B();
addresses[0].setAddress("xyz");
a.setAddresses(addresses);
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(a);}
and it will produce JSON string like
{"name":"zafa","addresses":[{"address":"xyz"}]}
You can create json array like this
private JSONArray getJsonArray(ArrayList<Object> array) {
JSONArray jsonArray = new JSONArray();
if (array != null && array.size() > 0) {
for (int i = 0; i < array.size(); i++) {
JSONObject jsonObject = new JSONObject();
Object object = array.get(i);
try {
jsonObject.put(DESCRIPTION, object.getData());
jsonObject.put(IMAGE_URL, object.getAnotherData());
jsonArray.put(i, jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return jsonArray;
}
You have not added Items to singleorder.
You do it with a line like this:
singleorder.add(key, value);
Below is my Json response from getting when Hit on Url with parsing parameter strlogid=101
[
{
"earnpoints": 411,
"type": "C"
},
{
"earnpoints": 1600,
"type": "G"
},
{
"earnpoints": 13540,
"type": "I"
}
]
Below is my code-To show Points on 3 different textview
private class PointTask extends AsyncTask<String, Void, Boolean> {
protected Boolean doInBackground(final String... args) {
JSONParse jParser = new JSONParse();
HashMap<String, String> hMap = new HashMap<>();
hMap.put("strlogid", "101");
JSONArray jsonarray = jParser.getJSONFromUrl(url,hMap);
// get JSON data from URL
for (int i = 0; i < jsonarray.length(); i++) {
try {
JSONObject c = (JSONObject) jsonarray.get(i);
c_point=c.getString("points");
g_point=c.getString("points");
i_point=c.getString("points");
t_point = cpoint+gpoint+ipoint;
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(final Boolean success) {
txtTotalPoints.setText(t_point);
txtOwnPoints.setText(g_point);
txtClubPoints.setText(c_point);
txtVoucherPoints.setText(i_point);
}
}
TotalPoints,OwnPoints,ClubPoints,VoucherPoints are show on Textview respectively
Try this
protected Boolean doInBackground(final String... args) {
JSONParse jParser = new JSONParse();
HashMap<String, String> hMap = new HashMap<>();
hMap.put("strlogid", "101");
JSONArray jsonarray = jParser.getJSONFromUrl(url,hMap);
// get JSON data from URL
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject c = (JSONObject) jsonarray.get(i);
if (c.getString("type").toString().equalsIgnoreCase("C")) {
c_point = c.getInt("earnpoints");
} else if (c.getString("type").toString().equalsIgnoreCase("G")) {
g_point = c.getInt("earnpoints");
} else if (c.getString("type").toString().equalsIgnoreCase("I")) {
i_point = c.getInt("earnpoints");
}
}
t_point = cpoint + gpoint + ipoint;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final Boolean success) {
txtTotalPoints.setText(t_point);
txtOwnPoints.setText(g_point);
txtClubPoints.setText(c_point);
txtVoucherPoints.setText(i_point);
}
}
Dont use async task for json parsing. I would reccomend you to use volley.
Here is the link\
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
#Override
public void onPostSuccess(String result, int id, boolean isSucess) {
// Log.e("re<><><><>", result);
try {
JSONArray ja = new JSONArray(result);
for (int arr = 0; arr < ja.length(); arr++) {
JSONObject json1 = ja.getJSONObject(arr);
Log.e("length", "" + ja.length());
// Getting JSON Array node
String earnpoints= json1.getString("earnpoints");
String type = json1.getString("type");
}
catch (JSONException e) {
e.printStackTrace();
Toast.makeText(LoginPage.this, "Please try again later", Toast.LENGTH_SHORT).show();
}
}
The code below tested on LG G3 and it worked fine. However when I tested it on a Samsung Galaxy S3/S2 doInBackground() is not called for some reason.
Code to check api:
public void startBlat(String tosearch) {
AsynctaskMovie asynctaskMovie = new AsynctaskMovie();
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) {
asynctaskMovie.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,tosearch);
}
else {
asynctaskMovie.execute(tosearch);
}
The Asynctask code:
class AsynctaskMovie extends AsyncTask<String, String, ArrayList<Movie>> {
JSONParser jsonParser = new JSONParser();
private static final String SEARCH_URL = "http://www.omdbapi.com/?";
#Override
protected void onPreExecute() {
super.onPreExecute();
movieArrayList = new ArrayList();
Log.i(getActivity().getCallingPackage(), "onPreExecute");
}
#Override
protected ArrayList<Movie> doInBackground(String... args) {
Log.i(getActivity().getCallingPackage(),"doInBackground");
HashMap<String, String> params = new HashMap<>();
params.put("s", args[0]);
params.put("r", "json");
JSONObject json = jsonParser.makeHttpRequest(SEARCH_URL, "GET", params);
Log.i(getActivity().getCallingPackage(), json.toString());
if (json != null) {
try {
if (json.getString("Response").equals("False")) {
return movieArrayList;
}
} catch (JSONException e) {
}
try {
JSONArray jsonArray = json.getJSONArray("Search");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
String movieid = jsonObject.getString(App.getInstance().IMDBimdbID);
if (!movieid.equals("null")) {
Movie movie = new Movie(movieid);
movieArrayList.add(movie);
}
}
jsonArray = new JSONArray();
for (Movie movie : movieArrayList) {
params = new HashMap<>();
params.put("i", movie.getMovieid());
params.put("plot", "short");
params.put("r", "json");
JSONObject jsongetfullinfo = jsonParser.makeHttpRequest(SEARCH_URL, "GET", params);
if (jsongetfullinfo != null) {
jsonArray.put(jsongetfullinfo);
Log.i("", jsongetfullinfo.toString());
}
}
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jObject = jsonArray.getJSONObject(i);
movieArrayList.get(i).updateFromIMDB(jObject);
}
for (Movie movie : movieArrayList) {
movie.setMovieposter(LoadFromUrl(movie.getPosterURL()));
}
return movieArrayList;
} catch (JSONException e) {
e.printStackTrace();
}
}
return movieArrayList;
}
#Override
protected void onPostExecute(ArrayList<Movie> movieArrayList) {
Log.i("ronen", "list size: " + movieArrayList.size());
if (movieArrayList.size() > 0) {
listView.setAdapter(new MovieAdapter(getActivity(), movieArrayList));
listView.setVisibility(View.VISIBLE);
} else {
Toast.makeText(getActivity().getApplicationContext(), "No found", Toast.LENGTH_SHORT).show();
}
}
private Bitmap LoadFromUrl(String theurl) {
URL url = null;
Bitmap bmp = null;
try {
url = new URL(theurl);
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
}
return bmp;
}
}
I have no idea what could solve this problem.
Following the answers I read here it seems that the code should work, but not so.
Can't see anything suspicious.
I'd recommend running a very simple AsyncTask on a very simple app, make sure it works (if not, maybe it something to do with the phone, so try on an emulator to be sure)
Then change it step by step to resemble your code, and you'll see where the bug is.
G'Luck!
I am working on an Android application. In my app I have to convert a string to JSON Object, then parse the values. I checked for a solution in Stackoverflow and found similar issue here link
The solution is like this
`{"phonetype":"N95","cat":"WP"}`
JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
I use the same way in my code . My string is
{"ApiInfo":{"description":"userDetails","status":"success"},"userDetails":{"Name":"somename","userName":"value"},"pendingPushDetails":[]}
string mystring= mystring.replace("\"", "\\\"");
And after replace I got the result as this
{\"ApiInfo\":{\"description\":\"userDetails\",\"status\":\"success\"},\"userDetails\":{\"Name\":\"Sarath Babu\",\"userName\":\"sarath.babu.sarath babu\",\"Token\":\"ZIhvXsZlKCNL6Xj9OPIOOz3FlGta9g\",\"userId\":\"118\"},\"pendingPushDetails\":[]}
when I execute JSONObject jsonObj = new JSONObject(mybizData);
I am getting the below JSON exception
org.json.JSONException: Expected literal value at character 1 of
Please help me to solve my issue.
Remove the slashes:
String json = {"phonetype":"N95","cat":"WP"};
try {
JSONObject obj = new JSONObject(json);
Log.d("My App", obj.toString());
} catch (Throwable t) {
Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}
This method works
String json = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
try {
JSONObject obj = new JSONObject(json);
Log.d("My App", obj.toString());
Log.d("phonetype value ", obj.getString("phonetype"));
} catch (Throwable tx) {
Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}
try this:
String json = "{'phonetype':'N95','cat':'WP'}";
You just need the lines of code as below:
try {
String myjsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
JSONObject jsonObject = new JSONObject(myjsonString );
//displaying the JSONObject as a String
Log.d("JSONObject = ", jsonObject.toString());
//getting specific key values
Log.d("phonetype = ", jsonObject.getString("phonetype"));
Log.d("cat = ", jsonObject.getString("cat");
}catch (Exception ex) {
StringWriter stringWriter = new StringWriter();
ex.printStackTrace(new PrintWriter(stringWriter));
Log.e("exception ::: ", stringwriter.toString());
}
just try this ,
finally this works for me :
//delete backslashes ( \ ) :
data = data.replaceAll("[\\\\]{1}[\"]{1}","\"");
//delete first and last double quotation ( " ) :
data = data.substring(data.indexOf("{"),data.lastIndexOf("}")+1);
JSONObject json = new JSONObject(data);
To get a JSONObject or JSONArray from a String I've created this class:
public static class JSON {
public Object obj = null;
public boolean isJsonArray = false;
JSON(Object obj, boolean isJsonArray){
this.obj = obj;
this.isJsonArray = isJsonArray;
}
}
Here to get the JSON:
public static JSON fromStringToJSON(String jsonString){
boolean isJsonArray = false;
Object obj = null;
try {
JSONArray jsonArray = new JSONArray(jsonString);
Log.d("JSON", jsonArray.toString());
obj = jsonArray;
isJsonArray = true;
}
catch (Throwable t) {
Log.e("JSON", "Malformed JSON: \"" + jsonString + "\"");
}
if (object == null) {
try {
JSONObject jsonObject = new JSONObject(jsonString);
Log.d("JSON", jsonObject.toString());
obj = jsonObject;
isJsonArray = false;
} catch (Throwable t) {
Log.e("JSON", "Malformed JSON: \"" + jsonString + "\"");
}
}
return new JSON(obj, isJsonArray);
}
Example:
JSON json = fromStringToJSON("{\"message\":\"ciao\"}");
if (json.obj != null) {
// If the String is a JSON array
if (json.isJsonArray) {
JSONArray jsonArray = (JSONArray) json.obj;
}
// If it's a JSON object
else {
JSONObject jsonObject = (JSONObject) json.obj;
}
}
Using Kotlin
val data = "{\"ApiInfo\":{\"description\":\"userDetails\",\"status\":\"success\"},\"userDetails\":{\"Name\":\"somename\",\"userName\":\"value\"},\"pendingPushDetails\":[]}\n"
try {
val jsonObject = JSONObject(data)
val infoObj = jsonObject.getJSONObject("ApiInfo")
} catch (e: Exception) {
}
Here is the code, and you can decide which
(synchronized)StringBuffer or
faster StringBuilder to use.
Benchmark shows StringBuilder is Faster.
public class Main {
int times = 777;
long t;
{
StringBuffer sb = new StringBuffer();
t = System.currentTimeMillis();
for (int i = times; i --> 0 ;) {
sb.append("");
getJSONFromStringBuffer(String stringJSON);
}
System.out.println(System.currentTimeMillis() - t);
}
{
StringBuilder sb = new StringBuilder();
t = System.currentTimeMillis();
for (int i = times; i --> 0 ;) {
getJSONFromStringBUilder(String stringJSON);
sb.append("");
}
System.out.println(System.currentTimeMillis() - t);
}
private String getJSONFromStringBUilder(String stringJSONArray) throws JSONException {
return new StringBuffer(
new JSONArray(stringJSONArray).getJSONObject(0).getString("phonetype"))
.append(" ")
.append(
new JSONArray(employeeID).getJSONObject(0).getString("cat"))
.toString();
}
private String getJSONFromStringBuffer(String stringJSONArray) throws JSONException {
return new StringBuffer(
new JSONArray(stringJSONArray).getJSONObject(0).getString("phonetype"))
.append(" ")
.append(
new JSONArray(employeeID).getJSONObject(0).getString("cat"))
.toString();
}
}
May be below is better.
JSONObject jsonObject=null;
try {
jsonObject=new JSONObject();
jsonObject.put("phonetype","N95");
jsonObject.put("cat","wp");
String jsonStr=jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}
i m getting this response in a result of GET request to server
{"LL": { "control": "dev/sys/getkey", "value": "4545453030304138303046392035343733373432363020323031332D30322D31312031383A30313A3135", "Code": "200"}}
i just want to extract the value of "value" from the above json response.
I m using this code to get this response
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
HttpResponse response = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(
"http://192.168.14.247/jdev/sys/getkey"));
response = client.execute(request);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String responseText = null;
try {
responseText = EntityUtils.toString(response.getEntity());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("Parse Exception", e + "");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("IO Exception 2", e + "");
}
Log.i("responseText", responseText);
Toast.makeText(MainActivity.this, responseText + "",
Toast.LENGTH_SHORT).show();
}
});
my question is that how can i parse this and get the value of only "value" tag.
thanks
you can parse current json String to get value from it as :
// Convert String to json object
JSONObject json = new JSONObject(responseText);
// get LL json object
JSONObject json_LL = json.getJSONObject("LL");
// get value from LL Json Object
String str_value=json_LL.getString("value"); //<< get value here
try this
JSONObject json = (JSONObject) JSONSerializer.toJSON(responseText);
String value = json.getJSONObject("LL").getString("value");
Try this:
JSONObject json= json1.getJSONObject("LL");
String value= json.getString("value");
Try this,
JSONObject ResponseObject = new JSONObject(Response);
String str = ResponseObject.getJSONObject("LL").getString(value);
You can parse your response and get value try this:
try {
JSONObject jsonObject = new JSONObject(response);// Convert response string in to json object.
JSONObject jsonLL = jsonObject.getJSONObject("LL");// Get LL json object from jsonObject.
String strValue = jsonLL.getString("value");// Get value from jsonLL Object.
} catch (Exception e) {
e.printStackTrace();
}
Simple and Efficient solution : Use Googlle's Gson library
Put this in build.gradle file : implementation 'com.google.code.gson:gson:2.6.2'
Now convert the JSON String to a convenient datastrucutre like HashMap in 2 lines like this.
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson(JsonString , type);
or you can use this below class :
To convert your JSON string to hashmap use this :
HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(response)) ;
Use this class :) (handles even lists , nested lists and json)
public class Utility {
public static Map<String, Object> jsonToMap(Object json) throws JSONException {
if(json instanceof JSONObject)
return _jsonToMap_((JSONObject)json) ;
else if (json instanceof String)
{
JSONObject jsonObject = new JSONObject((String)json) ;
return _jsonToMap_(jsonObject) ;
}
return null ;
}
private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
private static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
}
Thank me later :)