Removing linebreak from php json output - php

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);

Related

How to insert list of string dates into mysql using php?

i want to insert list of dates between two dates in mysql using php
and im using asynctask to POST data in php.
first i get the two date string and get the list of dates from the 2 date
List<Date> dates = getDates(mDate, mDate2);
private static List<Date> getDates(String dateString1, String dateString2)
{
ArrayList<Date> dates = new ArrayList<Date>();
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = null;
Date date2 = null;
try {
date1 = df1 .parse(dateString1);
date2 = df1 .parse(dateString2);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
while(!cal1.after(cal2))
{
dates.add(cal1.getTime());
cal1.add(Calendar.DATE, 1);
}
return dates;
}
And get the other pamaraters
String customername = getPpname();
String customerroom = getRrname();
String customerid = getRrid();
and create a container to pass multiple parameter in asycntask
private static class MYTASK {
List<Date> dates;
String customername;
String customerroom;
String customerid;
MYTASK(List<Date> dates, String customername, String customerroom, String customerid) {
this.dates = dates;
this.customername = customername;
this.customerroom = customerroom;
this.customerid = customerid;
}
}
then execute the asyctank
MYTASK params = new MYTASK(dates, customername, customerroom,customerid);
JSONTask_ListDates jsonTaskListDates = new JSONTask_ListDates();
jsonTaskListDates.execute(params);
and here is my asynctask
class JSONTask_ListDates extends AsyncTask<MYTASK, Void, Void> {
#Override
protected void onPreExecute() {
/* rlllogin.setVisibility(View.VISIBLE);*/
}
#Override
protected void doInBackground(MYTASK... params) {
String urlreserve = "http://alar-regulations.000webhostapp.com/reservation_insert_date.php";
String id = params[3].customerid;
String rname = params[1].customerroom;
String pname = params[2].customername;
List<Date> dates = params[0].dates;
try {
URL url = new URL(urlreserve);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
//new
httpURLConnection.setDoInput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("id", "UTF-8")+"="+URLEncoder.encode(id, "UTF-8")+"&"
+URLEncoder.encode("rname", "UTF-8")+"="+URLEncoder.encode(rname, "UTF-8")+"&"
+URLEncoder.encode("pname", "UTF-8")+"="+URLEncoder.encode(pname, "UTF-8")+"&"
+URLEncoder.encode("dates", "UTF-8")+"="+URLEncoder.encode(dates, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
//new
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(IS, "iso-8859-1"));
String response ="";
String line = "";
while ((line = bufferedReader.readLine()) !=null) {
response+=line;
}
bufferedReader.close();
IS.close();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
/*pDialog.dismiss();*/
/* rlllogin.setVisibility(View.GONE);*/
Intent intent = new Intent(Booking.this, Reservation_List.class);
startActivity(intent);
Booking.this.finish();
/* dialog2.dismiss();*/
}
}
there is an error in my asynctask the list dates = params[0].dates cant pass in URLEncoder it says
wrong first argument type found java.util.list required java.lang string
and in my php
<?php
require "connection.php";
$res_rname= $_POST["rname"];
$res_per_name= $_POST["pname"];
$res_id= $_POST["id"];
$dates= $_POST["dates"];
$sql_query = "Insert into res_event_table ( res_id, res_check_in_out,
res_room_name, res_name) values ( '$res_id','$val', '$res_rname',
'$res_per_name')";
if($dates>0)
{
foreach($dates as $val){
$result = mysqli_query($conn ,$sql_query);
if (!$result){
echo "failed" .mysqli_connect_error;
}else{
echo "Reservation Success";
}
}
}
?>
i haven't try the php because there is still wrong with my java.
please help me im disperate
If you give more informating question it will be easy to help you. If you hav problem with ArrayList Strings, I can recommend to transform it to just String. Pass it as a String, and after split it in String[] again.

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?

How to sync app data when server add or update the record

I have developed an Android app which gets data from MySQL, but the problem is that when insert, update & delete happen so it loads all the data from server, and I want to sync only that record which is insert or update.
This is my code:
#Override
protected void onHandleIntent(Intent intent) {
try {
//Activity activity = (Activity)context;
Log.d("st", String.valueOf(System.currentTimeMillis()));
DataBaseHelper dataBaseHelper = new DataBaseHelper(context);
dataBaseHelper.createDataBase();
dataBaseHelper.openDataBase();
HttpClient httpclient = new DefaultHttpClient();
//utils.getdata("Userid");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy hh:mm a");
Date date = new Date();
String link = "http://ec2-52-4-106-227.compute-1.amazonaws.com/capalinoappaws/apis/getProcurementDaily.php?currentDate="+simpleDateFormat.format(date);
link = link.replace(" ","%20");
HttpPost httppost = new HttpPost(link);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost,
responseHandler);
Log.i("Response", "Response : " + response);
if (!dataBaseHelper.sqliteDataBase.isOpen())
dataBaseHelper.openDataBase();
dataBaseHelper.delete("ProcurementMaster");
JSONArray jsonarray = new JSONArray(response);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobj = jsonarray.getJSONObject(i);
String ProcurementID = jsonobj.getString("ProcurementID");
String ProcurementEPIN = jsonobj.getString("ProcurementEPIN");
String ProcurementSource = jsonobj.getString("ProcurementSource");
String ProcurementAgencyID = jsonobj.getString("ProcurementAgencyID");
/*ProcurementAgencyID = ProcurementAgencyID.replace(")","");
ProcurementAgencyID = ProcurementAgencyID.replace("(","");*/
ProcurementAgencyID = ProcurementAgencyID.replace("'","\\u0027");
String ProcurementTypeIDP = jsonobj.getString("ProcurementTypeIDP");
String ProcurementTitle = jsonobj.getString("ProcurementTitle");
//Log.d("ProcurementTitle",ProcurementTitle);
/*
ProcurementTitle = ProcurementTitle.replace(")","");
ProcurementTitle = ProcurementTitle.replace("(","");*/
ProcurementTitle = ProcurementTitle.replace("'","''");
String ProcurementShortDescription = jsonobj.getString("ProcurementShortDescription");
/*ProcurementShortDescription = ProcurementShortDescription.replace(")","");
ProcurementShortDescription = ProcurementShortDescription.replace("(","");*/
ProcurementShortDescription = ProcurementShortDescription.replace("'","''");
String ProcurementLongDescription = jsonobj.getString("ProcurementLongDescription");
/*ProcurementLongDescription = ProcurementLongDescription.replace(")","");
ProcurementLongDescription = ProcurementLongDescription.replace("(","");*/
ProcurementLongDescription = ProcurementLongDescription.replace("'","''");
String ProcurementProposalDeadline = jsonobj.getString("ProcurementProposalDeadline");
String ProcurementPreConferenceDate = jsonobj.getString("ProcurementPreConferenceDate");
String ProcurementQuestionDeadline = jsonobj.getString("ProcurementQuestionDeadline");
String ProcurementAgencyURL = jsonobj.getString("ProcurementAgencyURL");
String ProcurementDocument1URL = jsonobj.getString("ProcurementDocument1URL");
String ProcurementDocument2URL = jsonobj.getString("ProcurementDocument2URL");
String ProcurementDocument3URL = jsonobj.getString("ProcurementDocument3URL");
String ProcurementDocument4URL = jsonobj.getString("ProcurementDocument4URL");
String ProcurementDocument5URL = jsonobj.getString("ProcurementDocument5URL");
String ProcurementAddedDate = jsonobj.getString("ProcurementAddedDate");
String ProcurementContractValueID = jsonobj.getString("ProcurementContractValueID");
String Status = jsonobj.getString("Status");
String LASTEDITEDUSERNAME = jsonobj.getString("LASTEDITEDUSERNAME");
String PDFPath = jsonobj.getString("PDFPath");
boolean isInserted = dataBaseHelper.InsertProcurementMaster(new ProcMaster(Integer.valueOf(ProcurementID), ProcurementEPIN, ProcurementSource,
ProcurementAgencyID, ProcurementTypeIDP, ProcurementTitle,ProcurementShortDescription,ProcurementLongDescription,ProcurementProposalDeadline,
ProcurementPreConferenceDate,ProcurementQuestionDeadline,ProcurementAgencyURL,ProcurementDocument1URL,ProcurementDocument2URL,ProcurementDocument3URL,
ProcurementDocument4URL,ProcurementDocument5URL,ProcurementAddedDate,ProcurementContractValueID,Status,LASTEDITEDUSERNAME,PDFPath));
//Log.d("InsertProcurementMaster", "Inserted");
//list_data.add(new ListData(image, contentShortDescription, ContentRelevantDateTime));
//isinserted = dataBaseHelper.InsertUserProcurmentTracking(been);
}
Log.d("et", String.valueOf(System.currentTimeMillis()));
} catch (Exception e) {
e.printStackTrace();
}
}
try implementing sockets on client and server side.
https://socket.io/

how to store json response value into edittext in android

Hi In this getting reg_no array value coming from database I want display that value into EditText without clicking any button.
Can any one please help me how to display the EditText value
class file
String RegNo = DatabaseUtility.executeQueryPhp("reg","");
System.out.print(RegNo);
try
{
JSONArray JA = new JSONArray(RegNo);
reg_no = new String[JA.length()];
for(int i=0;i<JA.length();i++)
{
reg_no[i] = JA.getJSONObject(i).getString("reg_no");
}
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
Simply do something like this :
String value = "";
for(int i=0;i<JA.length();i++)
{
reg_no[i] = JA.getJSONObject(i).getString("reg_no");
value+=reg_no[i];
}
myEditText.setText(value);
For showing every single value in new EditText
for(int i=0;i<JA.length();i++)
{
reg_no[i] = JA.getJSONObject(i).getString("reg_no");
EditText edit = new EditText(getApplicationContext());
edit.setText(reg_no[i]);
}
Showing All Values in Single EditText
EditText edit = new EditText(getApplicationContext());
for(int i=0;i<JA.length();i++)
{
reg_no[i] = JA.getJSONObject(i).getString("reg_no");
edit.append(reg_no[i]);
}
Try this..
for (int i = 0; i < JA.length(); i++)
{
JSONObject jsonObject = JA.getJSONObject(i);
reg_no[i] = jsonObject.getInt("reg_no");
editText[i].setText(reg_no[i].toString);
}
you can also use StringBuilder class
StringBuilder sb = new StringBuilder();
String RegNo = DatabaseUtility.executeQueryPhp("reg","");
System.out.print(RegNo);
try
{
JSONArray JA = new JSONArray(RegNo);
reg_no = new String[JA.length()];
for(int i=0;i<JA.length();i++)
{
reg_no[i] = JA.getJSONObject(i).getString("reg_no");
sb.append(reg_no[i]);
}
myEditText.setText(sb.toString());
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}

How to put http response into array in Android

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();
}

Categories