I am sending POST request with two parametars id and string.
public void sendParams(String id,String stringSave, final VolleyCallback vc) {
final String URL = "http://maps.b1.finki.ukim.mk/MapController/save";
HashMap<String, String> params = new HashMap<String, String>();
params.put("cId", id);
params.put("positions", stringSave);
RequestQueue rq=Volley.newRequestQueue(GridTilesActivity.this);
JsonRequest jr=new JsonRequest(Request.Method.POST,URL,params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
vc.onSuccess(response);
Log.d("Response ",response.toString());
System.out.println(response);
String string=response.optString("positions");
Log.d("Positions",string);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
});
rq.add(jr);
}
Now on button click i want to take response from this POST.
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendParams(mapId,pom,new VolleyCallback() {
#Override`enter code here`
public void onSuccess(JSONObject result) {
Log.d("Result","" + result.toString());
}
});
But i dont get nothing.What's wrong with this code..?
I added Log.d("Error",volleyError.toString()) on ErrorResponse and get this:
04-19 23:52:00.375 12825-12825/com.example.bukic.mapyourroom D/Error﹕ com.android.volley.ParseError: org.json.JSONException: End of input at character 0 of
First of, why don't you try the Volley Request on that buttonclick. Then you could handle the onResponse. Hope that helps?
Related
I have class A and B.
"A" makes an instance of "B" and call a method that modify a String property. However, after the calling the property checked in "A" is null.
Can anyone help me?
Class B
private String Retro;
....
public boolean Login(final String user, final String pass){
stringRequest = new StringRequest(Request.Method.POST, Url + strLogin,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
Retro = "Done";
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
**Retro = error.getMessage();**
Toast.makeText(context, "Error de acceso: "+Retro, Toast.LENGTH_LONG).show(); //error.getMessage()
}
}) {
#Override
protected Map<String, String> getParams(){
Map<String, String> parameters = new HashMap<>();
parameters.put("identifier", user);
parameters.put("password", pass);
return parameters;
}
};
// Add the request to the RequestQueue.
requestQueue.add(stringRequest);
return Retro == "Done";
}
Class A
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
accessDB = new StrapiDBAccess(this);
signIn();
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
...
if (acct != null) {
....
boolean result = accessDB.Login(parcelAccess.personEmail, "*******");
tvAuth.setText(tvAuth.getText()+" "+**accessDB.getRetro()**); //
}
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
parcelAccess.signedIn = false;
parcelAccess.personName = "Anónimo";
Toast.makeText(this, "Error de autenticación con Google. Chequee que tiene internet e inténtelo de nuevo.", Toast.LENGTH_SHORT).show();
}
}
I found the answer to my doubt. It is impossible to do by a field, or getter or any direct way. It is neccesary to implement an interface for success or error. It would be this way:
Class B
public void Login(final String user, final String pass, final VolleyCallback callback){
Retro = "";
stringRequest = new StringRequest(Request.Method.POST, Url + strLogin,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
***callback.onSuccess("Done");***
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Retro = Retro + String.copyValueOf(error.getMessage().toCharArray());
***callback.onError(Retro);***
//error.getMessage()
}
}) {
#Override
protected Map<String, String> getParams(){
Map<String, String> parameters = new HashMap<>();
parameters.put("identifier", user);
parameters.put("password", pass);
return parameters;
}
};
// Add the request to the RequestQueue.
requestQueue.add(stringRequest);
Toast.makeText(context, "Error de acceso: "+ErrorCode, Toast.LENGTH_LONG).show();
}
Class A
accessDB.Login(parcelAccess.personEmail, "************", new StrapiDBAccess.VolleyCallback(){
#Override
public void onSuccess(String result) {
}
#Override
public void onError(String error)
//no pudo ingresar
}
}
});
Well, I hope to help anyone who has this kind of trouble
I want to have answer on onResponse but did not get it. I need guidance how I can achieve this.
This is my code :
public class Network {
Context context;
String pokemondata;
CallbackInterface callbackInterface;
public Network(Context context,CallbackInterface callbackInterface) {
this.context = context;
this.callbackInterface=callbackInterface;
}
public void test(){
String URL = "http://pokeapi.co/api/v2/pokemon/";
RequestQueue requestQueue = Volley.newRequestQueue(context);
JsonObjectRequest jsonObjectRequest= new JsonObjectRequest(Request.Method.GET, URL, null,new Response.Listener<JSONObject>(){
#Override
public void onResponse(JSONObject response) {
Log.d("onResponse", String.valueOf(response));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,"Something went wrong",Toast.LENGTH_SHORT).show();
callbackInterface.data("failure");
Log.d("fail","failure");
}
});
requestQueue.add(jsonObjectRequest);
}
}
failure - OnErrorResponse which prints com.example.tablayout D/Data: My data +failure
onResponse data is "http://pokeapi.co/api/v2/pokemon/"
I have used String url = "https://pokeapi.co/api/v2/pokemon/"; instead of String URL = "http://pokeapi.co/api/v2/pokemon/";
Now it's working
Receive SMS then set EditText to msgBody
public class SmsBroadcastReceiver extends BroadcastReceiver {
//.....
((EditText)MainActivity.mThis.findViewById(R.id.editTextName)).setText(msgBody);}
The error is this in View cannot be applied to android.view.View.Onclicklistiner
//onCreate
buttonSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
buttonSave.performClick(this);
}
});
the message will automatically save to SQLite and sync to Mysql when buttonSave is click
private void saveNameToServer() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Saving Name...");
progressDialog.show();
final String name = editTextName.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_SAVE_NAME,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject obj = new JSONObject(response);
if (!obj.getBoolean("error")) {
//if there is a success
//storing the name to sqlite with status synced
saveNameToLocalStorage(name, NAME_SYNCED_WITH_SERVER);
} else {
//if there is some error
//saving the name to sqlite with status unsynced
saveNameToLocalStorage(name, NAME_NOT_SYNCED_WITH_SERVER);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
//on error storing the name to sqlite with status unsynced
saveNameToLocalStorage(name, NAME_NOT_SYNCED_WITH_SERVER);
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("name", name);
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
#Override
public void onClick(View view) {
saveNameToServer();
}
Are there other ways to auto click button when EditText value changes?
Instead of invoking the click buttonSave.performClick(this); just simply invoke saveNameToServer(); method to save your data.
buttonSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//buttonSave.performClick(this); // remove, not required
saveNameToServer(); // save your data
}
});
I have tried the method from Android Volley return value from response but I keep getting this error : com.box.ajian.box.Controllers.IOFunctions cannot be cast to com.box.ajian.box.Constants.VolleyCallback . What should I put in my casting area for it to work? I am quite confused with tis volleycallback stuff.
This is my code. Hope someone can help me
IOFunctions.java (Not an activity)
public void checkIfPersonExists(final Context context, final Person aPerson){
StringRequest postRequest = new StringRequest(Request.Method.POST, USEREXISTS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("RESPONSE",response.toString());
((VolleyCallback)context).onSuccess(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("email",aPerson.getEmail());
params.put("phone",aPerson.getPhone());
return params;
}
};
Volley.newRequestQueue(context).add(postRequest);
}
Functions.java (Not an activity)
public Boolean register(Person aPerson,Context context){
ioFunctions.checkIfPersonExists(context,aPerson);
new VolleyCallback(){
#Override
public void onSuccess(String result) {
if(result.equals(false)){
Log.d("HELLO","HELLO");
}
}
};
return false;
}
Register.java (Activity)
functions.register(new Person(Firstname,Lastname,functions.dateFormatter(DateofBirth),Email,Password,Phone),Register.this);
Interface
public interface VolleyCallback {
void onSuccess(String result);
}
The activity register calls the functions.java which then calls iofunctions.java. I want iofunctions.java to return a true or false and so Im relying on volley.
You do not need your own callback class. Volley comes with it's own!
Just add it to the parameters, pass it to the request.
public void checkIfPersonExists(final Context context, final Person aPerson,
Response.Listener<String> onResponse){ // <-- here
StringRequest postRequest = new StringRequest(Request.Method.POST, USEREXISTS,
onResponse, // <--- here
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("email",aPerson.getEmail());
params.put("phone",aPerson.getPhone());
return params;
}
};
Volley.newRequestQueue(context).add(postRequest);
}
Then handle accordingly, but don't make this method return because Volley is asynchronous.
public void register(Person aPerson,Context context){
ioFunctions.checkIfPersonExists(context,aPerson,
new Response.Listener<String>(){
#Override
public void onResponse(String response) {
boolean exists = !result.equals("false");
if(!exists){
Log.d("Person exists","Nope!");
// Person does not exist... continue registration from here
} else {
Log.d("Person exists", "That account exists!");
}
}
};
// Don't return here
}
I have been fiddling with this for a few days now. Couldn't get it right. Android studio won't let me compile it with this error. So, I have this application where I have two tabs and two fragments. One fragment is called new, and that fragment fetches json. But I couldn't get to do it properly. I have uploaded a picture of how the error looks like, and the class files. Can you please help me out?
Error: "Cannot resolve constructor JsonObjectRequest(int, java.lang.String, null.......)
new_fragment.java
public class new_fragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private VolleySingleton volleySingleton;
private ImageLoader imageLoader;
private RequestQueue requestQueue;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() !=null){
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
volleySingleton = VolleySingleton.getsInstance();
requestQueue = volleySingleton.getRequestQueue();
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,"http://10.0.8.152/json/new.json",null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(request);
}
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedIntanceState) {
setHasOptionsMenu(true);
View layout = inflater.inflate(R.layout.new_fragment, container, false);
return layout;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.ref_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.refreshico:
// do s.th.
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
VolleySingleton
public class VolleySingleton {
private static VolleySingleton sInstance = null;
private ImageLoader mImageLoader;
private RequestQueue mRequestQueue;
private VolleySingleton(){
mRequestQueue = Volley.newRequestQueue(appClass.getAppContext());
mImageLoader = new ImageLoader(mRequestQueue,new ImageLoader.ImageCache() {
private LruCache<String, Bitmap> cache = new LruCache<>((int)(Runtime.getRuntime().maxMemory()/1024)/8);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static VolleySingleton getsInstance(){
if(sInstance==null){
sInstance = new VolleySingleton();
}
return sInstance;
}
public RequestQueue getRequestQueue(){
return mRequestQueue;
}
public ImageLoader getImageLoader(){
return mImageLoader;
}
}
cast (String)null.
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,"http://10.0.8.152/json/new.json",(String)null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
new JsonObjectRequest takes 3rd Parameter as String requestBody
cast null to String
or you can make a null string like String rBody = null; and then pass rBody as 3rd Parameter
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
"http://10.0.8.152/json/new.json", (String) null, // here
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(request);
For everyone trying to implement this right now: Google changed the jsonObjectRequest constructor: now you don't suppy the request type anymore, instead you supply firstly the url and then null as second parameter if you want a get request. e.g.:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("http://www.aaa.com/getJSON/dummyMeldung.json", null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("meldung");
for (int i = 0; i <= jsonArray.length(); i++) {
JSONObject meldung = jsonArray.getJSONObject(i);
String comment = meldung.getString("comment");
Log.d("ausgabe", comment);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Well, i see the situation, and it happends because as your error say, the constructor doesnt exists.
If you are using the JsonObjectRequest as default, and you want to consume an Get method, you dont have to send the null parameter, you just should send of this way:
Change this:
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,"http://10.0.8.152/json/new.json",null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(request);
For this:
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,"http://10.0.8.152/json/new.json",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(request);
As you can see, i just remove the parameter for the JsonObject, because the method is Get, and there is an constructor thats accept that you dont send JsonObject.
Another solution is to make your own JsonObjectRequest, and custom it to accept that kind of values.
Regards.
There is a ambiguous Constructor, for solve this, use this code:
JSONObject jsonObject = null;
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.GET, "Your url", jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
The problem as to do with the version of volley.
On your build.gradle app file you should have
dependencies {
......
compile 'com.mcxiaoke.volley:library:1.0.0'
.....
}