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.
Related
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);
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);
}
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
I am trying to use Volley to send 3 strings to a php script that sends it to a localhost server. I have this so far;
RegisterRequest;
public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://192.168.*.*:80/phptesting/Register.php";
private Map<String, String> params;
public RegisterRequest(String username, String password,String isAdmin,
Response.Listener<String> listener,
Response.ErrorListener errListener){
super(Method.POST, REGISTER_REQUEST_URL,listener,errListener);
params = new HashMap<>();
params.put("username",username);
params.put("password",password);
params.put("isAdmin",isAdmin+"");
}
public Map<String, String> getparams() {
return params;
}
}
This is CreateUser;
public class CreateUser extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_user);
this.setTitle("Create User");
final EditText username1 = findViewById(R.id.Createusername);
final EditText password1 = findViewById(R.id.CreatePassword);
final Switch isAdmin = findViewById(R.id.isadmin);
final Button createuser = findViewById(R.id.createuserbtn);
if (getIntent().hasExtra("com.example.northlandcaps.crisis_response")){
isAdmin.setVisibility(View.GONE);
}
createuser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = username1.getText().toString();
final String password = password1.getText().toString();
final String isadmin = isAdmin.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response Value: ", response);
if (response.equals("success")){
Intent intent = new Intent(CreateUser.this, MainActivity.class);
CreateUser.this.startActivity(intent);
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(CreateUser.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry",null)
.create()
.show();
}
}
};Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), String.valueOf(error), Toast.LENGTH_SHORT).show();
}
};
RegisterRequest registerRequest = new RegisterRequest(username,password,isadmin,responseListener,errorListener);
RequestQueue queue = Volley.newRequestQueue(CreateUser.this);
queue.add(registerRequest);
}
});
}
Now, the only error im getting is an Undefined index. And thats because Volley isnt sending data to the php script. The php script does work properly when data is sent to it, so my question is this; what changes do i have to make to my script for it to send the 3 strings over?
Never mess with code or else it will be confusing for you to handle things properly.
So just make another class and use it in your activity.
Have a look at this class I have written, you can use it anywhere and for any type of data request.
public class SendData {
private Context context;
private String url;
private HashMap<String, String> data;
private OnDataSent onDataSent;
public void setOnDataSent(OnDataSent onDataSent) {
this.onDataSent = onDataSent;
}
public SendData(Context context, String url, HashMap<String, String> data) {
this.context = context;
this.url = url;
this.data = data;
}
public void send(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(onDataSent != null){
onDataSent.onSuccess(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(onDataSent != null){
onDataSent.onFailed(error.toString());
}
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.putAll(data);
return map;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(0, 0, 0));
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
}
public interface OnDataSent{
void onSuccess(String response);
void onFailed(String error);
}
}
And now you can easily use it from any activity. Just give data in the constructor and use the interface to track the events this way
HashMap<String, String> data = new HashMap<>();
data.put("username", "");//define the value
data.put("password", "");//define the value
data.put("is_admin", "");//define the value
SendData sendData = new SendData(this, "", data); //defie the context and url properly
sendData.setOnDataSent(new SendData.OnDataSent() {
#Override
public void onSuccess(String response) {
//parse the response
}
#Override
public void onFailed(String error) {
//something went wrong check the error
}
});
sendData.send();
I am new to android and using volley to communicate with web services.
Postman details
I found sending a raw text to the web service will only work on postman.I try using grant_type=password&username=myusername&password=mypassowrd getting myusername and mypassword from two editText from my mainActivity, .
Is there any better way to achieve this?
public class MainActivity extends AppCompatActivity {
Button btnLogin,btnFetch,btnExit;
EditText editTxtUsr,editTxtPass;
TextView txtView;
String uRL ="****";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLogin=findViewById(R.id.buttonLogin);
btnFetch=findViewById(R.id.buttonFetch);
btnExit=findViewById(R.id.buttonExit);
editTxtUsr=findViewById(R.id.editTextUsrname);
editTxtPass=findViewById(R.id.editTextPassword);
txtView=findViewById(R.id.textViewData);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String wsURL = uRL + "/authtoken";
//final String appData = "grant_type=password&username=" + editTxtUsr + "&password=" + editTxtPass;
StringRequest request = new StringRequest(Request.Method.POST, wsURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("true")) {
Toast.makeText(MainActivity.this, "Login Successful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Incorrect ", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(MainActivity.this, "Some error occured" + volleyError, Toast.LENGTH_SHORT).show();
}
}) {
#Override
public Map<String,String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/text");
headers.put("charset", "TYPE_UTF8_CHARSET");
return headers;
}
#Override
protected Map<String,String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<>();
parameters.put("grand_type", "SET_VALUE");
parameters.put("Username", editTxtUsr.getText().toString());
parameters.put("Password", editTxtPass.getText().toString());
return parameters;
}
};
RequestQueue rQueue= Volley.newRequestQueue(MainActivity.this);
rQueue.add(request);
}
});
btnExit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
}
I have tried various ways to achieve this, but with no luck. That's a sample of my code that I use to try to connect to the web service.
I get [253] BasicNetwork.performRequest: Unexpected response code 400 for...
I searched thoroughly through StackOverflow but I can't seem to find the correct answer to my question.
Any help would be appreciated.
Its been days I have been working on this but after I posted my question, I found the solution after some tries.
The answer is simpler than I have thought.
What you need to do is make an objectrequest and override the body with the text you want to post. Nothing had to change in headers or parameters.
I still can't find an answer using Stringrequest.
#Override
public byte[] getBody() {
try {
return requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
Where requestBody is the raw text you want to send as a string.