How To send array in params in fast android networking library - java

I am using Fast-Android-Networking and I want to send data to server which contains strings and arrays. It's ok to send string but I am unable to send array its not array list. It's simple array.
I have search other solution but all are regarding volley.
can anyone help?
Please dont mark duplicate.
The last 5 parameters are arrays. I tried it as String.valueOf(ReadQuran) but it also didn't work.
My Code:
AndroidNetworking.post(Api.ROOT_URL +"api/stageFiveFormData")
.addBodyParameter("mto_id",idu)
.addBodyParameter("school_id", scholid)
.addBodyParameter("person_name", personnameS)
.addBodyParameter("designation", designantionS)
.addBodyParameter("cell_number",personcellS)
.addBodyParameter("email",emailpersonS)
.addBodyParameter("whatsapp_number",whatsApppersonS)
.addBodyParameter("school_name",schoolNameS)
.addBodyParameter("postal_address",postalAdressS)
.addBodyParameter("city",cityS)
.addBodyParameter("tehsil",tehsilS)
.addBodyParameter("district",districtS)
.addBodyParameter("s_primary", priamryChecked)
.addBodyParameter("s_middle", middleChecked)
.addBodyParameter("s_high", highChecked)
.addBodyParameter("s_higher", hsChecked)
.addBodyParameter("principal_name", nameOfPrincipalS)
.addBodyParameter("p_contact_num",cellNoPrincipalS)
.addBodyParameter("p_email",emailPrincipalS)
.addBodyParameter("p_whatsapp_number",whatsAppPrincipalS)
.addBodyParameter("class", Class)
.addBodyParameter("rq_book", String.valueOf(ReadQuran))
.addBodyParameter("rqb_qty", String.valueOf(ReadQuranQty))
.addBodyParameter("fq_book", String.valueOf(FehamQuran))
.addBodyParameter("fqb_qty", String.valueOf(FehamQuranQty))
.setPriority(Priority.HIGH)
.build()
.getAsString(new StringRequestListener() {
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String result = jsonObject.getString("result");
String message = jsonObject.getString("message");
if (result.equalsIgnoreCase("success")) {
Toast.makeText(FormStage5.this, "" + message, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(FormStage5.this, formstage2submittedmsg.class);
startActivity(intent);
pDialog.dismiss();
} else/* (result.equalsIgnoreCase("0"))*/ {
Toast.makeText(FormStage5.this, ""+message, Toast.LENGTH_SHORT).show();
pDialog.dismiss();
}
} catch (JSONException e) {
pDialog.dismiss();
Toast.makeText(FormStage5.this, "Something Went Wrong , Try Again", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onError(ANError anError) {
Toast.makeText(FormStage5.this, "Please Check Your Internet Connection" + anError.toString(), Toast.LENGTH_LONG).show();
pDialog.hide();
}
});

The best way is to create a POJO class and set Array value, then pass it. It will automatically gets converted into JSON, if you are using retrofit with GSONConverter factory.

The accepted answer to this question talks about Retrofit and GSON, while the question is about Fast Android Networking. The accepted answer did not work for me.
I found that the only way to do this was to build the body myself and add it to the request with .addJSONObjectBody.
I wanted a body that looks like:
{
"roles": [
"customer-admin"
]
}
The final way I found which works is:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
JSONObject roles;
try {
roles = new JSONObject();
JSONArray rolesArr = new JSONArray();
rolesArr.put("customer-admin");
roles.put("roles", rolesArr);
} catch (JSONException e) {
// Make error toast here
return;
}
AndroidNetworking.post(url)
.addJSONObjectBody(roles)
.build()

pass the arrayname.toString() as a value

Related

How to use ArrayAdapter and JSONArray for a listView

So far I can send a Get request to a server with a letter added to the url :
private void GetDevice() {
String deviceId = editTextDeviceId.getText().toString().trim();
if(TextUtils.isEmpty(deviceId)){
editTextDeviceId.setError("Please enter deviceId");
editTextDeviceId.requestFocus();
}
HashMap<String, String>params = new HashMap<>();
params.put("deviceID", deviceId);
PerformNetworkRequest request = new PerformNetworkRequest(Api.URL_GETBYDEVICEID + deviceId, null, CODE_GET_REQUEST);
request.execute();
}
When I press the button Search it sends the request :
buttonSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
GetDevice();
}
});
The server response is JSONArray :
W/System.err: org.json.JSONException: Value [{"DeviceId":"T","TransactionValue":2,"RSSI":2,"Time":"2018-08-02T14:43:00"}] of type org.json.JSONArray cannot be converted to JSONObject
Here is my problem.
From what I read, I know I need to use an ArrayList and ArrayAdapter to convert it into a JSONObject. Am I right so far ?
Here is where I’m stuck, as I don’t understand how to do it.
Many thanks in advance!
The JSON string returned from the server is a Json array,
so you need to convert it to a Jsonarray as follows, the jsonString here is the JSON string returned.
try {
JSONArray array=new JSONArray(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
The param you send is a JSONArray ,and the param that the server needs is a JSONObject.
The structure of JSONObject is like { },and a JSONArray is like [ { } , { } , ...... , { } ].So, you can change your param to {"DeviceId":"T","TransactionValue":2,"RSSI":2,"Time":"2018-08-02T14:43:00"} or edit the code of the server to receive parameters with JSONArray.
Try this:
You need to add array adapter
ArrayList<String> items = new ArrayList<String>();
for(int i=0; i < jArray.length() ; i++) {
json_data = jArray.getJSONObject(i);
String deviceID=json_data.getString("deviceID");
items.add(deviceID);
Log.d(deviceID,"Output"+deviceID);
}
ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item, items));
setListAdapter(mArrayAdapter);
add device id in Hashmap it works

Android Geocoder getFromLocationName fails with valid address

I'm trying to get latitude and longitude of specific addresses using
addressList = geoCoder.getFromLocationName(locationName, 1);
For most addresses this works just fine, but there are some valid addresses, like "Lentoasemantie 1, Vantaa", which returns empty array. The strange thing is that the valid addresses used to work 4 days ago, but not anymore while most of the addresses continue to work.
So, this looks like Google backend problem and I'm wondering should I report this to Google (where / how?) or switch away from using Geocoder, because it's inherently unreliable?
Geocoder Android API is not as efficient as the Google Maps Geocoding API so I suggest you to use this one instead of Geocoder.
You can find below the function to get location from address through Volley queue (For Lentoasemantie 1, Vantaa, it works) :
public void getLocationFromAddress(String address) {
String url = "https://maps.googleapis.com/maps/api/geocode/json?address="
+ Uri.encode(address) + "&sensor=true&key=API_KEY";
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest stateReq = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONObject location;
try {
// Get JSON Array called "results" and then get the 0th
// complete object as JSON
location = response.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location");
// Get the value of the attribute whose name is
// "formatted_string"
if (location.getDouble("lat") != 0 && location.getDouble("lng") != 0) {
LatLng latLng = new LatLng(location.getDouble("lat"), location.getDouble("lng"));
//Do what you want
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
});
// add it to the queue
queue.add(stateReq);
}

json array value from volley into hashmap string, string

i have a request to build slider image from jsonArray using volley, i don't know how to put value of jsonArray to hashmap<string, string> .. it keep saying null object
error message
Attempt to invoke virtual method 'java.lang.Object
java.util.HashMap.put(java.lang.Object, java.lang.Object)' on a null object reference
JSON array value
[
{"cPID":"62001002280293829",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/rsch.jpg"},
{"cPID":"62001002020254584",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/penang.jpg"},
{"cPID":"62001002050264258",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/guardian.jpg"}
]
and then i wanna put that value like this into hashmap<string, string> inside onCreate()
HashMap<String,String> url_maps = new HashMap<>();
url_maps.put("Hannibal", "http://static2.hypable.com/wp-content/uploads/2013/12/hannibal-season-2-release-date.jpg");
url_maps.put("Big Bang Theory", "http://tvfiles.alphacoders.com/100/hdclearart-10.png");
url_maps.put("House of Cards", "http://cdn3.nflximg.net/images/3093/2043093.jpg");
url_maps.put("Game of Thrones", "http://images.boomsbeat.com/data/images/full/19640/game-of-thrones-season-4-jpg.jpg");
it gonna use for adding picture to my slider(slideshow) inside onCreate()
for(String name : url_maps.keySet()){
DefaultSliderView DefaultSliderView = new DefaultSliderView(getContext());
// initialize a SliderLayout
DefaultSliderView
.image(url_maps.get(name))
.setScaleType(BaseSliderView.ScaleType.Fit)
.setOnSliderClickListener(this);
//add your extra information
DefaultSliderView.bundle(new Bundle());
DefaultSliderView.getBundle()
.putString("extra",name);
mDemoSlider.addSlider(DefaultSliderView);
}
and i don't know how to put values from volley JsonArray, and this is my request but error saying null.
private void getSlider(){
String tag_string_req = "sliderList";
// Showing progress dialog before making http request
JsonArrayRequest mostReq = new JsonArrayRequest(AppConfig.URL_Slider, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
for (int i = 0; i < 5; i++) {
JSONObject jObj = response.getJSONObject(i);
url_maps.put(jObj.getString("cPID"), jObj.getString("image"));
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + "Error Data Occured!!" + error.getMessage());
Toast.makeText(getContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) ;
AppController.getInstance().addToRequestQueue(mostReq, tag_string_req);
}
the values request was accepted on volley, it show on Logcat .. but null on hashmap .. tell me if i got mistake in my code, sorry just newbie and still study
You are iterating thru just the keys... You need to iterate through the keys and values...
for (url_maps.Entry<String, String> url_map : url_maps.entrySet()) {
String key = url_map.getKey();
String value = url_map.getValue();
// ...
}
ANOTHER WAY TO ATTEMPT THIS IS...
to deserialize your Json into a java object...
ObjectMapper mapper = new ObjectMapper();
string StringJson = "[
{"cPID":"62001002280293829",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/rsch.jpg"},
{"cPID":"62001002020254584",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/penang.jpg"},
{"cPID":"62001002050264258",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/guardian.jpg"}
]";
// For the following line to work you will need to make a URLMaps Class to hold the objects
URLMaps urlMaps = mapper.readValue(StringJson , URLMaps.class);
The URLMaps Class might look like this.
public class URLMaps{
public string name = "";
public string image = "";
//constructor
public URLMaps(string a, string b) {
name = a;
image = b;
}
public string getName() {
return name;
}
public string getImage() {
return image;
}
}
Then to utilize the class you can go with:
urlMaps.getName(), or urlMaps.getValue() in your DefaultSliderView.image()
Also to note, since this is a class you can store an array of them or a list of them, so you can re-purpose your for loop...
For (URLMap urlmap : UrlMaps[]) // where URLMaps is your object that holds multiple instances of URLMaps.
Lastly, it has been a long time since I have coded in Java, so this code is untested, but should help you come to a solution.

How do I get data from JSON string?

Here is my code:
try {
JSONObject json = (JSONObject) new JSONTokener(result).nextValue();
System.out.println(json);
JSONObject json2 = json.getJSONObject("data");
String test = json2.getString("headline");
System.out.println(test);
} catch (JSONException e) {
e.printStackTrace();
}
My String values start with the object data. So I am trying to get that object first and then capture the the object headline inside that.
My problem is, it is not taking the object data from the string.
Once I reach the line JSONObject json2 = json.getJSONObject("data");, it throws the exception. Please shed some light on this.
"data": [
{
"headline": "Close Update"
"docSource": "MIDNIGHTTRADER",
"source": "MTClosing",
"dateTime": "2015-10-23T16:42:46-05:00",
"link": "Markets/News",
"docKey": "1413-A1067083-1B14K77PVTUM1O7PCAFMI3SJO4",
},
The value for the key data is a JSON array containing one object, and not an object itself.
To get that object inside data, replace your line that throws an exception with the following:
JSONObject json2 = json.getJSONArray("data").get(0);
This gets the data array as a JSONArray object and then gets the 0th element, which is the object you want.
Your data "object", isn't actually an object, it's an array, notice the opening square bracket... I'm assuming in your actual code, it closes with one too.
"data": [{
"headline": "Close Update"
"docSource": "MIDNIGHTTRADER",
"source": "MTClosing",
"dateTime": "2015-10-23T16:42:46-05:00",
"link": "Markets/News",
"docKey": "1413-A1067083-1B14K77PVTUM1O7PCAFMI3SJO4",
}]
Try json.getJSONArray("data")[0] instead... or whatever index you need
try {
JSONObject json = (JSONObject) new JSONTokener(result).nextValue();
System.out.println(json);
JSONObject json2 = json.getJSONArray("data")[0];
String test = json2.getString("headline");
System.out.println(test);
}
catch (JSONException e) {
e.printStackTrace();
Your problem is based on the fact that your service returns and array instead of a single json object, so from here you can follow this suggestions to process directly from the JSONArray Can't access getJSONArray in java, or, at server side you can encapsulate your response array into another object like this (java example):
public class Data<T> {
private List<T> elements;
public ObjectSugetionsDTO(){
And build the response like this:
return new ResponseEntity<Data<YourInternalRepresentation>>(
new Data<YourInternalRepresentation>(yourMethodCallForTheArray()),
HttpStatus.OK);
I have found the second way to be better at keeping my API cleaner and more readable
EDIT: Better way
I whould also suggest the use of retrofit (http://square.github.io/retrofit/), by doing so, your service calls is resumed to (Example of calling and API that retrieves a list of users):
public class UserService {
public static IUserService getUserService() {
return RestAdapterManager.createService(IUserService.class );
}
public interface IUserService{
#GET("/api/users")
public void getAllUsers(Callback<List<User>> callback);
}
}
and the service call itself
UserService.getUserService().getAllUsers(new Callback<List<User>>() {
#Override
public void success(List<User> users, Response response) {
Log.d("Exito! " , "" + users.size());
}
#Override
public void failure(RetrofitError error) {
Log.d("Fail!", error.getUrl());
}
});
The simple inicialization of the connection object
public static <S> S createService(Class<S> serviceClass, String username, String password) {
RestAdapter.Builder builder = new RestAdapter.Builder()
.setEndpoint(API_BASE_URL);//Your api base url
RestAdapter adapter = builder.setLogLevel(RestAdapter.LogLevel.FULL).build(); //change the logging level if you need to, full is TOO verbose
return adapter.create(serviceClass);
}

Android - getting Google Places Photos and API calls

I wrote the method below in Spring to obtain a Google Places Photo this morning. The method is still buggy - 10 points for someone who can fix up the code - but it shows the gist of what I want to do:
#RequestMapping(method=RequestMethod.GET, value="/placedetails")
public BufferedImage PlaceDetails(#PathVariable String placeid) {
ArrayList<String> placePhotos = new ArrayList<>();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://maps.googleapis.com/maps/api/place/details/json?placeid="+placeid+"&key="+serverKey)
.build();
try {
//calling the GoogleAPI to get the PlaceDetails so that I can extract the photo_reference
Response response = client.newCall(request).execute();
//parsing the response with Jackson so that I can get the photo_reference
ObjectMapper m = new ObjectMapper();
JsonNode rootNode = m.readTree(response.body().string());
JsonNode resultNode = rootNode.get("result");
final JsonNode photoArrayNode = resultNode.get("photos");
if (photoArrayNode.isArray()) {
for (JsonNode photo: photoArrayNode) {
placePhotos.add(photo.get("photo_reference").textValue());
}
}
//calling the GoogleAPI again so that I can get the photoUrl
String photoUrl = String.format("https://maps.googleapis.com/maps/api/place/photo?maxwidth=%s&photoreference=%s&key=%s",
400,
placePhotos.get(0),
serverKey);
System.out.println(photoUrl);
//getting the actual photo
Request photoRequest = new Request.Builder().url(photoUrl).build();
Response photoResponse = client.newCall(photoRequest).execute();
if (!photoResponse.isSuccessful()) throw new IOException("Unexpected code " + response);
//returning the photo
return ImageIO.read(photoResponse.body().byteStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
I think to get an android app to display a Google Places picture, one would have to do the following:
Obtain the PlaceID first in Android. In my case, I obtained my PlaceID through an AutoCompleteTextView on my android app: (https://developers.google.com/places/android/autocomplete) (Call 1)
Then I call my method below. I call the Google Places API to get the Place Details (Call 2) and then once the details returns, I parse out the photo_reference using Jackson and call the Google Places API again to get the photo returned as a bitmap etc. (Call 3).
I'm making 3 calls to Google Places to return a Photo. When compared to the quota of 1000 calls a day, that is quite a significant amount of calls for getting 1 Photo.
Is there no other less way to get Photos without making so many calls?
I looked at this thread: How to get a picture of a place from google maps or places API
The person suggested that one uses panaramio instead which seems to be a really good option in the beginning but when I tested it out by typing in the example in my browser: http://www.panoramio.com/map/get_panoramas.php?set=public&from=0&to=20&minx=-33.868&miny=151.193&maxx=-33.864&maxy=151.197&size=medium&mapfilter=true, no photos were returned in the .php file.
I'm not sure if panaramio API still works?
Hi your problem is here
if (photoArrayNode.isArray()) {
for (JsonNode photo: photoArrayNode) {
placePhotos.add(photo.get("photo_reference").textValue());
}
Which should be
if (photoArrayNode.isArray()) {
for (JsonNode photo: photoArrayNode) {
placePhotos.add(photo.get("photo_reference").getString());
}
The photo_reference is a String value within the photo array element
Also, the below is unnecessary work:
//calling the GoogleAPI again so that I can get the photoUrl
String photoUrl = String.format("https://maps.googleapis.com/maps/api/place/photo?maxwidth=%s&photoreference=%s&key=%s",
There is no need to format the url string. The snippet below is part of the example I recommended below which answers your question specifically.
package in.wptrafficanalyzer.locationnearbyplacesphotos;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class PlaceJSONParser {
/** Receives a JSONObject and returns a list */
public Place[] parse(JSONObject jObject){
JSONArray jPlaces = null;
try {
/** Retrieves all the elements in the 'places' array */
jPlaces = jObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
/** Invoking getPlaces with the array of json object
* where each json object represent a place
*/
return getPlaces(jPlaces);
}
private Place[] getPlaces(JSONArray jPlaces){
int placesCount = jPlaces.length();
Place[] places = new Place[placesCount];
/** Taking each place, parses and adds to list object */
for(int i=0; i<placesCount;i++){
try {
/** Call getPlace with place JSON object to parse the place */
places[i] = getPlace((JSONObject)jPlaces.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
return places;
}
/** Parsing the Place JSON object */
private Place getPlace(JSONObject jPlace){
Place place = new Place();
try {
// Extracting Place name, if available
if(!jPlace.isNull("name")){
place.mPlaceName = jPlace.getString("name");
}
// Extracting Place Vicinity, if available
if(!jPlace.isNull("vicinity")){
place.mVicinity = jPlace.getString("vicinity");
}
if(!jPlace.isNull("photos")){
JSONArray photos = jPlace.getJSONArray("photos");
place.mPhotos = new Photo[photos.length()];
for(int i=0;i<photos.length();i++){
place.mPhotos[i] = new Photo();
place.mPhotos[i].mWidth = ((JSONObject)photos.get(i)).getInt("width");
place.mPhotos[i].mHeight = ((JSONObject)photos.get(i)).getInt("height");
place.mPhotos[i].mPhotoReference = ((JSONObject)photos.get(i)).getString("photo_reference");
JSONArray attributions = ((JSONObject)photos.get(i)).getJSONArray("html_attributions");
place.mPhotos[i].mAttributions = new Attribution[attributions.length()];
for(int j=0;j<attributions.length();j++){
place.mPhotos[i].mAttributions[j] = new Attribution();
place.mPhotos[i].mAttributions[j].mHtmlAttribution = attributions.getString(j);
}
}
}
place.mLat = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
place.mLng = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
} catch (JSONException e) {
e.printStackTrace();
Log.d("EXCEPTION", e.toString());
}
return place;
}
}
For a complete example please see: the source code is available for download.
http://wptrafficanalyzer.in/blog/showing-nearby-places-with-photos-at-any-location-in-google-maps-android-api-v2/

Categories