How to put http response into array in Android - php

I‘m trying to use Http response to get data from PHP server but the tricky thing in here that I get the response as a one string. I want to put the response into array. The response originally contains many queries that I retrieved from MySQL. I am grateful for any help.

You should encode your response on the server side using a data interchange format such as XML or JSON.
Then you can easily parse it on the client side.
Android has great support for both, though JSON might be a bit easier.
If your data structure is very simple - e.g a list of words - you could use CSV (Comma Separated Value) and String.split() to get an array:
String[] words = response.split(",");
JSON example (string array)
[
"The quick brown fox jumps over the lazy dog",
"Jackdaws love my big sphinx of quartz",
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut"
]
JSONArray array = new JSONArray(response);
String[] sentences = new String[array.length()];
for (int i = 0, i < array.length(); i++){
sentences[i] = array.getString(i);
}

Try this...It will help you to store your response in array.
try
{
URL url = new URL("http:/xx.xxx.xxx.x/sample.php");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(in));
String x = "";
String total = "";
int i=0;
ArrayList<String> content = new ArrayList();
while((x = r.readLine()) != null)
{
content.add(x);
}
in.close();
r.close();
}
catch(Exception e)
{
e.printStackTrace();
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
You can convert the arrayList to array.
String ar[]= content.toArray(new String[content.size()]);

a better way would be to make your php webservice send data in JSON. then recieve it as a and parse the JSON response for data you need. I recommend JSON because it is more lighter than xml which will improve performance reducing bandwidth consumption.

Try to create a php scripts that return a JSON data this is the example of retrieving data and putting them into array.
<?php
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = mysql_query("SELECT * FROM tbl_products") or die(mysql_error());
if (mysql_num_rows($result) > 0) {
$response["product"] = array();
while ($row = mysql_fetch_array($result)) {
$product = array();
$product["products_id"] = $row["table_id"];
$product["products_price"] = $row["transaction_no"];
$product['products_name'] = $row["table_total_price"];
array_push($response["product"], $product);
}
$response["success"] = 1;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No products found";
echo json_encode($response);
}
?>
and this one is for android:
JSONObject json = jParser.getJSONFromUrl(NAME_OF_URL);
Log.d("All Product List: ", json.toString());
try {
int success = json.getInt("success");
if (success == 1) {
products = json.getJSONArray("product");
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
String id =c.getString("products_id");
String price =c.getString("products_price");
String name = c.getString("products_name");
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}

Related

Mongodb and Android link using php

I currently handle MongoDB with PHP.
I am trying to process data on Android using that value.
PHP:
public function Find($collection, $query = null, $fields = null) {
/* init */
$this->mClient = new MongoClient(...);
$this->mDBName = $dbName;
$this->mDB = $this->mClient->{$this->mDBName};
if(!isset($this->mDB)) {
// TODO
return;
}
/* find query */
$coll = $this->mDB->{$collection};
if(isset($query)) {
if(isset($fields)) $cursor = $coll->find($query, $fields);
else $cursor = $coll->find($query);
} else {
$cursor = $coll->find();
}
return json_encode(iterator_to_array($cursor, false));
}
ANDROID:
// Get String From PHP
// ex) [{"_id":{"$id":"59ad4d2425b572b7124be684"},"name":"\uacf5\ud3ec"},{"_id":{"$id":"59ad4d3625b572b7124be69a"},"name":"SF"}]
String result = getHttpData(getInstance().mStrUrl, data);
// In this part, data processing is done
List<DBObject> arr = new ArrayList<DBObject>();
//JSONObject json = new JSONObject(result);
JSONArray jsonArray = new JSONArray(result);
int len = jsonArray.length();
for (int i=0;i<len;i++){
String json = jsonArray.get(i).toString();
//Object o = com.mongodb.util.JSON.parse(result);
Object o = com.mongodb.util.JSON.parse(json);
DBObject dbObj = (DBObject) o;
arr.add(dbObj);
}
In the above case, referring to "_ id" will return BasicDBObject. It is necessary to receive an ObjectID.
Likewise for child document "_id" should be ObjectID.
HOW?

JSON Error: Unterminated object on valid json text

I'm having a problem with JSON. On my webspace I'm hosting a php file which converts a mysql request into JSON Format. Then a android device reads that JSON File and processes the data (temperature and humidity) in a graph.
PHP-Code:
<?php
include("connect.php");
// SQL Query abschicken
$result = mysql_query("SELECT * FROM classpidb ORDER BY ID DESC LIMIT 1000");
//Schleife bis alle Eintragungen in Array gespeichert
$listenArray["Liste"] = array();
while($row = mysql_fetch_array($result)) {
$listeneintrag = array();
$listeneintrag["ID"] = $row["ID"];
$listeneintrag["Time"] = $row["Time"];
$listeneintrag["Temp"] = $row["Temp"];
$listeneintrag["Humi"] = $row["Humi"];
array_push($listenArray["Liste"], $listeneintrag);
}
//Ausgabe im JSON Format
$listenArray["Status"] = ["0","Select erfolgreich"];
echo json_encode($listenArray);
//Verbindung trennen.
mysql_close($verbindung);
?>
JSON-Parsing in Android (result is the JSON-File read as string):
JSONObject jsonErgebnis = new JSONObject(result);
JSONArray statusArray = jsonErgebnis.getJSONArray("Status");
int status = statusArray.getInt(0);
if(status == 0)
{
JSONArray datenArray = jsonErgebnis.getJSONArray("Liste");
//for (int i = 0; i < datenArray.length(); i++) {
for (int i = datenArray.length() - 1; i >= 0; i--) {
JSONObject einzelsatz = datenArray.getJSONObject(i);
...
firstdatatemp.addXValue(einzelsatz.getString("Time"));
firstdatatemp.addEntry(new Entry((float) einzelsatz.getDouble("Temp"), set.getEntryCount()), 0);
...
// add a new x-value first
firstdatahumi.addXValue(einzelsatz.getString("Time"));
firstdatahumi.addEntry(new Entry((float) einzelsatz.getDouble("Humi"), set.getEntryCount()), 0);
}
}
If i use SELECT * FROM classpidb ORDER BY ID DESC LIMIT 100 it works fine. If i use 1000 instead of 100 I always get "Unterminated object at character ..." error. CodeBeautifier says my JSON text is valid.
Found the solution to the problem:
Android didn't finish reading the full php response, so I replaced the buggy code for Reading the response with
BufferedReader r = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}

How to know that a new record is retrieved into a JSONArray?

I want to post a JSONArray from Android to a webserver ; the JSONArray contains records from a SQLite database table from Android :
JSONObject parameters = new JSONObject();
parameters.put("jsonArray", new JSONArray(Arrays.asList(makeJSON())));
parameters.put("type", "Android");
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty( "Content-Type", "application/json" );
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(parameters.toString());
writer.close();
out.close();
the method makeJSON :
if(mCur != null && mCur.moveToFirst()){ // method makeJSON() retrieving database records
do{
try{
JSONObject jObj = new JSONObject();
String notificationDateFor = mCur.getString(mCur.getColumnIndexOrThrow("NotificationDateFor"));
String typeNotification = mCur.getString(mCur.getColumnIndexOrThrow("TypeNotification"));
String dob = mCur.getString(mCur.getColumnIndexOrThrow("DOB"));
String friendsName = mCur.getString(mCur.getColumnIndexOrThrow("FriendsName"));
String imageUri = mCur.getString(mCur.getColumnIndexOrThrow("imageUri"));
jObj.put("NotificationDateFor", notificationDateFor);
jObj.put("DOB", dob);
jObj.put("TypeNotification", typeNotification);
jObj.put("FriendsName", friendsName);
jObj.put("imageUri", imageUri);
jArr.put(jObj);
}catch(Exception e){
System.out.println("Exception: "+e);
}
}while(mCur.moveToNext());
}
return jArr;
PHP script :
$jsonArray = stripslashes($_POST['jsonArray']);
foreach ($jsonArray as $obj) {
... // how to know if a new record is being treated ?
}
Inside the PHP script how to know if I am working on a new record ? Because I want to insert/update each record from the JSONArray.
See if the data is being posted by echoing it out, like this:
$jsonArray = stripslashes($_POST['jsonArray']);
foreach ($jsonArray as $k=>$v) {
echo $k . ' - ' . $v . '<br>';
}

Removing linebreak from php json output

After hours of search and effort i couldn't fix it.So finally seeking your help.
My Json
[
{
"notice_id": "2",
"n_header": "Class Test",
"n_subject": "Class Test from 15-jan",
"n_datetime": "2014-01-05 09:00:00",
"noticenum": "NISTA1",
"n_body": "Dear Students Class test 1 will be held from january 15. \nDetaled Notice will be notified further with timetable",
"n_removeby": "2014-01-05",
"n_givenby": "7",
"nconcerned_id": "1",
"nconcerned_batch": "2010",
"nconcerned_degree": "BTECH",
"nconcerned_section": " "
},
{
"notice_id": "3",
"n_header": "Comprehensive Viva",
"n_subject": "Comprehensive viva from 20-feb",
"n_datetime": "2014-02-05 10:00:00",
"noticenum": "NISTB1",
"n_body": "Students under me for comprehensive\n viva are hereby informed to clear their viva before 20th feb. After 20 feb no viva would be entertained under me.",
"n_removeby": "2014-02-21",
"n_givenby": "1",
"nconcerned_id": "4",
"nconcerned_batch": "2010",
"nconcerned_degree": "BTECH",
"nconcerned_section": "IT"
}
]
However when i see it in my browser it looks like :
a http://www.4shared.com/download/D1UQsmEbce/json.png?lgfp=3000
As you see it breaks up undesirably.As a result when i parse it in my android app i get an exception value <br of type java.lang.String can't be converted to JSONArray which i believe because of this linebreak issue only.
what I have tried
I tried many things including preg_replace,str_replace etc in order to escape \r\n or <br> etc but couldn't get it work for me.Finally i have a function which i am using like this :
function parse($text) {
$text = str_replace("\r\n", "\n", $text);
$text = str_replace("\r", "\n", $text);
$text = trim( preg_replace( '/\s+/', '<br/>', $text));
// JSON requires new line characters be escaped
$text = str_replace("\n", "\\n", $text);
return $text;
}
I am writing a query to retrieve data from postgresql database.Hence running the following loop.
for ($i=0; $i<$rows; $i++)
{
$row = pg_fetch_array($result, $i, PGSQL_ASSOC);
$json['notice_id'] = trim(strip_tags($row['notice_id']));
$json['n_header'] = trim(strip_tags($row['n_header']));
$json['n_subject'] = trim(strip_tags($row['n_subject']));
$json['n_datetime'] = trim(strip_tags($row['n_datetime']));
$json['noticenum'] = trim(strip_tags($row['noticenum']));
$json['n_body'] = trim(strip_tags($row['n_body']));
$json['n_removeby']= trim(strip_tags($row['n_removeby']));
$json['n_givenby'] = trim(strip_tags($row['n_givenby']));
$json['nconcerned_id'] = trim(strip_tags($row['nconcerned_id']));
$json['notice_id'] = trim(strip_tags($row['notice_id']));
$json['nconcerned_batch'] = trim(strip_tags($row['nconcerned_batch']));
$json['nconcerned_degree'] = trim(strip_tags($row['nconcerned_degree']));
$json['nconcerned_section'] = trim(strip_tags($row['nconcerned_section']));
parse($json['notice_id']);
parse($json['n_header']);
parse($json['n_subject']);
parse($json['n_datetime']);
parse($json['noticenum']);
parse($json['n_removeby']);
parse($json['n_givenby']);
parse($json['nconcerned_id']);
parse($json['notice_id']);
parse($json['nconcerned_batch']);
parse($json['nconcerned_degree']);
parse($json['nconcerned_section']);
$data[] = $json;
}
$h = json_encode($data);
echo $h ;
}
Question
How could i get rid of this issue and get a neat json which won't result in any jsonexception?
Note:
I checked carefully many times for linebreaks there.But there are no linebreaks (\n) etc in my database.
Edited Code
$data = array ();
for ($i=0; $i<$rows; $i++)
{
$row = pg_fetch_array($result, $i, PGSQL_ASSOC);
$json['notice_id'] = $row['notice_id'];
$json['n_header'] = $row['n_header'];
$json['n_subject'] = $row['n_subject'];
$json['n_datetime'] = $row['n_datetime'];
$json['noticenum'] = $row['noticenum'];
$json['n_body'] = $row['n_body'];
$json['n_removeby']= $row['n_removeby'];
$json['n_givenby'] = $row['n_givenby'];
$json['nconcerned_id'] = $row['nconcerned_id'];
$json['notice_id'] = $row['notice_id'];
$json['nconcerned_batch'] = $row['nconcerned_batch'];
$json['nconcerned_degree'] = $row['nconcerned_degree'];
$json['nconcerned_section'] = $row['nconcerned_section'];
$json['notice_id']=parse($json['notice_id']);
$json['n_header']=parse($json['n_header']);
$json['n_subject']= parse($json['n_subject']);
$json['n_datetime']=parse($json['n_datetime']);
$json['noticenum']=parse($json['noticenum']);
$json['n_removeby']=parse($json['n_removeby']);
$json['n_givenby']=parse($json['n_givenby']);
$json['nconcerned_id']=parse($json['nconcerned_id']);
$json['notice_id']=parse($json['notice_id']);
$json['nconcerned_batch']=parse($json['nconcerned_batch']);
$json['nconcerned_degree']=parse($json['nconcerned_degree']);
$json['nconcerned_section']=parse($json['nconcerned_section']);
$data[] = $json;
}
$h = json_encode($data);
echo $h ;
output in browser now
a http://www.4shared.com/download/C4lUKR-1ba/json1.png?lgfp=3000
Here is another json which shows up neatly in my browser.
a http://www.4shared.com/download/tNWhDbfuce/ajson.png?lgfp=3000
It's strange why the other one not having a linebreak!
Weird Solution
I am not sure what solved this problem.But when i changed the url which i was using to execute my php file and it worked for me.Please refer here
You're misinterpreting what your browser is displaying. Remember that JSON is essentially plain text, but your browser is trying to display it as HTML. \n chars are NOT honored by HTML-mode displays, and they will wrap the text at the first appropriate space character. JSON can perfectly well keep \n chars inside its strings without any trouble.
Most likely your <br> error is coming from the <br> insertion you're doing in your preg_replace call, because there are NO <br> tags in the original JSON. In other words, you're causing the very error you're trying to fix, by trying to fix the error which wouldn't exist if you weren't trying to fix it.
OK based on your inputs i did complete working example depending on some answer here at stack overflow , Parse JSON from URLon android.
PHP Part
i have your data so i did example like this
<?php
$row = array (
"notice_id" => "2",
"n_header" => "Class Test",
"n_subject" => "Class Test from 15-jan",
"n_datetime" => "2014-01-05 09:00:00",
"noticenum" => "NISTA1",
"n_body" => "Dear Students Class test 1 will be held from january 15. \nDetaled Notice will be notified further with timetable",
"n_removeby" => "2014-01-05",
"n_givenby" => "7",
"nconcerned_id" => "1",
"nconcerned_batch" => "2010",
"nconcerned_degree" => "BTECH",
"nconcerned_section" => " ");
$row2 = array ("notice_id" => "3",
"n_header" => "Comprehensive Viva",
"n_subject" => "Comprehensive viva from 20-feb",
"n_datetime" => "2014-02-05 10:00:00",
"noticenum" => "NISTB1",
"n_body" => "Students under me for comprehensive\n viva are hereby informed to clear their viva before 20th feb. After 20 feb no viva would be entertained under me.",
"n_removeby" => "2014-02-21",
"n_givenby" => "1",
"nconcerned_id" => "4",
"nconcerned_batch" => "2010",
"nconcerned_degree" => "BTECH",
"nconcerned_section" => "IT");
$data [] =$row;
$data [] = $row2;
echo json_encode ($data);
Android Part
class MyAsyncTask extends AsyncTask<String, String, Void> {
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream inputStream = null;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Downloading your data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
MyAsyncTask.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... params) {
String url_select = "http://192.168.10.206/test.php";
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
// Set up HTTP post
// HttpClient is more then less deprecated. Need to change to URLConnection
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// Read content & Log
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncodingException", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
}
return null;
} // protected Void doInBackground(String... params)
protected void onPostExecute(Void v) {
//parse JSON data
try {
JSONArray jArray = new JSONArray(result);
for(int i=0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
String name = jObject.getString("n_body");
String tab1_text = jObject.getString("n_removeby");
int active = jObject.getInt("notice_id");
Log.i("NAME",name);
Log.i("REMOVE",tab1_text);
} // End Loop
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
} // protected void onPostExecute(Void v)
} //class MyAsyncTask extends AsyncTask<String, String, Void>
don't forget to call MyAsync task some where like that.
MyAsyncTask task = new MyAsyncTask();
task.execute();
And this works very fine,so please review your android code where i believe the issue is from their,Hope this help you.
You just have to add new lines before decoding it and it will work 100%:
$text = str_replace("\r\n", "\n", $text);

iterate through json matrix php android

Hi I have a script here
http://myprocity.com/android/fetchthecity.php
That returns a array of arrays. I want to parse through this in Android and store each value.
The code I have right now is this, maybe this is flawed? I'm getting nothing to show up
public static void refreshFeed(Activity act){
ActionEngine.swamiOn = false;
FetchTheCityTask f = new FetchTheCityTask(act);
f.execute();
try {
if (f.get() != null) {
JSONArray feedArr = new JSONArray();
feedArr = json.getJSONArray("data");
ArrayList<UserRecord> items = new ArrayList<UserRecord>();
for(int i = 0; i < feedArr.length(); i++){
for(int j = 0; j < feedArr.getJSONArray(i).length(); j++) {
JSONObject row = feedArr.getJSONArray(i).getJSONObject(j);
String item = row.getString("Item");
String descp = row.getString("Description");
String pic = row.getString("PicPath");
String time = row.getString("Time");
String donatedby = row.getString("DonatedBy");
String ebase = row.getString("Ebase");
String cond = row.getString("Condition");
String loc = row.getString("Location");
items.add(new UserRecord(item,descp,pic,time,donatedby,
ebase,cond,loc));
}
}
TheCityFragment.feedArea.setAdapter(new UserItemAdapter(act,
android.R.layout.simple_list_item_1, items));
That returns a array of arrays.
I don't think so,
I see from your file "Array of Objects" so your code doesn't work.
Try to do something:
JSONArray json = new JSONArray(resultAsString);
// ...
for(int i=0;i<json.length();i++){
//...
JSONObject row = json.getJSONObject(j);
String item = row.getString("Item");
String descp = row.getString("Description");
String pic = row.getString("PicPath");
String time = row.getString("Time");
String donatedby = row.getString("DonatedBy");
String ebase = row.getString("Ebase");
String cond = row.getString("Condition");
String loc = row.getString("Location");
//..
}
Hope it will help you
Your JSON result, parsed on : http://bodurov.com/jsonformatter/ shows this result :
I'd recommend to change the json result to this one :
{"data" : [yourjsonArray]}
So you need to encapsulate the JSON_ARRAY inside a JSON_OBJECT, so you can use getJSONArray("data") to get the array.
JSONObject jObject = new JSONObject(resultstringhere); //f.get() ?
JSONArray jArray = jObject.getJSONArray("data");
Hope this helps,
Reid

Categories