Getting volley response in another class - java

I made the first request successfully and I like to access my Volley response in other class , how can I do that because when I try to do that it return a null response

use interface and callback
public interface RestCallBack {
void onStart(String action);
void onComplete(String response, String action,Exception e);
}
And in your onResponse
listener.onComplete(response, action, null);
Then you can implement this interface in any class where you want the response.

At first its depends on your json data formate .......
You need to create a class
Declare a method in your class with a parameter string or array and call this method where you get json response
or follow this code
public class MyJsonParser {
public static Vector<MyModel> getJsonResponse(Context context,String response)
throws JSONException, IOException
{
final JSONObject stringResponse = new JSONObject(response);
final JSONObject responseHolder = stringResponse.getJSONObject("data");
final JSONArray jsonArray = responseHolder .getJSONArray("arrayData");
MyModel myModel;
Vector<MyModel> myArray = new Vector<MyModel>();
for (int i= 0;i<jsonArray .length();i++){
myModel= new MyModel();
JSONObject propertyHolder = jsonArray .getJSONObject(i);
myModel.setId(propertyHolder,"id");
myModel.setName(propertyHolder, "name");
myArray .addElement(myModel);
myModel= null;
}
return myArray ;
}
}
and call this method where you get json response like this....
MyJsonParser.getJsonResponse(context,response);

Related

How do i call API with multiple parameters in android studio

I have created this app that pulls data from an API and shows it in a list. the problem I am having is that I can't pull the JSON data from an API with a nested JSON array.
In this image it is simple since all the info is in one array / table.
https://imgur.com/a/v9gsbop
but in this image, it is more difficult for me. for example, how do i call the paragraph value: line in body?
https://imgur.com/Qj5CRn8
This is the code that i am currently using to pull data from API.
private void parseJSON () {
String url = "https://blah,com";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray =response.getJSONArray("items");
for (int i = 0; i< jsonArray.length(); i++){
JSONObject article = jsonArray.getJSONObject(i);
String authorName = article.getString("article_author");
String imageUrl = article.getString("src");
String published = article.getString("first_published_at");
String description = article.getString("value");
String headline = article.getString("title");
Try this way to work with nested json array,
Try this to get the result,
Your question is not quiet clear, but what from what I understand I do think you need this solutions:
Solution: Sending Parameters along with the Request
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
textView.setText("Response: " + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("parameter1 name","parameter1 Value");
params.put("parameter2 name","parameter2 Value");
return params;
};
As in the above example I have shown a get request; So suppose the URL is: "https://www.youtube.com/channel/UCXEIUll8VvOqRN-OSZ5_aOg" and parameter is "view_as" and parameter value is "subscriber" then params.put("view_as","subscriber");
Solution: If you want to pass multiple parameters to your request then,
Map<String, String> params = new HashMap();
params.put("first_param", 1);
params.put("second_param", 2);
JSONObject parameters = new JSONObject(params);
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, parameters, new Response.Listener<JSONObject>() { ... }
Solution: If you want to pull the items array and get its subsequent object contents, try using an iterator instead of a for loop,
JSONArray jsonArray = (JSONArray) apiResult[0].get("body");
Iterator jsonArrayIterator = jsonArray.iterator();
while(jsonArrayIterator.hasNext()) {
JSONObject jsonObject = (JSONObject) jsonArrayIterator.next();
JSONObject jsonValue = (JSONObject) jsonObject.get("value");
JSONObject jsonOriginal = (JSONObject) jsonValue.get("original");
JSONObject jsonWidth = (JSONObject) jsonOriginal.get("width");
}

ResponseBuilder toString() returns object classes in string, not just the raw response string

I'm presently migrating from the Java ASK-SDK v1 to Java ASK SDK v2.
I'm trying to return a webhook call using the ResponseBuilder class that I built my response up and the data is correct, however when I try to populate the HTTP body with the JSON text, the ResponseBuilder.toString() value doesn't just populate the data with just the string, I get the following:
Optional[class Response {
outputSpeech: class SsmlOutputSpeech {
class OutputSpeech {
type: SSML
playBehavior: null
}
ssml: <speak>Some of the things you can say are What would you like to do?</speak>
}
card: null
reprompt: class Reprompt {
outputSpeech: class SsmlOutputSpeech {
class OutputSpeech {
type: SSML
playBehavior: null
}
ssml: <speak>You can say ..., is that what you want?</speak>
}
}
directives: []
shouldEndSession: false
canFulfillIntent: null
}]
Is there another way to get the string for the body of the response? The BaseSkillResponse has a getResponse() call, however, I cannot figure out how to use the class to generate the String response output.
I was able to get the string with the following in my class:
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
myFunction(){
try{
return toJsonString(responseBuilder.build().get());
} catch(IOException e) {
e.printStackTrace();
}
}
public String toJsonString(Response response)throws IOException {
return OBJECT_MAPPER.writeValueAsString(response);
}
Solve this by doing the following:
public String toJsonString(Response response)throws IOException
{
JacksonSerializer jacksonSerializer = new JacksonSerializer();
constructedResponse = jacksonSerializer.serialize(response);
JSONObject jsonObject = new JSONObject();
jsonObject.put("response",constructedResponse);
}

How to use "?" no get Path Rest?

I am developing a rest server in java, netbeans.
I have my GET request:
//myip/application/v1/cardapio/id=1
#Stateless
#Path("v1/cardapio")
public class CardapioResource {
#GET
#Produces("application/json")
#Path("id={id}")
public String getCardapio(#PathParam("id") int id) {
JsonArray array = (JsonArray) gson.toJsonTree(ejb.findById(id));
JsonObject obj = new JsonObject();
obj.add("dados", array);
return obj.toString();
}
}
It works correctly.
But I want to do differently, as I saw in other examples, I want to mark the beginning of the variables with the "?".
Ex: //myip/application/v1/cardapio/?id=1
#Stateless
#Path("v1/cardapio")
public class CardapioResource {
#GET
#Produces("application/json")
#Path("?id={id}")
public String getCardapio(#PathParam("id") int id) {
JsonArray array = (JsonArray) gson.toJsonTree(ejb.findById(id));
JsonObject obj = new JsonObject();
obj.add("dados", array);
return obj.toString();
}
}
Thus error 404, page not found.
What you seen in "other examples" is just normal usage of URL's query part. Just use it with #Queryparam
#Stateless
#Path("v1/cardapio")
public class CardapioResource {
#GET
#Produces("application/json")
#Path("/") // can be removed actually
public String getCardapio(#QueryParam("id") int id) {
JsonArray array = (JsonArray) gson.toJsonTree(ejb.findById(id));
JsonObject obj = new JsonObject();
obj.add("dados", array);
return obj.toString();
}
}
Here you are mapping getCardapio to v1/cardapio/ and you will try to get id from query string so
Ex: //myip/application/v1/cardapio/?id=1
will just work.
You can't, after ? sign it's query parameters and not path parameters
You can use #QueryParam("id")
You can also use
#RequestParam("id") int id

anybody can correct this code?

#GET
#Produces(MediaType.APPLICATION_JSON)
public List<ProductData> getAllProductList(#QueryParam("hotel_id") int hotel_id) throws SQLException{
System.out.println("Hotel id id==="+hotel_id);
ProductData productData=new ProductData();
List<ProductData> products = new ArrayList<ProductData>();
rs=stmt.executeQuery("select * from products where hotel_id="+hotel_id);
while(rs.next()){
productData.setProductName(rs.getString("name"));
productData.setProductCategory(rs.getString("category"));
productData.setProductRate(rs.getDouble("rate"));
productData.setProductLogoPath(rs.getString("productLogoPath"));
products.add(productData);
}
return products;
}
I have passed List as JsonObject.Now i tried to get List value like
void handleResponse(String response) throws JSONException {
JSONObject jsonObject=new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("products");
}
but i can't get the List value.anyBody can help me?
There is the simple way to convert json string to object :
Try this :
ObjectMapper mapper = new ObjectMapper();
POJO obj = mapper.readValue(yourJSONString, POJO.class);
Use method signature something similar like-
public Response getAllProduct..
&
return like-
return Response.status(Status.OK).entity(products).build();
For intg. layer use-
public ClientResponse<> similarSignatureMethod..
&
call via the client and then get response entity as-
clientResponse.getEntity();

How do I sort JSONObjects in an JSONArray in Java (Server side)?

#GET
#Produces("application/json")
#Consumes("application/json")
#Path("/getStuff/{id}")
public String getStuff(
#PathParam("id") String id,
#Context HttpServletRequest request,
#Context HttpServletResponse response) throws Exception
{
Collection<Stuff> stuff = Manager.getStuff().values();
JSONArray jArray = new JSONArray();
for (Stuff i : stuff)
{
jsnObjct.put("id", i.getId());
jsnObjct.put("name", i.getName());
jArray.add(jsnObjct);
}
json = jArray.toString();
response.setContentType("text/javascript");
response.getOutputStream().print(json);
response.flushBuffer();
return null;
}
I'm guessing that you're using the net.sf.json library for this? If so, I'd try something like the following. I don't know for sure if this would work, but if it does work it will be by far the easiest approach. Unfortunately I'm not too familiar with that library so I'm not sure of the exact details (you may be able to skip the creation of a second JSONArray - not sure if add(int, Object) pushes objects down or overwrites them):
Object[] myArray = jArray.toArray();
myArray = Arrays.sort(myArray);
JSONArray sortedJArray = new JSONArray();
for (Object obj : myArray) {
sortedJArray.add(obj);
}

Categories