Android Volley ambiguous reference to JsonObjectRequest - android

i'm trying to use simple Volley JsonObjectRequest fro web service but i get this error:
error: reference to JsonObjectRequest is ambiguous, both constructor JsonObjectRequest(int,String,String,Listener<JSONObject>,ErrorListener) in JsonObjectRequest and constructor JsonObjectRequest(int,String,JSONObject,Listener<JSONObject>,ErrorListener) in JsonObjectRequest match
i'm install volley from Gradle and this is my simple code which i'm using in project.
public class Simple_JsonRequest extends Activity {
private TextView mTvResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act__json_request);
mTvResult = (TextView) findViewById(R.id.tv_result);
Button btnJsonRequest = (Button) findViewById(R.id.btn_json_request);
btnJsonRequest.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
RequestQueue queue = MyVolley.getRequestQueue();
JsonObjectRequest myReq = new JsonObjectRequest(Request.Method.GET,
"http://echo.jsontest.com/key/value/one/two",
null,
createMyReqSuccessListener(),
createMyReqErrorListener());
queue.add(myReq);
}
});
}
private Response.Listener<JSONObject> createMyReqSuccessListener() {
return new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
mTvResult.setText(response.getString("one"));
} catch (JSONException e) {
mTvResult.setText("Parse error");
}
}
};
}
private Response.ErrorListener createMyReqErrorListener() {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mTvResult.setText(error.getMessage());
}
};
}
}

How about you replace the null which is the 3rd argument, with something more specific and then try ?

Because JsonObjectRequest have two constructors,
one is
JsonObjectRequest(int,String,JSONObject,Listener<JSONObject>,ErrorListener)
and another is
JsonObjectRequest(int,String,String,Listener<JSONObject>,ErrorListener),so if you set the third parameter to null,the compiler won't know which constructor you want to use,so such an error occurred.
To solve your problem,you just can replace your third parameter to new JSONObject() or "".

Related

Two JSON parse method with volley within the same activity Android Studio

I have been using volley library to use JSON object request from a URL in my Android activity. The flow of my activity supposed to JSON parse a URL, and get an array, which contains another URL. Then I want to parse this second URL again and get the new array. But I got an error when I am trying to do the second JSON parse. Here are my code what I have tried and also the error that I received:
I would really appreciate your help. Thank you very much!
private RequestQueue mQueue;
private RequestQueue mQueueSecond;
private String linkDetails;
btnParseOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JsonParse();
}
});
btnParseTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JsonParseSecond();
}
});
private void JsonParse() {
String url = link;
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray groups = response.getJSONArray("results");
if(groups.length() > 0) {
JSONObject result = groups.getJSONObject(0);
linkDetails = result.getString("link");
}
catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
private void JsonParseSecond() {
String urlDetails = linkDetails;
Log.d(TAG, "JsonParseSecond: new url to be parsed is: " + urlDetails); //Just to check that I got the new link from the first JsonParse method
JsonObjectRequest requestTwo = new JsonObjectRequest(Request.Method.GET, urlDetails, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "JsonParseSecond: Checking that the JsonParseSecond can do JsonObjectRequest with no issue");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueueTwo.add(requestTwo);
I can run the first method of JsonParse() by clicking the button of btnParseOne with no issue. Then after clicking the btnParseOne, I click btnParseTwo to check my JsonParseSecond() method. But I received the following error:
2021-07-15 12:08:20.551 12739-12739/com.example.jsonparsetest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.jsonparsetest, PID: 12739
java.lang.NullPointerException: Attempt to invoke virtual method 'com.android.volley.Request com.android.volley.RequestQueue.add(com.android.volley.Request)' on a null object reference
at com.example.jsonparsetest.MainActivity.JsonParseSecond(MainActivity.java:1666)
at com.example.jsonparsetest.MainActivity.access$4400(MainActivity.java:111)
at com.example.jsonparsetest.MainActivity$23.onClick(MainActivity.java:1593)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:174)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
In the second method JsonParseSecond() you have used
mQueueTwo.add(requestTwo);
while you declared
private RequestQueue mQueueSecond;
Also initialized request queue as
mQueueSecond = Volley.newRequestQueue(mContext);
And then replace mQueueTwo.add(requestTwo); with mQueueSecond.add(requestTwo);

Appending string at the end of url in GET method :Volley

I am working with volley library in my android app development.
I have a base url and I need to append some value at the end of the url,click here,
So, this value "ZGxb87HuJK" keeps changing dynamically in my program and need to append this value at the end of url. How to add this in params?
Use this way.
StringRequest strreq = new StringRequest(Request.Method.GET,
"https://sample.com/testing/" + Hear Your dynamic value,
new Response.Listener<String>() {
#Override
public void onResponse(String Response) {
// get response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError e) {
e.printStackTrace();
}
});
Volley.getInstance(this).addToRequestQueue(strreq);
String URL = "https://sample.com/testing/" + "dynamic value e.g ZGxb87HuJK";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
URL, null,
new Response.Listener() {
#Override
public void onResponse(JSONObject response) {
//Success Callback
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Failure Callback
}
});
// Adding the request to the queue along with a unique string tag
MyApplication.getInstance().addToRequestQueue(jsonObjectReq, "getRequest");
Change your code like this

Volley Request Sets the previous value to TextView

I am trying to understand how volley is used in android, So in my project I am querying a single name from http://uinames.com/api/?amount=1
In the app I have a button that is calling the function to make the request and then set it to the TextView. Also for debug Purposes I am logging the response from the url. On the button click the response is correctly seen in the logcat but the text is not set to the TextView until the next time the button is clicked.
Here is the code for the JsonObjectRequest
public String getName() {
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET,
URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
full_name = response.getString(name) + " " + response.getString(last);
Log.d(TAG, full_name);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(objectRequest, "");
return full_name;
}
Following is the Code from the MainActivity that calls the method getName()
mButton = (Button) findViewById(R.id.btn);
mTextView = (TextView) findViewById(R.id.text);
final RequestClass newReq = new RequestClass();
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
name = newReq.getName();
mTextView.setText(name);
}
});
Here is what happens when your function String getName() is called:
A JsonObjectRequest is constructed, and a response and error listeners are passed to the request. Note that the listeners are not executed until their corresponding events happen.
The JsonObjectRequest is added to the request queue, to be executed when a thread from the thread pool is available.
Until now the full_name variable has not been touched, and you return the last value that was assigned to it (that's why when you click the button again, you get a name in your text view).
Your request gets a response and the listener is called assigning a new value to full_name after your function has returned. that is the value that you get on the next call to getName(). . .
In general, a function like getName can not perform a network operation and return its result immediately. It either needs to block until it has the response from the server (and this is prohibited in android). Or, it can return without the result being fetched yet, and have a callback function (or a listener) that is called with the result when it is available (and this is the the general approach in the Volley library).
That means that you have to setText in your response listener. I have noticed that you have a separated class for your network requests RequestClass, to keep your design as it is, one solution would be to pass the listeners to getName() function (and all other functions that do network stuff in this class), it may look something like this:
public void getName(Response.Listener<JSONObject> responseListener,
Response.ErrorListener errorListener) {
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET,
URL, null, responseListener, errorListener);
AppController.getInstance().addToRequestQueue(objectRequest, "");
}
And in your activity, you have to pass listeners like this:
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
name = newReq.getName(
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String full_name = response.getString("name") + " " + response.getString("last");
mTextView.setText(full_name);
Log.d(TAG, full_name);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
});
As a better design, you may want to avoid passing Volley listeners from the activity (which does not have to know anything about volley), so you may want to define your own listener interface, override and pass that from the activity to your networking class (where you instantiate your Response.Listener, Response.ErrorListener and override them to call functions in your listener).
Volley library is deprecated so don't use Volley library.
The best alternative for Volley is RetroFit library.
Try like this
public void getName() {
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET,
URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
full_name = response.getString("name") + " " + response.getString("last");
runOnUiThread(new Runnable() {
#Override
public void run() {
//Your code to run in GUI thread here
mTextView.setText(full_name);
}
});
Log.d(TAG, full_name);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(objectRequest, "");
}
mButton = (Button) findViewById(R.id.btn);
mTextView = (TextView) findViewById(R.id.text);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getName();
}
});

Android: how to do a simple POST request with Volley, without expected result?

I want to send a POST request to my server, and there is no expected data for the result (just HTTP status code - standard behavior). How can I do that ?
(abstract base Request class (Volley) wants a result type)
try {
mRequest =
new XXXXXX(
Request.Method.POST,
url,
null, null,
new Response.Listener() {
#Override
public void onResponse() {
// ok
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError e) {
// ko
}
},
null
);
return mRestCoreVolley.addToRequestQueue(mRequest);
} catch (Exception e) {
// error
}
You could try something like in the code below for the response listener:
new Response.Listener<Void>() {
#Override
public void onResponse(Void response) {
}
}
I guess your code is right. You can use a String like:
RequestQueue rq = Volley.newRequestQueue(this);
StringRequest postReq = new StringRequest(Request.Method.POST,
your_url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// do nothing
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
}) ;
Hope it helps you!

How to get start with Volley in Android?

I watched the google io ,and saw volley. But I don't know how to get start with it.
I've tried to clone https://android.googlesource.com/platform/frameworks/volley , but the test project keep warn me "resource directory does not exist" .
please give me some clue!
Set up the project as a library ( Project->Properties->Android->"Is Library" ).
Then, just create the res folder in Volley project, and eclipse will build the Volley.jar !
I found this to get start with.
I write this Test Project , and import com.android.volley and com.android.volley.toolbox from the volley library. And it works ^_^
protected static final String TAG = "com.gyh.myvolleytest";
public static final String url = "http://192.168.1.108:8080/httptest/servlet/mainservlet?name=stack&age=23";
public static Response.ErrorListener createErrorListener() {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error Response code: " + error.getMessage());
}
};
}
public static Response.Listener<String> createSuccessListener() {
return new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// TODO parse response
String string = response.toString();
Log.d(TAG, "string :" + string);
}
};
}
public static Response.Listener<JSONObject> createJsonListener() {
return new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String jsonStr = response.toString();
Log.d(TAG, "jsonStr :" + jsonStr);
System.out.println(jsonStr);
}
};
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View view) {
RequestQueue queue = Volley.newRequestQueue(this);
// JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
// url, null, createJsonListener(), createErrorListener());
StringRequest request = new StringRequest(Request.Method.GET, url,
createSuccessListener(), createErrorListener());
queue.add(request);
queue.start();
}
Hope this can help ^_^

Categories

Resources