I want to retrieve comments from a Flickr photo in my Android app, and have created a JSONObjectRequest using the following code:
public void loadComments(ImageInfo photo) {
//clear the comments arraylist ready for new request
NetworkMgr.getInstance(this).commentsList.clear();
NetworkMgr netMgr = NetworkMgr.getInstance(getApplicationContext());
RequestQueue requestQueue = netMgr.requestQueue;
String id = photo.id;
String url = "https://api.flickr.com/services/rest/?method=flickr.photos.comments.getList&api_key=MY_API_KEY&format=json&nojsoncallback=1&extras=authorname,_content&photo_id=" + id;
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, responseListener, errorListener);
requestQueue.add(request);
adapter.notifyDataSetChanged();
}
The photo ID is correctly being retrieved and appended to the String url, and below I use a response listener to get authorname and _content, from each comment object:
private Response.Listener<JSONObject> responseListener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject comments = response.getJSONObject("comments");
JSONArray commentList = comments.getJSONArray("comment");
for (int i = 0; i < commentList.length(); i++) {
ImageInfo newComment = new ImageInfo();
JSONObject comment = commentList.getJSONObject(i);
newComment.authorname = comment.getString("authorname");
newComment.commentContent = comment.getString("_content");
//add data to arraylist
NetworkMgr.getInstance(DetailsActivity.this).commentsList.add(newComment);
}
} catch (JSONException ex) {
ex.printStackTrace();
}
adapter.notifyDataSetChanged();
}
};
private Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
};
However when I put this url in my browser to view the JSON data, the comment JSONObject is non-existent.
How The JSON Response Should Look <<<< How My JSON Response Looks <<<<
Does anybody know why I cannot retrieve the JSON comment object and its data?
Try this
Put this in your loop
JSONObject allvaluesJsonObject=new JSONObject();
allvaluesJsonObject=jsonArray.getJSONObject(i);
remove this ImageInfo newComment = new ImageInfo();
Related
when there is only one object, i dont have problem to retrieve variable from database
but when i want to retrive variable from only user1 or user2 the text in android doesnt appear anything.
this is my array from php code
{"users":[{"id":"5","name":"user1","updated_at":"2020-10-21 13:35:10"},{"id":"6","name":"user2","updated_at":"2020-10-21 11:29:53"}]}
and this my java code
private void getData(String name) {
String tag_string_req = "get";
ArrayList<HashMap<String, String>> list_data;
list_data = new ArrayList<HashMap<String, String>>();
StringRequest strReq = new StringRequest(Method.GET,
AppConfig.URL_GET, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("users");
for (int a = 0; a < jsonArray.length(); a++) {
JSONObject json = jsonArray.getJSONObject(a);
String pengguna = jsonObject.getString("name");
if (pengguna.contains(name)) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("updated_at", json.getString("updated_at"));
list_data.add(map);
}
update_time.setText(list_data.get(0).get("updated_at"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
});
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
my question is how to get specific JSON object based on some variable? so the text in android only show text based on user.
edit : the problem already solved by some edit in php code, so only the object fetching from database based on user.
my response in android
{"users":[{"id":"6","name":"user2","updated_at":"2020-10-21 13:35:10"}]}
the problem right now is the textview doesnt show me the value although the response already correct
You can look up to follow this :
JSONObject jsonObject = new JSONObject();
jsonObject.getJSONObject("key");
It will resolve your problem, I think.
I have an API which send me a JSON object when I send a token to the server , I use GET method and I have to send token in body, not headers, it works in postman correctly when I put token in body but I have volley server error in android studio and I entered error response.here is my codes:
ant solution???? please
private void getFreightsFromServer()
{
final String url =" https://parastoo.app/api/driver-cargo-list";
JSONObject jsonData = new JSONObject();
String token = G.getString("token");
try
{
jsonData.put("token", token);
} catch (JSONException e)
{
e.printStackTrace();
}
Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>()
{
boolean isGet = false;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onResponse(JSONObject response)
{
try
{
MyPost post = new MyPost();
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject tempJsonObject = jsonArray.getJSONObject(i);
JSONObject jsonOriginCustomer = new JSONObject(tempJsonObject.getString("origin_customer"));
post.setOriginCity(jsonOriginCustomer.getString("customerCity"));
JSONObject jsonDestinationCustomer = new JSONObject(tempJsonObject.getString("destination_customer"));
Log.d("result", jsonDestinationCustomer.getString("customerCity"));
post.setDestinationCity(jsonDestinationCustomer.getString("customerCity"));
freightsList.add(post);
// isGet = true;
adapter.notifyDataSetChanged();
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
};
Response.ErrorListener errorListener = new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getContext(), error.toString(), Toast.LENGTH_LONG).show();
Log.d("jdbvdc", error.toString());
error.printStackTrace();
}
};
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, jsonData, listener, errorListener);
Log.d("fhdhdcf",jsonData.toString());
final int socketTimeout = 100000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
request.setRetryPolicy(policy);
AppSingleton.getInstance(getContext()).addToRequestQueue(request);
}
Please show the error message you have. Also I am not sure how ok it is to send something in a body of a GET request. This answer might help you:
HTTP GET with request body
It's better to use post method for this type of request.
But still if you want to use GET method then you should have to pass token in the URL.
Below is an example
final String username = etUname.getText().toString().trim();
final String password = etPass.getText().toString().trim();
URLline = "https://demonuts.com/Demonuts/JsonTest/Tennis/loginGETrequest.php?username="+username+"&password="+password;
I managed to get results for a json rpc request, like this:
{"id":1,"jsonrpc":"2.0","result":{"channels":[{"channel":"Channel A ","channelid":2165,"label":"Channel A"},{"channel":"Channel B ","channelid":748,"label":"Channel B"} etc.
I would like to parse the reponse to an array where i can read channel,channelid and label at each iteration of a loop. but did not manage to get it.
Any help would be much appreciated.
Sorry not that experienced with programming , its al self-taught
Code for json rpc request :
String groupchannelsurl = "http://192.168.2.100:8080/jsonrpc?request={\"jsonrpc\": \"2.0\", \"method\": \"PVR.GetChannels\", \"params\": {\"channelgroupid\" : 9,\"properties\":[\"channel\"]}, \"id\": 1 }";
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, groupchannelsurl, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
// display response
Log.d("Response", response.toString());
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
queue.add(getRequest);
The Android Developer documentation is really good if you get stuck.
JSONObject -
https://developer.android.com/reference/org/json/JSONObject.html
JSONArray - https://developer.android.com/reference/org/json/JSONArray.html
#Override
public void onResponse(JSONObject response) {
JSONArray channels = response.getJSONObject("result").getJSONArray("channels");
for (int i = 0; i < channels.length(); i++) {
JSONObject channel = channels.getJSONObject(i);
String channelName = channel.getString("channel");
int channelId = channel.getInt("channelid");
String channelLabel = channel.getString("label");
// ...
}
}
Hope this helps!
You can parse JSONObject like below
private void parseJsonObject(JSONObject responseObject) throws JSONException {
String id = responseObject.getString("id");
JSONArray jsonArray = responseObject.optJSONArray("channels");
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject arrayObject = (JSONObject) jsonArray.get(i);
String channel = arrayObject.getString("channel");
String channelId = arrayObject.getString("channelid");
}
}
}
i have a problem with get json with volley library.
this is my json:
{"result":1}
the php code count rows in mysql database and show result in this json file.
the number of count is integer.
and this is my code for get this json:
private void getData () {
//url + id of row that want to count
String url = Config.DATA_URL_COUNT +"1";
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//loading.setVisibility(View.INVISIBLE);
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Toast.makeText(this,error.getMessage().toString(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response) {
int name = 0;
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.TAG_RESULT);
JSONObject collegeData = result.getJSONObject(0);
name = jsonObject.getInt(Config.JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
String count = String.valueOf(name);
rowcount_kargozarybime.setText(count); //insert result in textview
}
and this is my php code:
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$categoryid = $_GET['categoryid'];
define('HOST','144.76.10.250');
define('USER','cp21983_test');
define('PASS','*******');
define('DB','cp21983_marivanjobs');
$con = mysqli_connect(HOST,USER,PASS,DB);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"SET character_set_results=utf8,character_set_client=utf8,character_set_connection=utf8, character_set_database=utf8,character_set_server=utf8");
$sql="SELECT * FROM jobs WHERE categoryid='".$categoryid."'";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
echo json_encode(array("result"=>$rowcount));
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
}
i well be thankfull if anyone can help me.
Try using :
JSONObject respObject = new JSONObject(response);
int result = respObject.getInt("result");
This is a json object,not a json array. therefore use this code to get result count
JSONObject jsonObject = new JSONObject(response);
int count = jsonObject.getInt("result");
rowcount_kargozarybime.setText(String.valueOf(count));
How do I get the name of the actor_id in the same request, and display all the information from the table and the "name"?
SELECT permalink,actor_id FROM stream WHERE source_id=me()
then I want the name of the actor_id
I know I can use the actor_id results and get the name in a new request
SELECT name FROM user WHERE uid=actor_id
but, I need to display the permalink and the name together.
How do I get results from
https://graph.facebook.com/user_id?fields=name
Can I do a URL/https request to display the name with actor_id results I got?
You can make the multiple query using RequestBatch-
ArrayList<Request> requests = new ArrayList<Request>();
// Request-1
String streamQuery = "SELECT permalink,actor_id FROM stream WHERE source_id=me()";
Bundle args1 = new Bundle();
args1.putString("q", streamQuery);
Request request1 = new Request(session, "fql", args1, HttpMethod.GET);
request1.setCallback(new com.facebook.Request.Callback() {
#Override
public void onCompleted(Response response) {
GraphObject graphObject = response.getGraphObject();
String s = textViewResults.getText().toString();
if (graphObject != null) {
JSONObject jsonObject = graphObject.getInnerJSONObject();
try {
JSONArray array = jsonObject.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject object = (JSONObject) array.get(i);
Log.d(TAG, "permalink = "+object.get("permalink"));
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
});
requests.add(request1);
// Request-2
String userQuery = "SELECT name FROM user WHERE uid=actor_id";
Bundle args2=new Bundle();
args2.putString("q", userQuery);
Request request2 = new Request(session, "fql", args2, HttpMethod.GET);
request2.setCallback(new com.facebook.Request.Callback() {
#Override
public void onCompleted(Response response) {
GraphObject graphObject = response.getGraphObject();
String s = textViewResults.getText().toString();
if (graphObject != null) {
JSONObject jsonObject = graphObject.getInnerJSONObject();
try {
JSONArray array = jsonObject.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject object = (JSONObject) array.get(i);
Log.d(TAG, "name = "+object.get("name"));
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
});
requests.add(request2);
// Execute Batch
RequestBatch requestBatch=new RequestBatch(requests);
requestBatch.setTimeout(10000);
List<Response> responses = requestBatch.executeBatchAndWait();
Hope that helps. Good luck!
I was able to resolve the issue with this request, I got the solution from this [link]Facebook android sdk how to get the number of likes for a given page
the "id" is from the first query of the actor_id
Bundle params = new Bundle();
params.putString("id", id);
params.putString("fields", "name");
Request request = new Request(session, "search", params, HttpMethod.GET, new Request.Callback() {
public void onCompleted(Response response) { try {
JSONObject res = response.getGraphObject().getInnerJSONObject().getJSONArray("data").getJSONObject(0);
final String name = (String) res.get("name");