Why I can't getting json in android? - php

I am having problem in getting one dimensional JSON please guide me where either the problem is in my JSON or in my code?
JSON:
{
"data": {
"id": "S000010",
"name": "ZS Solutions",
"email": "zswebs#gmail.com",
"phone": "051-1234567",
"address": "p.o.box 123",
"about": "im the company\r\nHAhahhaa"
}
}
Android activity JSON retrieval code:
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// TODO Auto-generated method stub
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("abc.php?Id="+id+"");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse hresponse = httpclient.execute(httppost);
HttpEntity entity = hresponse.getEntity();
is = entity.getContent();
String result=co(is);
JSONObject json=new JSONObject(result);
JSONArray a= json.getJSONArray(data);
for (int i = 0; i <= a.length(); i++) {
json = a.getJSONObject(i);
String cname=json.getString("name");
String cemail=json.getString("email");
String cphone=json.getString("phone");
String caddress=json.getString("address");
String cabout=json.getString("about");
Log.w("DATA ","NAME "+cname+"E-mail "+cemail+"Phone "+cphone+"ADDRESS"+caddress+"ABOUT"+cabout);
}
}
catch(Exception e){}

JSONArray a= json.getJSONArray(data); <-- this causing the Exception as
data is not a json Array, instead , it is a JSONObject
Your code should be
JSONObject json=new JSONObject(result);
JSONObject jsonobj=json.getJSONObject("data");
String cname=jsonobj.getString("name");
String cemail=jsonobj.getString("email");
String cphone=jsonobj.getString("phone");
String caddress=jsonobj.getString("address");
String cabout=jsonobj.getString("about");

Related

php server parse simple string using JSON to Android client

Hi i am quite new in Android client php server. I follow some tutorial for post and response variable by JSON but this reponse error. Value of type java.lang.String cannot be converted to JSONObject.
The JSON post is success but the response is error.
Android code:
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost("http://192.168.1.1/databastest/login.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
// Create a JSON object from the request response
JSONObject jsonObject = new JSONObject(result);
//Retrieve the data from the JSON object
resultLoging = jsonObject.getString("ResultArray");
}catch (Exception e){
Log.e("ClientServerDemo", "Error:", e);
exception = e;
}
return true;
}
#Override
protected void onPostExecute(Boolean valid){
//Update the UI
Toast.makeText(mContext, resultLoging, Toast.LENGTH_LONG).show();
if(exception != null){
Log.i("Error",exception.getMessage());
Toast.makeText(mContext, exception.getMessage(), Toast.LENGTH_LONG).show();
}
}
php code
mysqli_query($con,"INSERT INTO usersacc
(phone, password) VALUES('$pho', '$pass')");
#Build the result array (Assign keys to the values)
$result_data = array(
'ResultArray' => 'success',
);
#Output the JSON data
echo json_encode($result_data);
The insert is successful but the result not done.
Replace this your code with this may work.Get the response from server as Object not as String.
Object result = EntityUtils.toString(entity);
JSONObject jsonObject = new JSONObject(result.toString());
resultLoging = jsonObject.getString("ResultArray");

Receiving JSONObject in PHP

I am sending JSONObject to the server using below code. But I am unable to receive it in server side using PHP . Can anyone please guide me how to receive it.
public void sendStatus(JSONObject object) {
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
HttpClient httpclient = new DefaultHttpClient(myParams);
String jsonString = object.toString();
try {
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Content-type", "application/json");
StringEntity se = new StringEntity(jsonString);
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String temp = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
I have already done it using name value pair using following code
$datastring = trim($headers['name']);
But as in the above code I am only getting the JSONObject but not any tag. So please anyone can help me or provide me any useful link then I will be grateful.
My JSONObject format is as belos=w
{
"user_id": "123456",
"Objects": [
{
"name": "AAA"
},
{
"name": "BBB"
},
{
"name": "CCC"
},
{
"name": "DDD"
}
]
}
To send the JSON as string from the Android device you can send it as a POST param:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("json_string", jsonString));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
or if you want to send it as a header:
httppost.addHeader("json_string", jsonString)
However, a header has a maximum length so I'd recommend sending it as POST params
In order to work with a JSON object in PHP, you must decode it first into a associative array doing the following
$jsonAsArray = json_decode($jsonAsString, true)
Afterward, you'll be able to access JSON properties like:
$jsonAsArray['user_id'] // 123456
$jsonAsArray['Objects'][1]['name'] // BBB

Can´t convert JSON to JSONObject

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.

Error sending parameters to php

when connecting android to php sometimes parameters not sent.
user=i.getExtras().getString("user");
params.add(new BasicNameValuePair("user",user));
// getting JSON string from URL
json = jParser.makeHttpRequest(url_orders, "GET", params);
result obtained based on empty user.
This worked for me try this :
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://URL.com.php");
postParameters.add(new BasicNameValuePair("param1", value1));
postParameters.add(new BasicNameValuePair("param2", value2));
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent())
.toString()

Cannot receiving JSON data from app

Seems Android app sends the JSON Object without problems but when i receive i get a :
"Notice: undefined index"
The Code that sends the Object is here :
public void sendJson( String name1, String name2 ) throws JSONException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://example.com/JSON_FOLDER/JSON2/parseData.php");
HttpResponse response;
JSONObject json = new JSONObject();
try {
json.put("name1", name1);
json.put("name2", name2);
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.getParams().setParameter("json", json); // new code
//Execute HTTP POST request
httppost.setEntity(se);
response = httpclient.execute(httppost);
if( response != null ) {
str = inputStreamToString(response.getEntity().getContent()).toString();
Log.i("DATA", "Data send== " + str );
}
} catch ( ClientProtocolException e ) {
e.printStackTrace();
} catch ( IOException e ) {
e.printStackTrace();
}
}
On the Server side :
$json = $_POST['name1'];
$decoded = json_decode($json, TRUE);
and i got the undefined index notice.
Edit - revising my answer:
It appears you are sending a single parameter called json that contains 'name1' and 'name2' as the data.
Something like this should work: On the PHP side you need to decode the JSON first:
$json = json_decode($_POST['json']);
then you can access name1 and name2:
$name1 = $json['name1'];
$name2 = $json['name2'];
If you still get errors, I suggest printing out the $_POST and $_GET objects and see how your data is being sent. Then you will know how to access it.
Update:
the result you're getting array(0) { } means PHP did not get any parameters (GET or POST) from your request. You might try a different android example like this one:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://example.com/JSON_FOLDER/JSON2/parseData.php");
post.setHeader("Content-type", "application/json");
post.setHeader("Accept", "application/json");
JSONObject json = new JSONObject();
json.put("name1", name1);
json.put("name2", name2);
post.setEntity(new StringEntity(json.toString(), "UTF-8"));
HttpResponse response = client.execute(post);
if( response != null ) {
str = inputStreamToString(response.getEntity().getContent()).toString();
Log.i("DATA", "Data send== " + str );
}
Reference Article

Categories