JSON Parsing to Android using TableLayout or ListView - php

<?php
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,"qstatslite")or die("error");
$q = mysqli_query($con,"SELECT * FROM queue_stats ORDER BY queue_stats_id DESC LIMIT 20");
$return_arr = array();
while ($row = mysqli_fetch_array($q)) {
$row_array['queue_stats_id'] = $row['queue_stats_id'];
$row_array['datetime'] = $row['datetime'];
$row_array['qname'] = $row['qname'];
$row_array['qagent'] = $row['qagent'];
$row_array['qevent'] = $row['qevent'];
$row_array['info1'] = $row['info1'];
$row_array['info2'] = $row['info2'];
$row_array['info3'] = $row['info3'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
?>
Output:
[{"queue_stats_id":"198191","datetime":"2016-06-16 17:32:32","qname":"5","qagent":"50","qevent":"7","info1":"2","info2":"91","info3":"1"},{"queue_stats_id":"198190","datetime":"2016-06-16 17:31:01","qname":"5","qagent":"50","qevent":"10","info1":"2","info2":"1466069459.6496","info3":"1"},{"queue_stats_id":"198188","datetime":"2016-06-16 16:28:41","qname":"5","qagent":"53","qevent":"8","info1":"2","info2":"113","info3":"1"},{"queue_stats_id":"198187","datetime":"2016-06-16 16:26:48","qname":"5","qagent":"53","qevent":"10","info1":"2","info2":"1466065606.6445","info3":"1"},{"queue_stats_id":"198185","datetime":"2016-06-16 15:47:25","qname":"5","qagent":"50","qevent":"7","info1":"4","info2":"454","info3":"1"},{"queue_stats_id":"198183","datetime":"2016-06-16 15:39:51","qname":"5","qagent":"50","qevent":"10","info1":"4","info2":"1466062787.6382","info3":"3"},{"queue_stats_id":"198179","datetime":"2016-06-16 15:27:45","qname":"5","qagent":"50","qevent":"8","info1":"5","info2":"339","info3":"1"},{"queue_stats_id":"198178","datetime":"2016-06-16 15:22:06","qname":"5","qagent":"50","qevent":"10","info1":"5","info2":"1466061721.6337","info3":"4"},{"queue_stats_id":"198176","datetime":"2016-06-16 15:18:16","qname":"5","qagent":"53","qevent":"7","info1":"2","info2":"50","info3":"1"},{"queue_stats_id":"198175","datetime":"2016-06-16 15:17:26","qname":"5","qagent":"53","qevent":"10","info1":"2","info2":"1466061444.6325","info3":"1"},{"queue_stats_id":"198173","datetime":"2016-06-16 15:14:06","qname":"5","qagent":"50","qevent":"7","info1":"5","info2":"60","info3":"1"},{"queue_stats_id":"198172","datetime":"2016-06-16 15:13:06","qname":"5","qagent":"50","qevent":"10","info1":"5","info2":"1466061181.6318","info3":"4"},{"queue_stats_id":"198170","datetime":"2016-06-16 14:52:52","qname":"5","qagent":"53","qevent":"7","info1":"3","info2":"50","info3":"1"},{"queue_stats_id":"198169","datetime":"2016-06-16 14:52:02","qname":"5","qagent":"53","qevent":"10","info1":"3","info2":"1466059919.6275","info3":"3"},{"queue_stats_id":"198167","datetime":"2016-06-16 14:49:50","qname":"5","qagent":"28","qevent":"1","info1":"1","info2":"1","info3":"2"},{"queue_stats_id":"198165","datetime":"2016-06-16 14:25:44","qname":"5","qagent":"53","qevent":"7","info1":"47","info2":"162","info3":"1"},{"queue_stats_id":"198164","datetime":"2016-06-16 14:23:02","qname":"5","qagent":"53","qevent":"10","info1":"47","info2":"1466058176.6227","info3":"5"},{"queue_stats_id":"198163","datetime":"2016-06-16 14:22:51","qname":"5","qagent":"53","qevent":"0","info1":"15000","info2":"","info3":""},{"queue_stats_id":"198162","datetime":"2016-06-16 14:22:35","qname":"5","qagent":"50","qevent":"0","info1":"0","info2":"","info3":""},{"queue_stats_id":"198161","datetime":"2016-06-16 14:22:30","qname":"5","qagent":"53","qevent":"0","info1":"15000","info2":"","info3":""}]
Hi, I have this php/json codes..
can someone teach me how to display this JSON to android using TableLayout or in Listview?

use the following snippet to parse the JsonArray.
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String queue_stats_i = jsonobject.getString("queue_stats_i");
String datetime = jsonobject.getString("datetime");
String qname = jsonobject.getString("qname");
String qagent = jsonobject.getString("qagent");
String qevent = jsonobject.getString("qevent");
String info1 = jsonobject.getString("info1");
String info2 = jsonobject.getString("info2");
String info3 = jsonobject.getString("info3");
}
Hope it help

First: parse the json.
Second: create item layout and adapter for listView.
You can see here: listView

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?

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/

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 read json array in php

i am trying to read my android-data in php and insert it into two different tables (one table with common data and one table with every item in array). Inserting the common data into the orders table works fine, the array data does not.
Here is my android-code with my basicNameValuePairs:
ArrayList<ShoppingCardArticle> shoppingCardArticles = UsingSharedPrefs.getShoppingCard();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
TextView time = (TextView)findViewById(R.id.textView1);
String stringTime = time.getText().toString();
int amount = shoppingCardArticles.size();
String sAmount = Integer.toString(amount);
double fullprice = 0;
for(int a=0;a<shoppingCardArticles.size();a++) {
double price = shoppingCardArticles.get(a).getArticlePrice();
int quant = shoppingCardArticles.get(a).getArticleQuantity();
price = price * quant;
fullprice = fullprice + price;
}
String sFullprice = Double.toString(fullprice);
nameValuePairs.add(new BasicNameValuePair("fullprice", sFullprice));
nameValuePairs.add(new BasicNameValuePair("amount", sAmount));
nameValuePairs.add(new BasicNameValuePair("time", stringTime));
for(int i = 0; i<shoppingCardArticles.size(); i++) {
String proid = Integer.toString(shoppingCardArticles.get(i).getArticleId());
String proquan = Integer.toString(shoppingCardArticles.get(i).getArticleQuantity());
nameValuePairs.add(new BasicNameValuePair("proid[]", proid));
nameValuePairs.add(new BasicNameValuePair("proquan[]", proquan));
}
JSONParser jsonParser = new JSONParser();
JSONObject json = jsonParser.makeHttpRequest(url_create_product, "POST", nameValuePairs);
return null;
And this is my php-code:
$lastIdSql = "SELECT orderID FROM orders ORDER BY orderID DESC LIMIT 1";
$lastID = mysqli_query( $mysqli, $lastIdSql );
if ( ! $lastID ) {
#die(#mysqli_error());
}
$lastIDi = mysqli_fetch_array($lastID);
$lastIDii = $lastIDi['orderID'];
$ordDynID = $lastIDii + 1;
$fullprice = $_POST['fullprice'];
$amount = $_POST['amount'];
$time = $_POST['time'];
$queryOrd = "INSERT INTO orders (userID, fullprice, orderTime, amount, ordDynID) VALUES ('1', '$ordFullPrice', '$ordTime', '$ordAmount', '$ordDynID')";
if ($mysqli->query($queryOrd) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $queryOrd . "<br>" . $mysqli->error;
}
$proID = array($_POST['proid']);
$proQuan = array($_POST['proquan']);
foreach($proID as $item) {
$productid = $item['proid'];
$productquantity = $item['proquan'];
$query = "INSERT INTO ordersproducts (ordID, proID, proQuan) VALUES ('$ordDynID', '$productid', '$productquantity')";
if ($mysqli->query($query) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $query . "<br>" . $mysqli->error;
}
}
$mysqli->close();
So my question is, am i doing something wrong while reading the data in my php-file or is it a problem in my android-code?
Thanks in advance
Cheers
When you post arrays by name in your Android code like proID[] and proQuan[]. The $_POST['proid'] and $_POST['proquan'] are already arrays. It's similar to a html form having several inputs with the name with square brackets ie.(<input type="text" "name="proid[]" value="" />) So you just assign it like this.
$proID = $_POST['proid'];
$proQuan = $_POST['proquan'];
And assuming the elements in $proID and $proQuan are correctly mapped to each other. A for loop is more suitable to iterate through the arrays.
for ($i = 0; $i < count($proID); $i++) {
$productid = $proID[$i];
$productquantity = $proQuan[$i];
//your insert goes here
}
And of course I should tell you about the SQL Injection vulnerability in your PHP code. Use prepared statement and parameter binding to prevent that.
I'm not an android developer, but I can help you debug it in your PHP code. First of all, can you do a var_dump($_POST) and tell me the output?
I can see that you're using json_decode wrong, it looks like you're trying to use it for each key value pair instead of the full json text.
The way it works (check http://php.net/manual/en/function.json-decode.php for more information is that you pass it a full json text (i.e. '{ "a":1, "b":2 }') and it translates it to POPO (Plain old PHP object) that can be accessed this way
$object = json_decode('{ "a":1, "b":2 }');
$a = $object->a; // $a = 1
$b = $object->b; // $b = 2

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