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