i am trying to parse an array from my php script to my android app.
my android code
public void func4(View view)throws Exception
{final String TAG_CONTACTS = "response";
AsyncHttpClient client = new AsyncHttpClient();
RequestParams rp = new RequestParams();
rp.put("pLat", "SELECT officer_name FROM iwmp_officer");
client.post("http://10.0.2.2/conc3.php", rp, new AsyncHttpResponseHandler() {
public final void onSuccess(String response) {
// handle your response here
ArrayList<String> User_List = new ArrayList<String>();
try
{
JSONArray jArray = new JSONArray(response.toString());
// JSONObject jsonObject = new JSONObject(response);
for (int i = 0; i < jArray.length(); i++)
{
JSONObject json_data = jArray.getJSONObject(i);
User_List.add(json_data.getString(TAG_CONTACTS));
String s = User_List.get(0).toString();
tx.setText(s);
}
}
catch (Exception e)
{
tx.setText((CharSequence) e);
}
}
#Override
public void onFailure(Throwable e, String response) {
// something went wrong
tx.setText(response);
}
});
}
now i am sending or ECHOing a jSON array from my php code, which is being read into the response object of string type.
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
echo json_encode($cars);
exit;
?>
now error i am getting is org.json.JSONException: Value Volvo at 0 of type java.lang.String cannot be converted to JSONObject
i think thar onSuccess func accept string parameter and i m sending json as a parameter to it.. thats what causing problem please help.
Try Like this
JSONObject json = jsonParser.makeHttpRequest(url_get_contact, "GET", params);
Log.d("All Groups: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
groups = json.getJSONArray(TAG_GROUP);
System.out.println("Result Success+++"+groups);
for (int i = 0; i < groups.length();i++) {
JSONObject c = groups.getJSONObject(i);
String name = c.getString(TAG_CONTACTS);
System.out.println("Checking ::"+name);
namelist.add(name); // namelist is ur arraylist
}
}else {
showAlert();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
Let me know ur problem solved or not...
Answer found, i guess i was trying to convert an already String converted object from json into string again.
well to be precise i ust deleted JSONObject json_data = jArray.getJSONObject(i);
and it worked for me. Now i am able to save all values in my array.
Related
I am not familiar with Android Coding, I have to convert this code to PHP to get data from this API URL. Can you please help me to write this code in PHP?
public void onClick(View view) {
((InputMethodManager) InputData.this.getSystemService("input_method")).hideSoftInputFromWindow(view.getWindowToken(), 0);
String charSequence = InputData.this.xyzView.getText().toString();
String obj = InputData.this.inputOne.getText().toString();
String obj2 = InputData.this.inputTwo.getText().toString();
if (obj.equalsIgnoreCase("") || Integer.parseInt(obj) != 0) {
if (obj2.equalsIgnoreCase("")) {
obj2 = "0";
}
if (obj.equalsIgnoreCase("")) {
InputData InputData = InputData.this;
Toast.makeText(InputData, InputData.getString(R.string.err_msg_fileNo), 1).show();
return;
}
InputData InputData2 = InputData.this;
JSONObject jSONObject = new JSONObject();
try {
jSONObject.put("xyz", charSequence);
jSONObject.put("inputOne", obj);
jSONObject.put("inputTwo", obj2);
jSONObject.put("reqFrom", "0123");
jSONObject.put("password", "MjMEJJ6SXpj");
} catch (JSONException e) {
e.printStackTrace();
}
InputData2.URL = "https://apiurl.com/information/service/dataservide/";
Log.d("ur;", InputData.this.URL);
new C0328e(InputData.this, (C0324a) null).execute(new String[]{InputData.this.URL, jSONObject.toString()});
return;
}
Toast.makeText(InputData.this, "Invalid Input", 1).show();
Also give suggestions if you have any. Thank you so much, Friends.
I am trying to get json Array from url in android using volley but it is showing following error
com.android.volley.ParseError: org.json.JSONException: Value of type java.lang.String cannot be converted to JSONArray
that means i am receiving html from url.
how can i receive data in json format from url so that i can parse using jsonObject or jsonArray in android
My android code is
RequestQueue queue = Volley.newRequestQueue(getContext());
JsonArrayRequest request = new JsonArrayRequest(Method.GET, URL,null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response ) {
Toast.makeText(getContext(), response, Toast.LENGTH_SHORT).show();
Log.i("My success",""+response.toString());
try {
for (int i = 0; i <= response.length(); i++) {
JSONObject silver_rate_values = response.getJSONObject(i);
String Silver_Rate = silver_rate_values.getString("silver_rate");
Log.v("SilverRate", "silverRate value is" + Silver_Rate);
}
}catch (JSONException e) {
e.printStackTrace();
Log.e("Silver rate", "Json parsing error: " + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "my error :"+error, Toast.LENGTH_LONG).show();
Log.i("My error",""+error);
}
}){
};
My php code is
$sql = "SELECT * FROM `user_info` \n"
. "ORDER BY `customer_info`.`updatedTime` DESC LIMIT 1";
$result = mysqli_query( $con,$sql );
if(! $result ) {
die('Could not get data: ' . mysql_error());
}
//print values to screen
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$a = $row['a'];
$b = $row['b'];
$c = $row['c'];
$data[] = $row;
}
header('Content-type: application/json');
$json=json_encode(array("Values" => $data));
echo $json;
?>
</body>
My php output is
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
{"Values":[{"a":"8888","b":"9999","c"7777"}]} </body>
</html>
If I remove header from php code then the output is
{"Values":[{"a":"8888","b":"9999","c"7777"}]}
Then also I am getting same error from Android side
just Add this line you can achive result
$jsonfinal = json_encode(json_decode($json), JSON_PRETTY_PRINT);
echo $jsonfinal ;
now i am changing my code and using StringRequest instead of JsonArrayRequest. below is the code
RequestQueue queue = Volley.newRequestQueue(getContext());
StringRequest request = new StringRequest(Method.GET, URL_Silver, new Response.Listener<String>() {
#Override
public void onResponse(String response ) {
Log.i("My success",""+response);
try {
JSONObject obj = new JSONObject(response);
JSONArray array = obj.getJSONArray("silverRateValues");
for (int i = 0; i <= array.length(); i++) {
JSONObject silver_rate_values = array.getJSONObject(i);
String Silver_Rate = silver_rate_values.getString("silver_rate");
Log.v("SilverRate", "silverRate value is" + Silver_Rate);
}
}catch (JSONException e) {
e.printStackTrace();
Log.e("Silver rate", "Json parsing error: " + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "my error :"+error, Toast.LENGTH_LONG).show();
Log.i("My error",""+error);
}
}){
};
queue.add(request);
But still getting the same error...however now response is called and it is...
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
{"Values":[{"a":"8888","b":"9999","c":"7777"}]} </body>
</html>
and the error is
org.json.JSONException: Value of type java.lang.String cannot be converted to JSONObject
I'm trying to retrieve the total number of correct answers answered by the students from different countries.
I'm using JSON to link to my php then to my database. But i seems to can't read the spaces in between words. For example, the country name is "Czech Republic" in the database. However when i echo, it shows me "Czech".
The $country in the php code is from the android studio, where i sent a url link Config.LEADERSHIPBOARD_URL_ME + country; to get connected to the database.
This is my php code:
<?php
$country = $_GET['country'];
require "conn.php";
$sql_mcq = "SELECT * FROM mcqparticipator WHERE country = '".$country."'";
$r_mcq = mysqli_query($conn,$sql_mcq);
$result = array();
$mcqCount = 0;
if($r_mcq)
{
while($row = mysqli_fetch_array($r_mcq))
{
if(($row['correctAns'] == "1"))
{
$mcqCount++;
}
}
array_push($result,array(
"McqCount"=>$mcqCount,
"Country"=>$country));
echo json_encode(array("result"=>$result));
}
else
{
echo "No connection";
}
$conn->close();
?>
And this is my code from android studio:
// Description: This method will generate a url and send a request
// This method will call showJSON() method to start sending the response
private void getData(){
loading = ProgressDialog.show(getActivity(), "Please wait...","Fetching", false, false);
url = Config.LEADERSHIPBOARD_URL_ME + country;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
Toast.makeText(getActivity(), "Country in studio: " + country, Toast.LENGTH_LONG).show();
Toast.makeText(getActivity(), "Country in database: " + dcountry, Toast.LENGTH_LONG).show();
Toast.makeText(getActivity(), "Mcq count: " + McqCount, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(getActivity(),"No existing question", Toast.LENGTH_LONG).show();
Toast.makeText(getActivity(), error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue= Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
// Description: This method will generate a response using JSON via php.
// Retreive and compare the participants answer with the correct answer
public void showJSON(String response) {
try{
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
McqCount = collegeData.getString(Config.MCQ_COUNT);
dcountry = collegeData.getString("Country");
} catch (JSONException e) {
e.printStackTrace();
}
}
Appreciate if someone could help me, thank you!
Here´s the JSON that my php file delivers:
[{"id":"408","punktezahl":"15","name":"testname","email":"hsksjs","datum":"24.01.14 17:11","wohnort":"Vdhdhs","newsletter":"J"}]
When I try to access the JSON Object like this
public void connect(){
System.out.println("%%%%%%%%%%%%%%%%%1" );
Thread t = new Thread(){
#Override
public void run() {
try {
System.out.println("%%%%%%%%%%%%%%%%%2" );
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(params, 0);
HttpClient httpClient = new DefaultHttpClient(params);
String urlString = "http://url";
//prepare the HTTP GET call
HttpGet httpget = new HttpGet(urlString);
//get the response entity
HttpEntity entity = httpClient.execute(httpget).getEntity();
System.out.println("%%%%%%%%%%%%%%%%%3" );
if (entity != null) {
//get the response content as a string
String response = EntityUtils.toString(entity);
//consume the entity
entity.consumeContent();
// When HttpClient instance is no longer needed, shut down the connection manager to ensure immediate deallocation of all system resources
httpClient.getConnectionManager().shutdown();
//return the JSON response
JSONObject parentObject = new JSONObject(response);
JSONObject userDetails = parentObject.getJSONObject("output");
String name = userDetails.getString("name");
System.out.println("HEEEEEEEEEEEEEEEEEEEEEEEEEEEE" + name);
}
}catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
I get the following error:
01-24 18:18:21.746: W/System.err(20673): org.json.JSONException: Value [{"id":"408","datum":"24.01.14 17:11","punktezahl":"15","email":"hsksjs","newsletter":"J","wohnort":"Vdhdhs","name":"testname"}] of type org.json.JSONArray cannot be converted to JSONObject
01-24 18:18:21.746: W/System.err(20673): at org.json.JSON.typeMismatch(JSON.java:111)
01-24 18:18:21.746: W/System.err(20673): at org.json.JSONObject.<init>(JSONObject.java:159)
01-24 18:18:21.746: W/System.err(20673): at org.json.JSONObject.<init>(JSONObject.java:172)
01-24 18:18:21.746: W/System.err(20673): at com.wuestenfest.jagdenwilli.Highscore_zeigen$1.run(Highscore_zeigen.java:82)
Where´s my mistake?
Your response is a JSONArray not a JSOnObject.
So change
JSONObject parentObject = new JSONObject(response);
to
JSONArray jsonarray = new JSONArray(response);
Your JSON
[ // json array node
{ // jsson onject npode
"id": "408",
"punktezahl": "15",
"name": "testname",
"email": "hsksjs",
"datum": "24.01.14 17:11",
"wohnort": "Vdhdhs",
"newsletter": "J"
}
]
I do not see any json object output either in the above json. So
JSONObject userDetails = parentObject.getJSONObject("output");
is also wrong.
Parsing
JSONArray jsonarray = new JSONArray(response);
JSONObject jb =(JSONObject) jsonarray.getJSONObject(0);
String name= jb.getString("name");
The problem is just as the exception describes: you are trying to parse your response object into a JSONObject, but it is actually a JSONArray (as seen by the square brackets). In stead, parse it as a JSONArray, and get the first element from the array, which would be your desired JSONObject.
In my Android app, I'm trying to communicate with a web server that holds randomly-generated fake usernames and scores.
{ scores: [
{
un: "Feltricapulta",
sc: "143"
},
{
un: "Henroid",
sc: "120"
},
{
un: "ieteubmospta",
sc: "70"
},
{
un: "pmbotesteuai",
sc: "67"
},
{
un: "epesomiubtat",
sc: "65"
}
] }
The code in the PHP file looks like this:
<?php
include ('connecttomysql.php');
$command = 'SELECT un, sc FROM xmlscores ORDER BY sc DESC';
$execute_command = mysql_query($command);
echo '{ "scores": ';
while ($table_row = mysql_fetch_assoc($execute_command))
{
$jsonArray [] = $table_row;
}
echo json_encode($jsonArray);
echo '}'
?>
I've called this .php URL in Android using the generic HttpGet method. The output of the json data prints to the stacktrace and provides me with the "Cannot convert from Object to Array" error.
Looking at the PHP file and the json output, is there anything noticeably wrong with my codes or the output? I can't figure it out.
"Cannot convert from Object to Array"
means you are trying to convert response string to JSONArray. but Current String Contains JSONObject as root element instead of JSONArray. so convert it to JSONObject as:
JSONObject json=new JSONObject(<Server response string here>);
// get scores JSONArray from json
JSONArray jsonscoresarray=json.getJSONArray("scores");
...
// Implementation of Json array should go like this.
#Override
public void fromJSON(Object json) throws JSONException {
JSONObject jsonObject = new JSONObject((String) json);
JSONArray jsonArray = jsonObject.getJSONArray("scores");
mScores = new ArrayList<Score>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjct = (JSONObject)jsonArray.getJSONObject(i);
Score object = new Score();
object.fromJSON(jsonObjct);
mScores.add(object);
}
}