We are developing an Ecommerce Mobile Application but here we are facing an problem in passing an array of string to an Json Object. Whenever we are passing the same it is throwing an error as attached in the Log. It seems like an extra "\" is coming up.
Please find below my code Snippet:
try {
stFullName=Edit_FullName.getText().toString();
Log.e("BillingName",stFullName);
stEmailId=Edit_EmaiAdress.getText().toString();
stAddress=Edit_Adress.getText().toString();
stCity=Edit_City.getText().toString();
stState=Edit_State.getText().toString();
stZipCode=Edit_ZipCode.getText().toString();
stPhoneNo=Edit_MobileNumber.getText().toString();
stCountry=Edit_Country.getText().toString();
stLandmark=Edit_Landmark.getText().toString();
jsonObject1.put("BillingName",stFullName);
jsonObject1.put("BillingEmail",stEmailId);
jsonObject1.put("BillingTelephone",stPhoneNo);
jsonObject1.put("BillingCountry",stCountry);
jsonObject1.put("BillingZip",stZipCode);
jsonObject1.put("BillingCity",stCity);
jsonObject1.put("BillingState",stState);
jsonObject1.put("BillingLandmark",stLandmark);
jsonObject1.put("GrandTotal",ProductAmount);
jsonObject1.put("BillingAddress",stAddress).toString().replaceAll("\\\\","");
jsonObject1.put("DeviceID",deviceId);
jsonObject1.put("IsDifferentShipping",false);
String jsonFormattedString = jSonData;
Log.e("jsonFormattedString",jsonObject1.toString());
JSONArray jsonArray = new JSONArray();
jsonArray.put(productArray);
Log.e("productArray",productArray.toString());
productArray = productArray.toString().replaceAll("\\\\","").trim();
jsonObject1.put("ChekoutProductsModel_List",productArray.toString().replaceAll("\\\\",""));
Log.e("productArray", jsonObject1.toString().replaceAll("\\\\","").trim());
//
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("object1",jsonObject1.toString());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Config.Url.concat(getMakePayment),
jsonObject1, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject Response) {
Log.e("jsonResponse",Response.toString());
try {
String jsonResponse=Response.getString("ResponseObject");
Log.e("ResponseBilling",jsonResponse);
if(jsonResponse.equals("Billing info save successfully!")){
Toast.makeText(context,jsonResponse,Toast.LENGTH_SHORT).show();
Intent intent=new Intent(context,ProductReview.class);
intent.putExtra("product_id",ProductCode);
intent.putExtra("stock_id",StockId);
startActivity(intent);
}
else {
Toast.makeText(context,jsonResponse,Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
If any body can please check and help us out on the same.
Related
I try to get information from this link
and I don't get it !
This is my code:
String s = getJSONFile();
String myDataArray[] = {};
try{
JSONObject reportJSON = new JSONObject();
JSONArray dateJSON = reportJSON.getJSONArray("terrestrial_date");
myDataArray = new String[dateJSON.length()];
for (int i = 0; i <dateJSON.length(); i++){
JSONObject jsonObject = dateJSON.getJSONObject(i);
myDataArray[i] = jsonObject.getString("terrestrial_date");
}
}catch (JSONException e){
e.printStackTrace();
}
ArrayAdapter<String> stringAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.row, myDataArray);
if (mListView != null){
mListView.setAdapter(stringAdapter);
}
}
this is the getJSONFile method:
public String getJSONFile() {
String json = null;
try {
InputStream is = getResources().openRawResource(R.raw.weather_json);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
Thanks for help :)
You should use GSON librari and for the Model of this code http://www.jsonschema2pojo.org/
This is so easy.
terrstial_date is a String of report. try this,
String date=jsonObject.getString("terestial_date");
also your json parsing structere is not correct accroding to your json
{
"report": {
"terrestrial_date": "2017-10-13",
"sol": 1844,
"ls": 73.0,
"min_temp": -81.0,
"min_temp_fahrenheit": -113.8,
"max_temp": -28.0,
"max_temp_fahrenheit": -18.4,
"pressure": 869.0,
"pressure_string": "Higher",
"abs_humidity": null,
"wind_speed": null,
"wind_direction": "--",
"atmo_opacity": "Sunny",
"season": "Month 3",
"sunrise": "2017-10-13T10:59:00Z",
"sunset": "2017-10-13T22:43:00Z"
}
}
This is how you can get response from OkHttp
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://marsweather.ingenology.com/v1/latest/?format=json")
.get()
.build();
try {
Response response = client.newCall(request).execute();
String json = response.body().string();
JSONObject jsonObject = new JSONObject(json);
JSONObject reportJson = jsonObject.getJSONObject("report"); // your report object.
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
Put your Json file in your assets folder with .json extension and use this method to get JsonString from it
public String loadJSONFromAsset(String fileName) {
String json = null;
try {
InputStream is = getAssets().open(fileName);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
And get the String using this function like this
String jsonString = MyApplication.loadJSONFromAsset(this,"yourJsonFileName.json");
and Parse like that
try{
JSONObject responce = new JSONObject(jsonString);
JSONArray report= responce.getJSONObject("report");
String terrestrial_date = report.getString("terrestrial_date");
}catch (JSONException e){
e.printStackTrace();
}
this is my code after all the change:
public void find_weather() {
String url = "http://marsweather.ingenology.com/v1/latest/?format=json";
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject main_object = response.getJSONObject("results");
JSONArray array = response.getJSONArray("");
JSONObject object = array.getJSONObject(0);
String date = object.getString("date");
String tempMin = String.valueOf(main_object.getDouble("min_temp"));
String tempMax = String.valueOf(main_object.getDouble("max_temp"));
String atmo_opacity = object.getString("atmo_opacity");
mMaxTemp.setText("max_temp");
mMinTemp.setText("min_temp");
mAtmoOpacity.setText("atmo_opacity");
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEEE-MM-dd");
String formatted_data = sdf.format(calendar.getTime());
mDate.setText(formatted_data);
double temp_max_int = Double.parseDouble(tempMax);
double temp_min_int = Double.parseDouble(tempMin);
mMaxTemp.setText(String.valueOf(i));
mMinTemp.setText(String.valueOf(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(jor);
You are doing in wrong way
1.report is a JsonObject inside your response means you have your report inside another JsonObject. First you have to parse your response to get report data
2.terrestrial_date is a string data so you have to use report.getJsonString("terrestrial_date") you are using reportJSON.getJSONArray("terrestrial_date"); which is used for Array data
For, more information get a look here How to parse JSON in Android
Try this,
String s = getJSONFile();
String terrestrial_date = "";
try{
JSONObject responce = new JSONObject(s);
JSONObject report= responce.getJSONObject("report");
terrestrial_date = report.getString("terrestrial_date");
}catch (JSONException e){
e.printStackTrace();
}
EDIT
Try, Volley for fetching JSON data
First you need to add dependency of volley in build.gradle file-:
dependencies {
compile 'com.android.volley:volley:1.0.0'
}
Then use following code to fetch or parse your JSON data
// Tag used to cancel the request
String url = "http://marsweather.ingenology.com/v1/latest/?format=json";
StringRequest strReq = new StringRequest(Request.Method.GET,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
String terrestrial_date = "";
try{
JSONObject responce = new JSONObject(response);
JSONObject report= responce.getJSONObject("report");
terrestrial_date = report.getString("terrestrial_date");
}catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to request queue
Volley.newRequestQueue(this).add(strReq);
SCREENSHOT
As, You can see the screenshot above. I am getting response with the same code
I was tried to get data from MySQL PHP to Android with JSON Object but not work with me. I was searching about my problem but the examples I found didn't help me.
I have an array list of strings, then I set the strings MySQL DB.
After that, I want to get the cities strings from the DB with JSON, but I was unsuccessful.
My questions are:
How can I make sure that if I have city, it won't appear again?
How can I set the cities in an array list in Android?
My PHP code:
<?php
include 'connection/connection.php';
$noResult = "no results";
// to set the names at the list view
$sql = "SELECT workrCity FROM workersTable ";
$result = $connect->query($sql);
if ($result->num_rows > 0){
while($row[] = $result->fetch_assoc()) {
$json = json_encode($row,JSON_UNESCAPED_UNICODE);
}
} else {
echo $noResult;
}
echo $json;
$connect->close();
?>
the array list function in my Fragment working good :
private ArrayList<City> initCities() {
Log.d(TAG, "ArrayList_CitiesFragment_initCities");
String[] cityName = {"","","",""}; // the cities names
ArrayList<City> theCities = new ArrayList<>();
for (String aCityName : cityName) {
City city = new City(aCityName, false);
theCities.add(city);
}
return theCities;
}
Now I want to get the cities names from MySQL in a JSON-like output:
handler = new Handler(Looper.getMainLooper());
Thread runner = new Thread(new Runnable() {
#Override
public void run() {
Log.d(TAG, " runner");
GetCitiesJson getCitiesJson = new GetCitiesJson();
try{
String[] res = getCitiesJson.getCitiesDataFromDB();
JSONObject jsonObject = new JSONObject(String.valueOf(res));
JSONObject workrCity = jsonObject.getJSONObject("workrCity");
Activity activity = getActivity();
Toast.makeText(activity,"its :" + workrCity, Toast.LENGTH_SHORT).show();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
});
runner.start();
I know that my code is not correct, but I don't know what's missing...
Hi: Im using Volley library to get a Json file from my server and works fine and fast.
In app/build.gradle under dependencies:
compile 'com.android.volley:volley:1.0.0'
Then, in the activity you want to get the json data:
String from = "http://www.yourserver.com/file.json";
StringRequest request = new StringRequest(from, new Response.Listener<String>() {
#Override
public void onResponse(String string) {
try {
parseJson(URLDecoder.decode(URLEncoder.encode(string, "iso8859-1"),"UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
// Error
Log.d("ERROR:", String.valueOf(volleyError));
}
});
Volley.newRequestQueue(this).add(request);
Then you can parse the Json:
public static void parseJson(String jsonString) {
try {
JSONObject object = new JSONObject(jsonString);
getMessage(this, object);
} catch (JSONException e) {
e.printStackTrace();
}
}
And finally you can get the strings inside your Json:
public static void getMessage(JSONObject object){
if(object.length() != 0) {
try {
message = String.valueOf(object.get("message"));
} catch (JSONException e) {
e.printStackTrace();
}
} }
Okay i was copy the code. but have one problem.that the message = String.valueOf(object.get("message")); where is the var named message? it's on red colo
message is a String:String message; Then in your Json, you need a node called message to get it.
I'm using retrofit to POST a json array to server. Data is something like this:
{something:
{somethings:
[
{"param1":"value", "param2":value},
{"param1":"value", "param2":value}
]
}
}
however, my server forces me to MUST include the indices in the array like:
{something:
{somethings:
{
"0":{"param1":"value", "param2":value},
"1":{"param1":"value", "param2":value}
}
}
}
In other words cannot send parameters like this:
something[somethings][][param1]
something[somethings][][param2]
I must include indices:
something[somethings][0][param1]
something[somethings][0][param2]
How to do this using retrofit?
My interface looks like this:
interface ApiService {
#POST("endpoint")
public Callback<Something> postSomething (#Body Something something);
}
My classes look like following:
public class PostSomething {
private MapOfSomething something = new MapOfSomething();
public MapOfSomething getSomething() {
return portfolio;
}
public void setSomething(MapOfSomething something) {
this.something = something;
}
}
public class MapOfSomething {
private JSONObject somethings = new JSONObject();
public JSONObject getPortfolios() {
return somethings;
}
public void setSomethings(List<Something> somethingList) {
for (int i = 0; i<somethingList.size(); i++) {
try {
somethings.put(String.valueOf(i).toString(), somethingList.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
and calling the method like:
PostSomethings something = new PostSomethings();
MapOfSomething map = new mapOfSomething();
map.setSomethings(listofSomething);
something.setSomethings(map);
apiService.postSomething(something);
One way to solve your problem is to put json directly into body , so your interface will look like this
interface ApiService {
#POST("endpoint")
public Callback<Something> postSomething (#Body JSONObject jsonObject);
}
Now you need to create the JSONObject , here is how I have created your desired JSONObject
JSONObject mainJson = new JSONObject();
JSONArray list = new JSONArray();
JSONObject singleElement1 = new JSONObject();
try {
singleElement1.put("param1","value1");
singleElement1.put("param2","value2");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject singleElementSet1 = new JSONObject();
try {
singleElementSet1.put("1",singleElement1);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject singleElement2 = new JSONObject();
try {
singleElement2.put("param1","value1");
singleElement2.put("param2","value2");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject singleElementSet2 = new JSONObject();
try {
singleElementSet2.put("2",singleElement2);
} catch (JSONException e) {
e.printStackTrace();
}
list.put(singleElementSet1);
list.put(singleElementSet2);
JSONObject subJson = new JSONObject();
try {
subJson.put("something",list);
mainJson.put("something",subJson);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("json",""+mainJson.toString());
I am assuming right now you are calling your service like this way
Call<Something> call = instanceOfYourAPIService.postSomething(anInstanceOfSomethingObject);
But now you have to replace this with the following
Call<Something> call = instanceOfYourAPIService.postSomething(mainJson); //mainJson is the JSONObject which is created earlier
Hope it helps
EDIT
JSONObject mainJson = new JSONObject();
JSONObject singleElement1 = new JSONObject();
try {
singleElement1.put("param1","value1");
singleElement1.put("param2","value2");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject singleElement2 = new JSONObject();
try {
singleElement2.put("param1","value1");
singleElement2.put("param2","value2");
} catch (JSONException e) {
e.printStackTrace();
}
ArrayList<JSONObject> jsonObjectArrayList = new ArrayList<JSONObject>();
//hope you can add item to this arraylist via some loop
jsonObjectArrayList.add(singleElement1);
jsonObjectArrayList.add(singleElement2);
JSONArray list = new JSONArray();
for(int i = 0;i<jsonObjectArrayList.size();i++){
JSONObject elementSet = new JSONObject();
try {
elementSet.put(String.valueOf(i).toString(),jsonObjectArrayList.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
list.put(elementSet);
}
JSONObject subJson = new JSONObject();
try {
subJson.put("something",list);
mainJson.put("something",subJson);
} catch (JSONException e) {
e.printStackTrace();
}
I am using volley in my android app and i add Torrent objects to the Arraylist and it fills the list but after the program exits this method getAllDetails() the arraylist is empty..could someone please explain what is really going on???
private void getAllDetails() {
String URL = MOVIE_DETAILS_URL + movie.getId() + CAST_URL;
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(URL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject dataObject = response.getJSONObject(Keys.DATA);
JSONObject movieObject = dataObject.getJSONObject(Keys.MOVIE);
JSONArray torrentsArray = movieObject.getJSONArray(Keys.TORRENTS);
for (int i = 0; i < torrentsArray.length(); i++) {
JSONObject torrentObject = torrentsArray.getJSONObject(i);
Torrent torrent = new Torrent();
torrent.setUrl(torrentObject.getString(Keys.URL));
torrent.setSize(torrentObject.getString(Keys.SIZE));
torrent.setQuality(torrentObject.getString(Keys.QUALITY));
torrent.setSeeds(Integer.parseInt(torrentObject.getString(Keys.SEEDS)));
torrent.setPeers(Integer.parseInt(torrentObject.getString(Keys.PEERS)));
torrentList.add(torrent);
}
getTorrent();//when this method is called here the list has items on it and it works fine
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}
this method uses the torrentlist arraylist to download the .torrent file
private void getTorrent() {
String mUrl = torrentList.get(0).getUrl();
InputStreamVolleyRequest request = new InputStreamVolleyRequest(Request.Method.GET, mUrl,
new Response.Listener<byte[]>() {
#Override
public void onResponse(byte[] response) {
// TODO handle the response
try {
if (response != null) {
String name = movie.getMovie_title() + ".torrent";
File torrentDirectory = createFolder();
File file = new File(torrentDirectory, name);
FileOutputStream fos = new FileOutputStream(file);
fos.write(response);
Toast.makeText(ViewMovie.this,"Successfully Downloaded",Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("KEY_ERROR", "UNABLE TO DOWNLOAD FILE");
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO handle the error
error.printStackTrace();
}
}, null);
RequestQueue mRequestQueue = Volley.newRequestQueue(getApplicationContext(), new HurlStack());
mRequestQueue.add(request);
}
A quick fix you can try to pass your ArrayList to your getTorrent() function.
getTorrent(torrentList);
You will call your function like this.
private void getTorrent(ArrayList<Torrent> passedList) {
String mUrl = passedList.get(0).getUrl();
// rest of your code here
}
But you need to know that, this function will always give you the result of first torrent. Because you are getting 0 index in ArrayList. Maybe by passing index also, you can create more functional method.
I've got a slight problem with a getString function in my Android code.
I create a string and I want to use it to retrieve a String which is part of a JSON Array but I get the following error:
The method getString(String) is undefined for the type String
This is the specific code for this section:
private void read_JSON()
{
JSONArray jsa2 = new JSONArray();
for (int i=0; i < jsa2.length(); i++)
{
try
{
JSONObject jso2 = new JSONObject();
jso2 = jsa2.getJSONObject(i);
String one = one.getString("Blur");
//esbrinar com arreglar aixo!!
}catch (JSONException e)
{
e.printStackTrace();
}
}
}
"Blur" is a String which is part of a JSONArray, defined here:
private void create_JSON()
{
JSONObject jso = new JSONObject();
try {
jso.put("Nombre","Miguel");
jso.put("Apellidos", "Garcia");
jso.put("Año_nacimiento", 1990);
JSONArray jsa = new JSONArray();
jsa.put("Blur");
jsa.put("Clur");
jso.put("Nombres_Hijos", jsa);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Could you help me understand what I'm doing wrong?
Thank you very much.
Yours sincerely,
Mauro.
jso2.getString("Blur") might be what you're trying to call. I believe you want to extract a string from the JSONObject you just got from JSONArray. What you actually wrote is to extract string from the string you just defined.