error: no suitable constructor found for JsonArrayRequest - java

I'm a programming student building an Android App that uses a api json url and I'm getting a no suitable constructor found for JsonArrayRequest
Here is the error:
C:\Users\jerma\AndroidStudioProjects\VolleyParsing\app\src\main\java\com\jermainebjonesgmail\volleyparsing\MainActivity.java:37:
error: no suitable constructor found for
JsonArrayRequest(int,String,>,)
JsonArrayRequest arrayRequest = new JsonArrayRequest(Method.GET,
^
constructor JsonArrayRequest.JsonArrayRequest(String,Listener,ErrorListener)
is not applicable
(actual and formal argument lists differ in length)
constructor JsonArrayRequest.JsonArrayRequest(int,String,JSONArray,Listener,ErrorListener)
is not applicable
Here is my code:
public class MainActivity extends AppCompatActivity {
private final static String URL = "https://age-of-empires-2-api.herokuapp.com/api/v1/units";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestQueue queue = Volley.newRequestQueue(this);
JsonArrayRequest arrayRequest = new JsonArrayRequest(Method.GET,
URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("Response: ", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error", error.getMessage());
}
});
queue.add(arrayRequest);
}
}

You are creating JsonArrayRequest in a wrong way. see java docs, for constructor.
Constructor Summary
JsonArrayRequest(String url, Response.Listener<JSONArray> listener, Response.ErrorListener errorListener)
Creates a new request.
JsonArrayRequest can be created as below:
Request request = new JsonArrayRequest(httpMethod, url, params, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
serverCallback.onAPIResponse(apiTag, response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
serverCallback.onErrorResponse(apiTag, error);
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
};
Please find sample code here

Related

How give json parameters in Volley String Request (Android Studio)

I want to pass the following JSON object in a volley string request:
{
"command":"connect",
"port":"VIRTUAL",
"baudrate":115200,
"printerProfile":"_default",
"save":true,
"autoconnect":false
}
The response is 1.
How can I implement this in Android studio using Kotlin and Volley?
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.POST,URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//error
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("command","connect");
params.put("port","VIRTUAL");
params.put("baudrate", "115200");
params.put("save","true");
params.put("autoconnect","false");
return params;
}
};
queue.add(sr);

Volley execute wrong method

I am using volley library to send data on server as a json. My server response successfully. Data is saving in database. But Volley execute the ErrorResponse, here is my code
private void upload(final Context context) {
String url = BASE_URL + "upload.php";
RequestQueue requestQueue = Volley.newRequestQueue(context);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Intent intent=new Intent(ProfilePictureActivity.this,HomeActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Log.i("Error", "" + error);
Toast.makeText(context, "Cannot save", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> stringMap = new HashMap<>();
stringMap.put("name", names);
stringMap.put("date_of_birth",dobs);
stringMap.put("address", presentAddress);
stringMap.put("phone",phone);
stringMap.put("email", email);
stringMap.put("image",phone+".jpg");
stringMap.put("photo",imageToString(bitmap));
return stringMap;
}
};
requestQueue.add(stringRequest);
}

How to create a single volley webservice class to use across the android app?

My android application uses multiple network calls in a single activity and i have several of these activities where i have to use both post and get requests. I want to create a single "VolleyWebservice" class and call the same in multiple activities instead of writing the complete volley code. I am relatively new to android development and i don't understand where i am going wrong.
public class VolleyWebService {
public JSONObject result;
public JSONObject getResponse(String url, Context mContext) {
RequestQueue mQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Anshuman" + response.toString());
result = response;
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
mQueue.add(request);
return result;
}
}
The method in My activity where i am calling this class
private void callFunctionGetDist() {
ProgressDialog progressDialog;
progressDialog = ProgressDialog.show(recorddata.this, "", "Please Wait...", true);
JSONObject response = new VolleyWebService().getResponse(urlConfigClass.GET_DISTRICT, this);
try {
if(response.toString().contains("Status:Success,Details")){
arrDistName.clear();
arrDistCode.clear();
arrDistName.add("Select District Name");
arrDistCode.add("Select District Code");
JSONArray jsonArray = response.getJSONArray("Status:Success,Details");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jobJ = jsonArray.getJSONObject(i);
String scheName = jobJ.getString("post");
JSONObject jobJDist = new JSONObject(scheName);
String distname = jobJDist.getString("District");
String distcode = jobJDist.getString("DistrictCode");
arrDistName.add(distname);
arrDistCode.add(distcode);
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<>(recorddata.this,
R.layout.custom_textview_to_spinner, arrDistName);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
district.setAdapter(dataAdapter);
progressDialog.dismiss();
}else{
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Response is null or empty", Toast.LENGTH_LONG).show();
}
} catch (Exception volleyError) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
}
I tried creating the same class but i am not able to get the response to other activities. Although i am getting the correct response in the Volley jsonbject response, the response return null in other activities.
I want to have the result object return the response in my recorddata activity
This is what i have tried so far, no luck though!
public void postResponse (String url, Context mContext, final VolleyResponseListener listener) {
try {
String encodedUrl = url.replace(" ", "%20") + "";
if (encodedUrl.contains("("))
encodedUrl = encodedUrl.replace("(", "%28");
if (encodedUrl.contains(")"))
encodedUrl = encodedUrl.replace(")", "%29");
encodedUrl = encodedUrl.replace(" ", "%20");
RequestQueue mQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POst, encodedUrl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Anshuman" + response.toString());
listener.onSuccess(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.onError(error);
}
}) {
#Override
protected Map<String, String> getParams() {
return new HashMap<>();
}
};
mQueue.add(request);
} catch (Exception e) {
e.printStackTrace();
}
}
For the sake of achieving your goal, (without taking in to consideration architecture and coding principles), you can pass a callback:
public class VolleyWebService {
public interface VolleyResponseListener {
void onSuccess(JSONObject response);
void onError(VolleyError error);
}
public JSONObject result;
public JSONObject getResponse(String url, Context mContext, VolleyResponseListener listener) {
RequestQueue mQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Anshuman" + response.toString());
listener.onSuccess(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.onError(error);
}
});
mQueue.add(request);
return result;
}
}
To use it:
volleyWebService.getResponse("your url", context, new VolleyResponseListener() {
#Override
void onSuccess(JSONObject response) {
//do what you want on success
}
#Override
void onError(VolleyError error) {
//do what you want on error
}
});

move a method from mainActivity to a class file

i have the following method inside mainActivity but i am trying to move it to separate class file so i can call it in other activities
public void addUser(){
StringRequest stringRequest = new StringRequest(Request.Method.POST,
constants.register_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getApplicationContext(), response ,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage() ,Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("username", "value");
params.put("email", "value");
params.put("password", "value");
return params;
}
};
requestHandler.getInstance(this).addToRequestQueue(stringRequest);
}
i have created a class called 'aqlCalls' and tried to put this and other methods inside but i can't figure how to do that..
any help appreciated..
I think you need to try to find the exact problem firstly.
According to the code in your method, I guess the problem is the Toast. If you want to use the Toast outside the Activity, you need to pass the context to this method. If you search for "android toast outside activity", you will get a lot of similar questions. such as this.
I suggest that adding a new parameter to context the addUser() and use the context to show the Toast.
And when using this method, pass a context (such as getApplicationContext()) to the method.
for example
void addUser(Context mcontext){
//all the toast usage change to
Toast.makeText(mContext, ....)
}
You can create your own listener to communicate with the activities and set the method static and save inside a class, passing the Context and use it in the request call.
public static void addUser(Context context, AddUserListener listener){
...
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
listener.onSucces(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.onError(error.getMessage())
}
})
The Listener should be:
public interface AddUserListener{
void onSuccess(String response);
void onError(String message)
}
And finally in the activity do this:
MyClass.addUser(getApplicationContext(), new AddUserListener {
#Override
void onSuccess(String response){
... //Toast.makeText(...)
}
#Override
void onError(String message){
...//Toast.makeText(...)
}
});
Notice:
Please if you receive any Exception write down in your post, maybe you will receive an exception related with MainThread
I think your looking like something like this:
public class aqlCalls {
public static void addUser(Context context) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, constants.register_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", "value");
params.put("email", "value");
params.put("password", "value");
return params;
}
};
requestHandler.getInstance(context).addToRequestQueue(stringRequest);
}
}
Then you can call it from your class with:
public class OtherClass{
static void yourMethode() {
aqlCalls.addUser();
}
}
I think this is what you are looking for.

http request with Volley-api on Android

I'm trying to make a http-post request to my localhost server. The problem I have Is that I'm not getting any response when I make the request.
I'm doing the request from a fragment class:
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.i(TAG, " Button clickde");
fLogin.setCallback(loginButton); //Let's register a callback
final RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "AbCdEfGh123456");
String url = "http://127.0.0.1/create_row.php";
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, url,new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG, error.getMessage());
}
});
fLogin.setFacebookListener(new FacebookLogin.OnFacebookListener() {
#Override
public void onFacebookLoggedIn(JSONObject parameters) {
}
});
}
});
Nothing is printed out from the onResponse or Response.ErrorListener.
You did't add the jsObjRequest to the queue, so the request wasn't executed, add it to the queue by:
queue.add(jsObjRequest);
see the tutorial on developer.android.com.

Categories

Resources