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);
Related
I am a new guy in android and trying to make a rest api call using volley.
I am getting "com.android.volley.ClientError" in my code. Can anyone help me to solve this please.
private void LoginByNet(String uID, String pSD){
String URL = "http://myipaddress:65017/api/values";
RequestQueue rq = Volley.newRequestQueue(this);
JsonObjectRequest jq = new JsonObjectRequest(
Request.Method.GET,
URL,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), "Success:"+response.toString(), Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Error:"+ error.toString(), Toast.LENGTH_SHORT).show();
userName.setText(error.toString());
}
}
);
rq.add(jq);
}
This means that the server returned a 4xx error code.
[https://github.com/google/volley/blob/d1a3d5388c79ff1a6fdb904daeff9b39d0bb7d26/src/main/java/com/android/volley/toolbox/BasicNetwork.java#L199][1]
You can get the exact error code using : #error.networkResponse.statusCode
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
The function will then send a json object onto a database using an API, but it seems that Volley.newRequestQueue(this); is a null value. it giving me this error:E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.kevin.barcodescanner, PID: 11301
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.kevin.barcodescanner.AddToCart.jsonParse(AddToCart.java:59)
at com.example.kevin.barcodescanner.MainActivity$2.onClick(MainActivity.java:49)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25885)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
public class MainActivity extends AppCompatActivity {
public static TextView resultTextView;
Button scan_btn, add_btn;
AddToCart add = new AddToCart();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultTextView = (TextView)findViewById(R.id.result_text);
scan_btn = (Button)findViewById(R.id.btn_scan);
add_btn =(Button)findViewById(R.id.add_btn);
scan_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), ScanCodeActivity.class));
}
});
add_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add.jsonParse();
}
});
}
}
public class AddToCart extends AppCompatActivity {
private RequestQueue mQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mQueue = Volley.newRequestQueue(this);
}
public void jsonParse() {
JSONObject json = new JSONObject();
try {
json.put("id","11111111111");
json.put("name","222222222222");
json.put("price","1");
} catch (Exception e) {
e.printStackTrace();
}
String url = "https://fg3qzgb2va.asdasdasdasdas-api.ap-southeast-1.amazonaws.com/sample";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, json,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.print("String Response : "+ response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
jsonObjectRequest.setTag("VACTIVITY");
mQueue.add(jsonObjectRequest);
}
}
Thing is that since AddToCart is not really an activity the oncreate methode was never really called, since there is nothing to display.
A better solution would parse context from MainActivity to AddToCart via constructor and instantiate your queu in the constructor
public class AddToCart {
private RequestQueue mQueue;
public AddToCart(Context context) {
super.onCreate(savedInstanceState);
mQueue = Volley.newRequestQueue(context);
}
public void jsonParse() {
JSONObject json = new JSONObject();
try {
json.put("id","11111111111");
json.put("name","222222222222");
json.put("price","1");
} catch (Exception e) {
e.printStackTrace();
}
String url = "https://fg3qzgb2va.asdasdasdasdas-api.ap-southeast-1.amazonaws.com/sample";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, json,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.print("String Response : "+ response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
jsonObjectRequest.setTag("VACTIVITY");
mQueue.add(jsonObjectRequest);
}
}
public void doMySearch(List<String> IDs) {
for (String Id : IDs) {
String url = "http://api.tvmaze.com/shows/" + Id + "?embed=nextepisode";
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("ONREQUEST ");
try {
String name = response.getString("name");
String airdate = response.getJSONObject("_embedded").getJSONObject("nextepisode").getString("airdate");
HashMap<String, String> episodesToDisplay = new HashMap<String, String>();
episodesToDisplay.put(name, airdate);
listOfEpisodes.add(episodesToDisplay);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
System.out.println("BEFORE ADD TO REQUEST QUEUE ");
MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
System.out.println("AFTER ADD TO REQUEST QUEUE ");
}
System.out.println("AFTER FOR LOOP ");
}
See my prints in the code, the output I get with 4 items in my IDs list is:
BEFORE ADD TO REQUEST QUEUE
AFTER ADD TO REQUEST QUEUE
BEFORE ADD TO REQUEST QUEUE
AFTER ADD TO REQUEST QUEUE
BEFORE ADD TO REQUEST QUEUE
AFTER ADD TO REQUEST QUEUE
BEFORE ADD TO REQUEST QUEUE
AFTER ADD TO REQUEST QUEUE
AFTER FOR LOOP
ONREQUEST
ONREQUEST
ONREQUEST
ONREQUEST
The point is System.out.println("AFTER FOR LOOP "); is executed before onRequest and I want it to call a function in that place which would use a list populated inside onRequest. I thought onRequest would be executed after adding items to queue but it's not. Is there any way I can make it work in the order I expect? I cannot call funtion inside onRequest since I want it to use fully populated list and onRequest is called many times at once.
You have to create a callback to it.
Like this
public interface VolleyCallback {
void onSuccess(String string);
void onFailure(VolleyError error);
}
Then when you call your doMySearch function, you pass your callback, like this:
doMySearch(ids, new VolleyCallback() {
#Override
public void onSuccess(String response) {
Log.d("Success", response);
}
#Override
public void onFailure(VolleyError error) {
Log.e("Error", "ops thats an error!");
}
});
And finally, on your doMySearch function, where you override the onResponse and onErrorResponse listener you call your callback, like this:
public void doMySearch(List<String> IDs, final VolleyCallback callback) {
for (String Id : IDs) {
String url = "http://api.tvmaze.com/shows/" + Id + "?embed=nextepisode";
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("ONREQUEST ");
callback.onSuccess("ONREQUEST");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
callback.onFailure(error);
}
});
System.out.println("BEFORE ADD TO REQUEST QUEUE ");
MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
System.out.println("AFTER ADD TO REQUEST QUEUE ");
}
System.out.println("AFTER FOR LOOP ");
}
Your code block is executed async, so you have to put your code inside the onResponse method.
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 "".