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));
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 have a table called hotel_review in this I have hotel_stars column and I want to display the sum of all the hotel stars in Android using Volley. I want to display the average of the hotel rating, to do this I need the sum of the column. I think I'm close but not getting the values. I'm not getting any error but I can not fetch the values as well.
my php code:
<?php
require "init.php";
header('Content-Type: application/json;charset:UTF-8');
$hotel_id = $_POST['hotel_id'];
$query = mysqli_query($con, "SELECT SUM(hotel_stars) AS 'Total' FROM hotel_review WHERE hotel_id = '".$hotel_id."';");
$row = mysqli_fetch_assoc($query);
$sum = $row['Total'];
if($query)
{
$code = "getvalue";
$data[]['Total'] = $sum;
$result = array("code"=>$code,"stars" => $data);
echo json_encode($result);
}else {
$code = "not_get";
$msg = "Try Again....";
array_push($response, array("code"=>$code,"msg"=>$msg));
//echo("Error description: " . mysqli_error($con));
header('Content-Type: application/json;charset:UTF-8');
echo json_encode($response);
// echo("Error description: " . mysqli_error($con));
}
mysqli_close($con);
?>
my android code:
public void getHotelStars()
{
StringRequest stringRequest = new StringRequest(Request.Method.POST, getStars,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String code = jsonObject.getString("code");
if (code.equals("not_get")) {
Toast.makeText(hotel_reviews.this, "error", Toast.LENGTH_SHORT).show();
} else {
String totalStars = jsonObject.getString("stars");
// String totalCount = jsonObject.getString("total_stars");
Toast.makeText(hotel_reviews.this, ""+totalStars, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(hotel_reviews.this, "error", Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("hotel_id",HotelId);
//params.put("division",EmployeeDivision);
return params;
}
};MySingleton.getInstance(hotel_reviews.this).addToRequestque(stringRequest);
}
Im getting the proper hotel_id in params.put so no error is there in fetching id.
use it like this after you fire your query:
while ($row = mysqli_fetch_assoc($query)) {
$sum=$row["Total"];
echo $sum;
}
after your query and see if your total is there in $sum. Thereafter you can start using that anywhere.
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 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();