Get php array with with android - php

I've an error that occur when I try to fix it but it doesn't fix.
JSONArray application_band =jsonResponse.getJSONArray("banda");
String [] list = new String[application_band.length()];
for(int i = 0; i<application_band.length(); i++){
list[i] = application_band.getString(i);
}
And this when I create the intent:
if (hurado_section ==1) {
Intent intent = new Intent(LoginActivity.this, CategoryOneActivity.class);
intent.putExtra("hurado_name", hurado_name);
intent.putExtra("hurado_id", hurado_id);
intent.putExtra("hurado_section", hurado_section);
intent.putExtra("application_band",list);
LoginActivity.this.startActivity(intent);
}
Error:
07-20 16:47:10.781 27808-27808/com.example.cursoft.scoringsystemseu W/System.err: org.json.JSONException: No value for banda
What could be the problem?

Related

in android jsonarray cannot be converted in jsonobject

The script fetches data from phpmyadmin but android studio cause this error
of type org.json.Jsonarray cannot be converted to jsonobject
my code android
code
Actually you are getting JSONArray instead of JSONObject from your server. So, You have to parse the array first then you can get object from it.
JSONArray jsonArray = new JSONArray(response);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = jsonObject.getString("id");
String m_e = jsonObject.getString("M_E");
}

org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject while receiving valid JSON response

I am trying to read the valid JSON response but getting the error String cannot be converted to JSONObject don't know why.?
android code
String sendParam = sendParams[0];
byte[] sendParamsByte = sendParam.getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(sendParamsByte.length));
conn.setDoOutput(true);
conn.getOutputStream().write(sendParamsByte);
InputStream responseInputStream = conn.getInputStream();
StringBuffer responseStringBuffer = new StringBuffer();
byte[] byteContainer = new byte[1024];
for (int i; (i = responseInputStream.read(byteContainer)) != -1; ) {
responseStringBuffer.append(new String(byteContainer, 0, i));
}
JSONObject response = new JSONObject(responseStringBuffer.toString());
My JSON Response -
{
"firstOne":"XXXXXXXXXX",
"secOne":"XXXXXXXXXXXXXXXXXX",
"thrOne":"XXXXXXXXXXXXX",
"final":"XXXXXXXXXXXXXXX"
}
error log -
org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
06-02 12:09:13.975 2310-3800/X.x W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
06-02 12:09:13.975 2310-3800/X.x W/System.err: at org.json.JSONObject.<init>(JSONObject.java:159)
06-02 12:09:13.975 2310-3800/X.x W/System.err: at org.json.JSONObject.<init>(JSONObject.java:172)
Any idea..?
Try this
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
}
you can get JSONObject from sb.toString().trim().
good luck
conn.setRequestProperty("Content-Length","application/json;charset=UTF-8");
Change to this.

JsonObject from PHP to Android + security

Hi everyone I have this php output.
//fetching all the rows from the query
$row = $stmt->fetchAll();
//output to json
die(json_encode($row));
[{"u_id":"8","id":"8","name":"test1","location_long":"10.01475","location_lati":"53.57823","description":"loo\nlol","date":"2014-11-21","time":"18:00:00","date_created":"2014-11-20","date_updated":"0000-00-00"},
{"u_id":"8","id":"9","name":"test9","location_long":"10.01475","location_lati":"53.57823","description":"test9\n","date":"2014-11-21","time":"19:00:00","date_created":"2014-11-20","date_updated":"0000-00-00"},
{"u_id":"8","id":"10","name":"test10","location_long":"10.01475","location_lati":"53.57823","description":"lol","date":"2014-11-22","time":"19:00:00","date_created":"2014-11-20","date_updated":"0000-00-00"},
{"u_id":"8","id":"11","name":"lol","location_long":"10.01475","location_lati":"53.57823","description":"","date":"2014-11-24","time":"18:00:00","date_created":"2014-11-20","date_updated":"0000-00-00"}]
Now I want get each item with its value into my listview item
Code:
JSONObject json = jsonParser.makeHttpRequest(
EVENTS_URL, "POST", params);
JSONArray jsonArray = new JSONArray(json);
for(int i = 0; i < jsonArray.length();i++)
{
adapter.add(new DataProvider(own_event,
jsonArray.getJSONObject(i).getString("description"),
jsonArray.getJSONObject(i).getString("name"),
jsonArray.getJSONObject(i).getString("date"),
jsonArray.getJSONObject(i).getString("time"),
jsonArray.getJSONObject(i).getDouble("location_long"),
jsonArray.getJSONObject(i).getDouble("location_lati"),
jsonArray.getJSONObject(i).getInt("id")));
}
Now I get this error:
Error parsing data org.json.JSONException: Value [] of type
org.json.JSONArray cannot be converted to JSONObject
In the line where I create the JSONArray jsonArray.
I never worked with json before so, is there a better way to parse the data from my php file to android, and a more secure way in doing that?
Server response is came in JSONArray so no need to convert in JSONObject just build JSONArray from server response and return as JSONArray instead JSONObject from makeHttpRequest :
JSONArray jsonArray = jsonParser.makeHttpRequest(EVENTS_URL, "POST", params);

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.

trying to get json object from php to android

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.

Categories