Attempting to load specific api through twitch headers. This Code has always worked in the past in fact still works but is pulling another user that i have replaced.
Tried to use android volley url to string, tried Variable
tried to clear cache in code, in app, and in device
this appears to be related to the volley's cache but i cant seem to clear it.
I dont feel it is api related otherwise wouldn't pull the old information either. or at least wouldn't work after cache was cleared.
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
queue.getCache().clear();
String url = "https://api.twitch.tv/helix/users?login=Twitchuser";
// Request a string response from the provided URL.
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(com.android.volley.Request.Method.GET, url, null, new
Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject = response;
JSONArray JA = jsonObject.getJSONArray("data");
for (int i = 0; i < response.length(); i++) {
JSONObject object = JA.getJSONObject(i);
String bio = object.getString("description");
mTextView2.append(bio);
}
JSONObject jsonObject2 = response;
JSONArray JA2 = jsonObject2.getJSONArray("data");
for (int i = 0; i < response.length(); i++) {
JSONObject object = JA2.getJSONObject(i);
String name =
object.getString("display_name");
mTextView.append(name);
}
JSONObject jsonObject3 = response;
JSONArray JA3 = jsonObject3.getJSONArray("data");
for (int i = 0; i < response.length(); i++) {
JSONObject object = JA3.getJSONObject(i);
String Image =
object.getString("profile_image_url");
new
DownLoadImageTask(mImageView).execute(Image);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
mTextView.append("Welcome Guest");
Log.e("VOLLEY", "ERROR");
}
})
{ //this is the part, that adds the header to the request
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Client-ID", "Client id");
params.put("content-type", "application/json");
return params;
}
};
MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
shoud get twitch user name, description and logo and display to card within the android app. it does, but for the old user entered.
Related
I know this question has been asked a few times and i have tried all the solutions however, nothing seems to work. My method:
public static LocationGeoData getLocationGeoData(Location location){
RequestQueue requestQueue = Volley.newRequestQueue(MyApplication.getAppContext());
Date dateNow = new Date();
SimpleDateFormat fmt = new SimpleDateFormat("yyyy.MM.dd");
String url = "MYCORRECTURL";
Log.d("geoData", "In getGeoData " + url); // this is called and logs
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("geoData", "inside the response");// this never gets called
try {
JSONObject jsonObject = response.getJSONObject("data");
for(int i = 0; i <jsonObject.length(); i++){
JSONObject heading = jsonObject;
if(heading.getString("field-value").equals("field-value")){
JSONObject totIntensity = heading.getJSONObject("total-intensity");
JSONObject declination = heading.getJSONObject("declination");
JSONObject inclination = heading.getJSONObject("inclination");
int totalIntensity = totIntensity.getInt("value");
double declinationValue = declination.getDouble("value");
double inclinationValue = inclination.getDouble("value");
locationGeoData = new LocationGeoData(totalIntensity, declinationValue, inclinationValue);
}
}
} catch (JSONException e) {
Log.d("geoData", "Error recorded");//never called
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("geoData", "Error recorded");// never called
}
});
requestQueue.add(request);
return locationGeoData;
}
The second Log message inside the response never gets called, i get no error messages, my url works and i can see the JsonOBject in the browser when tested, but the response is never called in my method. Can anyone advise me what i am doing wrong?
could anyone help me set up parsing for this JSON data file.
I want to get each train departure. The structure is departures -> all - > 0,1,2,3 etc... Thanks
I am trying to get certain strings such as time, destination and platform and then display it in a list for each departure.
private void jsonParse()
{
String url = key;
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("REST", response.toString());
try {
JSONArray jsonArray= response.getJSONArray("departures");
Log.d("REST", jsonArray.toString());
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject departure = jsonArray.getJSONObject(i);
JSONObject all = departure.getJSONObject("all");
String Mode = all.getString("Mode");
TextViewResult.append(Mode + "\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
Queue.add(request);
}
If I have understood correctly, you are getting no results, right?
The JSON objects (0, 1, ...) are children of "all", which is a JSONArray, not a JSONObject. And "departures" seems to be a JSONObject and not a JSONArray. You should:
Get "departures" as a JSONObject out of the loop.
Get "all" as a JSONArray from teh previous one, as it is a child of "departures", and do this also out of the loop.
Iterate over the previous JSONArray in the loop, obtaining the JSONObject's which represent one departure each.
So, the block inside the try would look like this:
//logging omitted
JSONObject departuresJSONObj = response.getJSONObject("departures");
JSONArray allJSONArr = departuresJSONObj.getJSONArray("all");
JSONObject departureJSONObj;
String mode;
for (Object departureObj : allJSONArr) {
if (departureObj instanceof JSONObject) {
departureJSONObj = (JSONObject) departureObj;
mode = departureJSONObj.getString("mode"); //mode is lowercase in the JSON
TextViewResult.append(mode + "\n");
}
}
Hope this helps.
Question1: How to get response value in onResponse function.
Question2: I create cauHoiArrayList. when I check and get cauHoiArrayList values in onResponse function => it worked. But if I check and get cauHoiArrayList values in GETDATA function ==> it did not work. How to I get cauHoiArrayList values.
Thanks you,
This is my code details:
public void GetCauHoi(String url) {
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(
Request.Method.POST,
url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
cauHoiArrayList = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
_id = object.getInt("_ID");
cauhoi = object.getString("CauHoi");
tenmh = object.getString("TenMH");
tenmonhoc = object.getString("TenMonHoc");
dapan_a = object.getString("DapAn_A");
dapan_b = object.getString("DapAn_B");
dapan_c = object.getString("DapAn_C");
dapan_d = object.getString("DapAn_D");
dapandung = object.getString("DapAnDung");
hinhanh = object.getString("HinhAnh");
dokho = object.getInt("DoKho");
cauHoiArrayList.add(new CauHoi(_id, cauhoi, tenmh, tenmonhoc, dapan_a, dapan_b, dapan_c, dapan_d, dapandung, hinhanh, dokho));
}
Log.d("tag",""+cauHoiArrayList.get(0).getCauHoi());
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ScreenSlideActivity.this, ""+error, Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("laytenmonhocc", "" + laytenmonhoc);
params.put("laydokhoc", "" + laydokho);
return params;
}
};
requestQueue.add(stringRequest);
}
public ArrayList<CauHoi> GETDATA (){
return cauHoiArrayList;
}
Volley requests are asynchronous. You must be calling GETDATA by time when response is not arrived yet. You need to sure call GETGATA when you have response. Only OnResponse method is guarantee that response is present.
This question may look like a duplicate(it is NOT), but I am stuck with this JSONException error:
Value die of type java.lang.String cannot be converted to JSONArray.
I'm using JsonArrayRequest of Volley to get jsonarray from a server. My JsonArrayRequest is throwing the above error, as i want to post a string to the server and receive jsonarray as a response. Below is my code:
JsonArrayRequest jsonReq = new JsonArrayRequest(Request.Method.POST,
URL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject JO = response.getJSONObject(i);
GetterSetter getterSetter = new GetterSetter();
getterSetter.setName(JO.getString("name"));
getterSetter.setNumber(JO.getString("number"));
getterSetter.setDate(JO.getString("date"));
myList.add(getterSetter);
} catch (JSONException e) {
e.printStackTrace();
}
}
myAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("myKey", myValue);
return params;
}
};
MySingleton.getInstance().addToRequestQueue(jsonReq);
}
The PHP file is working properly and it is passing json string to android.
The error is happening somewhere within onResponse block. The same block works clean when using StringRequest instead of JsonArrayRequest.
Any idea what exactly is causing this error? Any help or guidance is much appreciated.
* I'm new in Android Volley and the way it works.
EDIT
This is a format/syntax of the url response:
[
{"name":"test",
"number":"123",
"date":"2017-08-22"
},
{"name":"test1",
"number":"1234",
"date":"2017-08-23"
}
]
Try using StringRequest and then create your own JSONArray from the response string:
new JSONArray(response);
You can find example StringRequest from the documentation:
Sending a Simple Request
I am creating class which should send JSONArrayRequest using volley with specific params, then find mysql rows which equals these params and send it back. I wrote simple mysql function which receive POST params and Java method which send and receive JSONObjects. But it isn't working and I receive nothing.
This is my PHP file called details.php. It receive parameters from my Android App and send back an array.
require_once __DIR__ . '/db_connect.php'
$db = new DB_CONNECT();
$path= $_POST["path"];
$result = mysql_query("SELECT * FROM modx_ms2_product_files WHERE path = $path") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$json_response = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product ["file"] = $row["file"];
// push single product into final response array
array_push($json_response, $product);
}
// echoing JSON response
echo json_encode($json_response);
$conn->close();
}
This is my method getArray(), which send request and receive response:
public void getarray() {
String path = "1578/";
final String URL = "http://myurl.io/details.php";
HashMap<String, String> params = new HashMap<String, String>();
params.put("path", path);
JsonArrayRequest customarray = new JsonArrayRequest(Request.Method.POST,URL,new JSONObject(params),new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length() > 0) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject Obj = response.getJSONObject(i);
pics pic = new pics();
pic.setFile(Obj.getString("file"));
Log.i("cmon", Obj.getString("file"));
pics.add(pic);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(customarray);
}
This is my modx_ms2_product_files table:
http://i.imgur.com/yl1f7Ze.png
http://i.imgur.com/9V6PrBU.png
Have you tried using StringRequest? For some reason when i used JsonArrayRequest i didn't get any response back from the server. If you decide to create a StringRequest you could convert your response to a JSONArray like this:
StringRequest get = new StringRequest(Method.POST, URL, new Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray myArray = new JSONArray(response);
for(int i = 0; i < myArray.length(); i++)
{
JSONObject jObj = myArray.getJSONObject(i);
// get your data here
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Then of course add your request to the request queue.