Mongodb and Android link using php - 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?

Related

android - cannot request in JsonArrayRequest

I am a student studying Volley request.
There's an error that I can't solve, so I'm asking you to find a solution.
I don't understand why can't POST from Android to PHP at all.
It worked well in other situations, but not only in JsonArrayRequest.
I'll attach the code, so if there's any problem with my code, please let me know.
This is string request code in Android Studio
package kr.ac.castcommunity.cc.request
import android.util.Log
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.Response.success
import com.android.volley.toolbox.JsonArrayRequest
import com.android.volley.toolbox.StringRequest
import java.util.HashMap
import org.json.JSONObject
import com.android.volley.toolbox.JsonObjectRequest
import org.json.JSONArray
class CommentRequest(boardid : String , listener: Response.Listener<JSONArray>) :
JsonArrayRequest(Request.Method.POST, URL, JSONArray(), listener, Response.ErrorListener { error ->
Log.d("COMMENT ERROR", "Server Response FAIL: $error")
}) {
private val parameters: MutableMap<String, String>
companion object {
private val URL = "http://MyIP/cc/commentlist.php"
}
init {
parameters = HashMap()
parameters["boardid"] = boardid
Log.d("boardID :",boardid)
}
override fun getParams(): Map<String, String> {
return parameters
}
}
This is PHP code
(It works well if I randomly assign a variable.)
(But it doesn't work when I interlock it.)
<?php
$con = mysqli_connect("localhost", "root", "root", "cc");
mysqli_query($con, 'SET NAMES utf8');
$boardid = $_POST["boardid"]; // but It's not operating
//$boardid = "1"; // It's operating
$boardid = (int)$boardid;
$statement = mysqli_prepare($con, "select * from comment where boardid = ?");
mysqli_stmt_bind_param($statement, "i", $boardid);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $commentid, $boardid, $content, $writer, $date);
$response = array();
$response["success"] = false;
$result = array();
while(mysqli_stmt_fetch($statement)){
$response["success"] = true;
$response["commentid"] = $commentid;
$response["boardid"] = $boardid;
$response["content"] = $content;
$response["writer"] = $writer;
$response["date"] = substr($date,10,-3);
array_push($result, array(
"success"=>$response["success"],
"commentid" => $response["commentid"],
"boardid" => $response["boardid"],
"content" => $response["content"],
"writer" => $response["writer"],
"date" => $response["date"]));
}
echo json_encode($result);
?>
D/COMMENT ERROR: Server Response Fail: com.android.volley.ParseError: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray
and response code
val boardid = intent.getIntExtra("bnum", 0)
mCommentRecyclerView = comment_recyclerView
val responseListener = Response.Listener<JSONArray> { response ->
try {
Log.d("response", "comment response Start")
for (i in 0 until response.length()) {
val jobject = response.getJSONObject(i)
val success = jobject.getBoolean("success")
val boardid = jobject.getInt("boardid")
val commentid = jobject.getInt("commentid")
val content = jobject.getString("content")
val date = jobject.getString("date")
val writer = jobject.getString("writer")
if (success == true) {
mDatas.add(Comment(boardid, commentid, content, date, writer))
} else {
return#Listener
}
}
mAdpater = CommentAdapter(this, mDatas)
mCommentRecyclerView!!.adapter = mAdpater
mCommentRecyclerView!!.addItemDecoration(BoardDecoration(20))
val lm = LinearLayoutManager(this)
lm.reverseLayout = true
lm.stackFromEnd = true
mCommentRecyclerView!!.layoutManager = lm
mCommentRecyclerView!!.setHasFixedSize(true)
val decoration = DividerItemDecoration(this, LinearLayoutManager.VERTICAL)
mCommentRecyclerView!!.addItemDecoration(decoration)
} catch (e: JSONException) {
e.printStackTrace()
}
}
val commentRequest = CommentRequest(boardid.toString(), responseListener)
val queue = Volley.newRequestQueue(this#DetailActivity)
queue.add(commentRequest)
I really don't know why. I need your help.
Through your error message. I think there is a problem with the conversion of String to JsonObject.
You can print out the response from the server first, and then print out the conversion parameters.
I think the error appears in the for loop code below. Please check if the error is caused by the <br> tag.
Log.d("response", "comment response Start")
for (i in 0 until response.length()) {
val jobject = response.getJSONObject(i)
val success = jobject.getBoolean("success")
val boardid = jobject.getInt("boardid")
val commentid = jobject.getInt("commentid")
val content = jobject.getString("content")
val date = jobject.getString("date")
val writer = jobject.getString("writer")
println(jobject)
println(success)
println(boardid)
println(commentid)
println(content)
println(date)
println(writer)
if (success == true) {
mDatas.add(Comment(boardid, commentid, content, date, writer))
} else {
return#Listener
}
}

Post ArrayList to PHP and add it to MySQL database

I am creating an app similar to those from online stores
I did an ArrayList for products added to the shopping cart.
How I must do to send this into my PHP script and add this to MySQL database.
I tried return count of my ArrayList elements, but I can't.
This is PHP code:
<?php
$postedArray = $_POST["arrayToPOST"];
$response = array();
if(isset($postedArray))
{
$count = count($postedArray);
$response["Count"] = $count;
$response["postedArray"] = $postedArray;
}
else
{
$response["Count"] = 0;
$response["postedArray"] = "ERROR ON POST";
}
echo json_encode($response);
?>
This is my function in Android app:
val arrayList: ArrayList<String> = ArrayList<String>()
arrayList.add("First value")
arrayList.add("Second value")
arrayList.add("Third value")
val gson = GsonBuilder()
.setLenient()
.create()
val retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl("http://192.168.100.11/")
.build()
val webAPIInterface = retrofit.create(WebAPIInterface::class.java)
var call = webAPIInterface.postData(arrayList)
call.enqueue(object : Callback<ResponsePOJO> {
override fun onFailure(call: Call<ResponsePOJO>?, t: Throwable?) {
Log.e("MainActivity", "Retrofit 2 ERROR: "+t.toString())
}
override fun onResponse(call: Call<ResponsePOJO>?, response: Response<ResponsePOJO>?)
{
Log.v("MainActivity", "RESPONSE: "+response!!.body().toString())
if(response!!.isSuccessful)
{
Log.v("MainActivity", "Response is successful")
Log.v("MainActivity", "")
}
else
{
Log.e("MainActivity", "Response isnt successful")
}
}
})
I looking for solution in internet, but I found nothing.
Please help !

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

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