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