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'
.....
}
Related
public class MainActivity extends AppCompatActivity {
private static final String url = "https://www.googleapis.com/books/v1/volumes?q=android&maxResults=1";
private static String data ="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
data=data + response.substring(0);
Log.d("CODE1",response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,"Something went wrong",Toast.LENGTH_SHORT).show();
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
TextView text = (TextView) findViewById(R.id.text_view);
text.setText(data);
}
}
I am trying to use the "response" value of onResponse function at the end of the onCreate function. As you can see data is assigned to TEXTVIEW but it is not displayed. How can we use the data in response to pass to other data structure and then use for other work?
use like this:
data=data + response.substring(0);
Log.d("CODE1",response);
text.setText(data);
Because, this line(setText) runs before you send request. You displayed empty data.
Move the setText method into onResponse
Your code will be like this:
TextView text = (TextView) findViewById(R.id.text_view);
final StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("CODE1",response);
text.setText(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,"Something went wrong",Toast.LENGTH_SHORT).show();
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
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
I have a json data from a url in which I want to fetch text data from using volley library. I have also a fragment in which the data would be shown.
Volley gives me an error after fetching the data and I have no idea what am doing wrong.
The onErrorResponse function gets called again and again and the toast message is shown - Something went wrong.
Here's the Fragment.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.fragment, container, false);
final TextView textView = view.findViewById(R.id.event_text);
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Config.events_server, (String) null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
textView.setText(response.getString("trending"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(view.getContext(), "Something went wrong", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
MySingleton.getmInstance(view.getContext()).addToRequestQueue(jsonObjectRequest;
return view;
}
And the MySingleton.java
public class MySingleton {
private static MySingleton mInstance;
private static Context ctx;
private RequestQueue requestQueue;
private MySingleton(Context ctx) {
this.ctx =ctx;
requestQueue = getRequestQueue();
}
private RequestQueue getRequestQueue() {
if(requestQueue == null) {
requestQueue = Volley.newRequestQueue(ctx.getApplicationContext());
}
return requestQueue;
}
public static synchronized MySingleton getmInstance(Context context) {
if(mInstance == null) {
mInstance = new MySingleton(context);
}
return mInstance;
}
public <T>void addToRequestQueue(Request<T> request){
getRequestQueue().add(request);
}
}
Try this:
Add this in your Singleton classs:
#Override
public void onCreate() {
super.onCreate();
// initialize the singleton
mInstance = this;
}
:
HashMap<String, String> params = new HashMap<>();
params.put("value","value" );
params.put("value", "value");
JSONObject par = new JSONObject(params);
JsonObjectRequest objectRequest = new JsonObjectRequest("url here", par,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
Log.d(" response", response.toString());
}},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
//handle error here
}
});
// Access the RequestQueue through your singleton class.
MyApplication.getInstance().addToRequestQueue(jsObjRequest);
Let me know in the comments for any further queries
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
}