How to get out values from java interface - java

I have a variable inside an interface method and I want it outside the interface:
String responseString;
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// i want this value out!
responseString = response.toString();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.toString());
}
});
Of course I can't just assign responseString = response.toString() because they have different scopes. So how can I do this?
Probably this question has already been answered but I couldn't find anything similar online.

Try this once as per your JSON structure Either JSONArray or JSONObject.
//JSON Array
private JSONArray result;
//Creating a string request
StringRequest stringRequest = new StringRequest(URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray("your key");
//OPTIONAL function
functionName(result);//If using function
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});

The new Response.Listener<String>() {...} that you're doing in that method is called "anonymous" implementation. Indeed you are implementing the interface, but you don't hold any static reference to it in the code.
What you should do, is to have a normal implementation of the interface which of course implements the method required, but also holds a field and a special getter for your field:
public class YourStringListener implements Response.Listener<String> {
private String responseString; //<-- declare a field
#Override
public void onResponse(String response) {
this.responseString = response.toString(); //<-- set the field
}
public String getResponseString() {
return this.responseString; //<-- get the field from outside
}
}
Now, you should be able to do this:
String responseString;
YourStringListener listener = new YourStringListener(); //<-- don't implement anonimously, use the concrete implementation
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, listener, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.toString());
}
});
System.out.println(listener.getResponseString()); //<-- access the value of response string from the concrete implementation instance
Of course, be careful you're into a listener. The value will be null until when the method onResponse will have asynchronously been called back.

Related

Is it possible to get a response as a json file instead of making him a jsonobject in java?

So i have a get request from an API, when i get the response i want to make that response into a json file instead of making him an JSONOBJECT, is it possible ? i will paste the get funcion here, and the way im getting the JSONOBJECT.
I want to replace the way i get a JSONOBJECT, from a way to get that json as a file that goes to my assets directory.
public void getAssetPlant(final VolleyCallBack callBack) {
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.GET, url_assets, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject j = new JSONObject(response);
callBack.onSuccess();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MapActivity.this, "Failed to gather info" + error.networkResponse.statusCode, Toast.LENGTH_SHORT).show();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer " + token);
return headers;
}
};
requestQueue.add(request);
}

How to solve: org.json.JSONException: Value GVL7TY of type java.lang.String cannot be converted to JSONObject

I'm trying to make a post request and get a string that my server generates as a response. I get this error: D/Error.Response: com.android.volley.ParseError: org.json.JSONException: Value GVL7TY of type java.lang.String cannot be converted to JSONObject. the GVL7TY value is the generated code from the server. I'm new to android and I don't know how to fix it. appreciate your help!
private void sendRequest(final String email, final String name,String url,RequestQueue queue) {
JSONObject request = new JSONObject();
try
{
request.put("TeacherEmail", email);
request.put("ClassName", name);
}
catch(Exception e)
{
e.printStackTrace();
}
JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST, url, request,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject responseObj) {
// response
Log.d("Response", responseObj.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
) {
};
queue.add(postRequest);
}
The response returned from your server is not valid json. Try debuging the raw response.

Android-volley: how do I take the String response value and assign it outside of a volley StringRequest method?

The data appears as expected when I run the method in the debugger, however whenever I try to do anything with it the value of parentObject is returned as null.
I simply want to take the response from the server and store it as a JSONObject to be reused elsewhere.
public void jsonParse() {
String url = "http://178.128.166.68/getUserInfo.php";
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
/*
the data appears as expected within the debugger however
returns null when i attempt to use it elsewhere
*/
parentObject = new JSONArray(response);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("phone", phone);
params.put("password", password);
return params;
}
};
mQueue.add(request);
}
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
parentObject = new JSONArray(obj);
for (int i = 0; i < parentObject.length(); i++) {
JSONObject parObj = (JSONObject) parArray.get(i);
ModelClass modelClass = new ModelClass()// you have to create a model
modelClass.set1Parameter(parObj.getString("1Parameter"));
modelClass.set2Parameter(parObj.getString("2Parameter"));
arrayList.add(modelClass)//In your arraylist save the data
}
} catch (JSONException e) {
e.printStackTrace();
}
}
First of all you need to check what type response you getting from server i.e (JsonObject or JsonArray).
public void jsonParse() {
String url = "http://178.128.166.68/getUserInfo.php";
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
/*
if its JSONObject
*/
JSONObject jsonobject = new JSONObject(response);
String value= jsonobject.getString("value");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("phone", phone);
params.put("password", password);
return params;
}
};
mQueue.add(request);
}
as per your question ... you want to store response in jsonObject but in code you are store response in jsonArray
parentObject = new JSONArray(response);
so you must have to confirm response is in object or array.
if response is in object (like {}) change to parentObject = new JSONObject(response);
else change type of parentObject to JSONArray

using data from java classes and methods

i have an entry level question:
if there is external java class let's say 'Class1' inside this class there is a method called 'method1' inside this method there is Override method 'onResponse' inside this method two variables is being set 'a' and 'b'.
in the android mainActivity i called the method from the class like this:
Class1.method1();
after calling the method how i can retrieve these variables to be used in mainActivity...
thanks..
public abstract class Class1 extends Context {
final Context mcontext;
public static void method1(final Context mcontext, final String x){
StringRequest stringRequest = new StringRequest(Request.Method.POST, constants.URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject parentObject = new JSONObject(response);
JSONObject userDetails = parentObject.getJSONObject("data");
//read attributes
String a = userDetails.getString("a");
String b = userDetails.getString("b");
} catch (JSONException e) {
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(mcontext, error.getMessage() ,Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("x", x);
return params;
}
};
requestHandler.getInstance(mcontext).addToRequestQueue(stringRequest);
}
Why not create a wrapper class for a and b
public class Details {
public string a;
public string b;
}
and then read/return it in the method1
public abstract class Class1 extends Context {
final Context mcontext;
public static Details method1(final Context mcontext, final String x){
Details data = new Details;
StringRequest stringRequest = new StringRequest(Request.Method.POST, constants.URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject parentObject = new JSONObject(response);
JSONObject userDetails = parentObject.getJSONObject("data");
//read attributes
data.a = userDetails.getString("a");
data.b = userDetails.getString("b");
} catch (JSONException e) {
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(mcontext, error.getMessage() ,Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("x", x);
return params;
}
};
requestHandler.getInstance(mcontext).addToRequestQueue(stringRequest);
return data;
}
if you want to return more than one value you should use Android ways called Intent
but if you insist
you can use Array or ArrayList return type for the inner inner method
class Class1{
public static ArrayList<Object> method1(){
return onResponse();
}
public static ArrayList<Object> onResponse(){
return arrayList<Object>;
}
}
but still i see no reason to not use Intent

Parsing JSONArray using Gson + Volley not getting response

So I am trying to parse an array of objects from json using Google's Gson library and Volley for HTTP requests. My issue is it's as if the code isn't 'hitting' the OnResponse call. I've tried adding a simple Log printout within the function just to see if it does anything.
My GsonRequest class comes straight from Google's Training Docs. I constructed these methods based on an answer to this question.
This is my code:
private void runVolleyJson() throws AuthFailureError {
GsonRequest<Meetings> getMeetings = new GsonRequest<Meetings>(AUTH_URL, Meetings.class, getHeaders(),
createMyReqSuccessListener(),
createMyReqErrorListener());
helper.add(getMeetings);
}
private Response.Listener<Meetings> createMyReqSuccessListener() {
return new Response.Listener<Meetings>() {
#Override
public void onResponse(Meetings response) {
// NOTHING HAPPENS FROM HERE!
try {
Log.d("response", response.toString());
} catch (Exception e) {
e.printStackTrace();
}
// Do whatever you want to do with response;
// Like response.tags.getListing_count(); etc. etc.
}
};
}
private Response.ErrorListener createMyReqErrorListener() {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Do whatever you want to do with error.getMessage();
}
};
}
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> map = new HashMap<>();
map.put("Content-Type", "application/json;");
map.put("Authorization", "Bearer <sometoken>");
return map;
}
There is absolutely no error. It is authorizing the request, but nothing happens in OnResponse, it just seems to ignore that function.
Now I've tried using a standard StringRequest with volley and it works flawlessly, like this:
private void runVolleyTest() {
StringRequest request = new StringRequest(Request.Method.GET, AUTH_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonarray = new JSONArray(response);
for(int i = 0; i < jsonarray.length(); i++) {
Gson gson = new Gson();
Meeting m = gson.fromJson(jsonarray.get(i).toString(), Meeting.class);
Log.e("Meeting", m.getMeetingId() + " " + m.getStatus());
}
} catch (JSONException e) {
e.printStackTrace();
}
;
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
txtError(error);
}
}) {
#Override
public Map<String, String> getHeaders() {
HashMap<String, String> map = new HashMap<>();
map.put("Content-Type", "application/json;");
map.put("Authorization", "Bearer <sometoken>");
return map;
}
};
//request.setPriority(Request.Priority.HIGH);
helper.add(request);
}
Try adding this line at the beginning
RequestQueue helper = Volley.newRequestQueue(mContext);
Add these line
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
if you don't want to the save response in cache memory then add this
requestQueue.add(stringRequest);
According to my personal opinion its better if you pass the application context.

Categories