How to send JSON Array output from android studio to PHP - php

The code below gets all the rows in my Android SQLite database and covert it to JSON Array. Now I want to get the JSON Array using PHP to store it to my online database. What should I do? Please help.
This is the code that I use:
private JSONArray getResults()
{
String myPath = this.getDatabasePath("cart.db").toString();// Set path to your database
String myTable = CartContract.CartEntry.TABLE_NAME;//Set name of your table
SQLiteDatabase myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
String searchQuery = "SELECT * FROM " + myTable;
Cursor cursor = myDataBase.rawQuery(searchQuery, null );
JSONArray resultSet = new JSONArray();
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
int totalColumn = cursor.getColumnCount();
JSONObject rowObject = new JSONObject();
for( int i=0 ; i< totalColumn ; i++ )
{
if( cursor.getColumnName(i) != null )
{
try
{
if( cursor.getString(i) != null )
{
Log.d("TAG_NAME", cursor.getString(i) );
rowObject.put(cursor.getColumnName(i) , cursor.getString(i) );
}
else
{
rowObject.put( cursor.getColumnName(i) , "" );
}
}
catch( Exception e )
{
Log.d("TAG_NAME", e.getMessage() );
}
}
}
resultSet.put(rowObject);
cursor.moveToNext();
}
cursor.close();
Log.d("FINAL RESULT", resultSet.toString() );
return resultSet;
}
This is the output:
FINAL RESULT: [{"id":"1","food_id":"52","food_price":"30","food_name":"Pink Lemonade","quantity":"5","amount":"150","special_request":""},{"id":"2","food_id":"51","food_price":"30","food_name":"House Blend Iced Tea","quantity":"3","amount":"90","special_request":""}]
and I want to put these values here: (online database)
attached picture
how should I do that?
UPDATE: I already send the result of my JSONArray and stored it in "$data" but my problem now is how to insert the values to my online database. By the way, in my PHP code, here is where I store the JSONArray as a string:
$data = $_POST["data"];
UPDATE: I already made it! Thanks for noticing and answering my question

I will give you some general guidelines. Sending JSON on HTTP calls can get weird because it can contain characters that are special to HTTP. To get around this, encode the JSON with Base 64 on Android and decode it in PHP.
I assume that you can figure out how to base64 encode with Java.
On PHP, you get back your original JSON.
$originalJson = base64_decode($inputFromAndroid);
$object = json_decode($originalJson, true);
// Now you have the data as a PHP array.

Related

How to send array in http get request

private void timer1_Tick(object sender, System.EventArgs e)
{
int iIdx;
int[] iData;
bool[] bData;
if (m_bRegister) // Read registers (4X references)
{
// read register (4X) data from slave
if (adamTCP.Modbus().ReadHoldingRegs(m_iStart, m_iLength, out iData))
{
m_iCount++; // increment the reading counter
txtStatus.Text = "Read registers " + m_iCount.ToString() + " times...";
// update ListView
label1.Text = HttpGet("http://127.0.0.1/misc/api1.php?value0=" + iData[0].ToString());
label2.Text = HttpGet("http://127.0.0.1/misc/api1.php?value1=" + iData[1].ToString());
label3.Text = HttpGet("http://127.0.0.1/misc/api1.php?value2=" + iData[2].ToString());
label4.Text = HttpGet("http://127.0.0.1/misc/api1.php?value3=" + iData[3].ToString());
label5.Text = HttpGet("http://127.0.0.1/misc/api1.php?value4=" + iData[4].ToString());
for (iIdx = 0; iIdx < m_iLength; iIdx++)
{
listViewModbusCur.Items[iIdx].SubItems[2].Text = iData[iIdx].ToString(); // show value in decimal
listViewModbusCur.Items[iIdx].SubItems[3].Text = iData[iIdx].ToString("X04"); // show value in hexdecimal
}
How do i send array using httpget method? The code on top show that i'm sending data one by one. I need to send it in array and retrieve it back in api,php so that i could insert it into database in one row. currently, it's 1 data for 1 row.
Here is a example to convert array to json in PHP
$arr=array(
"varl1"=>1,
"varl2"=>"example",
"varl3"=>3,
);
$json_arr=json_encode($arr);
Now you can send $json_arr
and then you can decode it using json_decode()
you should passing 'value0' become just one querystring, ex : value[]
so the url will become
http://127.0.0.1/misc/api1.php?value[]="+ iData[0].ToString()"&value[]="+ iData[1].ToString() and etc what you want to send it "
or you should use http_build_query to the param array data
the code you show is php ??
the api maybe php but the code style more like .NET c#
correct me if im wrong.
//Update Response
string[] param = new string[(how many your counter param)];
param [0] = "test0";
param [1] = "test1";
param [2] = "test2";
in my example i give you 3
string sParams = JsonConvert.SerializeObject(param) ;
HttpGet("http://127.0.0.1/misc/api1.php?value=" + sParams);

jsonObject.getString("String in UTF8" ) giving blank

I am fetching a string from my MySql DB on and online server using webservice in JSON format.
I am able to see that Android Studio is fetching it correctly as I see it in debugging mode.
But when I go ahead and add it to a List list, I get nothing.
Here's some more info:
What I am getting:
{"products":[{"veg_name_eng":"Corn","veg_name_hindi":"मक्का"}],"success":1}
My concern is with: "veg_name_hindi":"मक्का"
When I go ahead and try to put it in a dataitem list, I get nothing:
public static List<DataItem> dataItemList;
dataItemList.add(jsonObject.getString(veg_name_eng),jsonObject.getString(veg_name_hindi))
veg_name_eng and veg_name_hindi are the column names at my table.
After the above code I get dataItemList = null, So nothing is adding to it.
In my server side MySql DB, I am using UTF-8 encoding.
I am using android studio.
UPDATE 1:
I am parsing the JSON as :
JSONObject jsonObject = new JSONObject(myJSONString);
veg_list = jsonObject.getJSONArray("products");
try {
while (TRACK < veg_list.length()) {
JSONObject jsonObject = veg_list.getJSONObject(TRACK);
addItem(new DataItem(jsonObject.getString(veg_name_eng), jsonObject.getString(veg_name_hindi)));
TRACK = TRACK + 1;
}
} catch (JSONException e) {
e.printStackTrace();
}
// and the addItem function is as follows:
private static void addItem(DataItem item) {
dataItemList.add(item); //While Debugging, I can see that value of item is correct. (i.e., item: DataItem{veg_name_eng='Cork', veg_name_hindi='मक्का'} )
dataItemMap.put(item.getVeg_id(), item);
}
Firstly, Make a model of the your JSON String using
http://json2java.azurewebsites.net/
and then map your JSON String to your Model using Gson. It's much easy to use.
Another way to get your required String for this particular result is parse json string yourself.
For Example :
String vegNameEng,vegNameHindi;
vegNameEng = vegNameHindi = "";
try{
JSONObject obj = new JSONObject(yourJsonString);
JSONArray arr = obj.getJSONArray("products");
vegNameEng = arr.getJSONObject(0).getString("veg_name_eng");
vegNameHindi = arr.getJSONObject(0).getString("veg_name_hindi");
}catch(JSONException ex){
}
Now vegNameEng and vegNameHindi have the required data.
I figured out, It was a silly mistake, the variable I was using to put data into the database was overwritten by some other variable with the same name. Closing the thread for now. Thanks #Umer-Farooq.

Android PHP Json

I have looked around for over a few hours and most of the post I see are from way back when, so maybe I just don't understand or it might be outdated. I have two problems.
I have an Json object and Json Array that comes out like this:
{"command":"update", "Data":["first data","second data","third data","fourth data"]}
I want it it to read like this:
{"command":"update", "Data":[{"1":"first data"},{"2":"second data"},{"1":"third data"},{"2":"fourth data"}]}
I am unclear how to add the 1 & 2 so I can know what to pull on the php side.And it might not be the proper format either, but you will get an ideal. Android code:
JSONObject parent = new JSONObject();
JSONArray child = new JSONArray();
child.put("first data");
child.put("second data");
parent.put("Data", child);
Next problem on my php side is pulling the data so I can put it into my database and I am unsure exactly how this is done:
// DECODE OUR JSON FROM ANDROID
$data = json_decode(file_get_contents('php://input'), true);
// FOR LOOP TO INSERT DATA INTO DATABASE
for($i=0; $i<count($obj['Data']); $i+=2)
{
// need to get 1 & 2 values to insert into database
//$first = NEED VALUE OF 1
//$second = NEED VALUE OF 2
// mysqli statement to insert into database
$Q = "INSERT INTO `DATA_TABLE` (data1, data2) VALUES ('$first', '$second');
mysqli_query($conn, $Q);
}
Change your code to
JSONObject parent = new JSONObject();
JSONArray child = new JSONArray();
child.put({ "1", "first data" });
child.put({ "2", "second data" });
But I would more likely store your data as an object inside an array with each object being one insert into your database.
JSONObject parent = new JSONObject();
JSONArray child = new JSONArray();
JSONObject item1 = new JSONObject();
JSONObject item2 = new JSONObject();
...
item1.name = "Item 1 name";
item1.rating = "Item 1 rating";
...
child.put(item1);
child.put(item2);
Then you can iterate through each item in the data array and know that it contains all the data you need to populate your database.

Json is being put in array into the wrong order

I am working on an android app which is retrieving information from a MySQL database.
The android app is posting to a PHP REST web service and the web service is returning JSON data.
What I am currently trying to do is get a list of databases on the MySQL server in alphabetical order. When the JSON is printed to the logcat it seems to be in the right order but when I call json.names() on the JSONObject in android it then has the databases in the wrong order.
For example, the logcat might shown it as db1, db2, db3, db4 but when the array is returned from json.names() its then appears to be in a random order. For example db4, db1, db3, db2.
Is there a particular reason for this and how can I stop this from happening.
Thanks for any help you can provide
Below is the code that processes the JSON
public void processConnectDBResult(IConnectDB iConnectDb, JSONObject json)
{
ArrayList<String> databases = new ArrayList<String>();
ArrayList<String> tables = null;
HashMap<String, List<String>> dbAndTables = new HashMap<String, List<String>>();
try
{
//Retrieve the array of the databases
JSONArray databasesJson = json.names();
for (int i = 0; i < databasesJson.length(); i++)
{
databases.add(databasesJson.getString(i));
//Retrieve the tables array from the database array
JSONArray tablesJson = json.getJSONArray(databasesJson.getString(i));
tables = new ArrayList<String>();
for (int j = 0; j < tablesJson.length(); j++)
{
tables.add(tablesJson.getString(j));
}
dbAndTables.put(databases.get(i), tables);
}
iConnectDb.processDatabaseRetrievalResult("SUCCESS", "", databases, dbAndTables);
}
catch (Exception ex)
{
}
}

PHP/Android and JSONObject; I can only seem to access the last element

I have a set up where it is returning a possibly decent amount of info. Here is the logcat:
04-17 22:38:21.886: DEBUG/TestMYSQL(12603): Result of sql:
[{"id":"1","front_text":"the dog was so cute","back_text":"its name was dolly"},
{"id":"2","front_text":"plants use the sun","back_text":"isn't that interesting"},
{"id":"3","front_text":"plants can use the sun to create","back_text":"energy"},
{"id":"4","front_text":"a plant also needs minerals","back_text":"from the soil"},
{"id":"5","front_text":"without water the plant would","back_text":"probably die"},
{"id":"6","front_text":"plants are little machines","back_text":"who love to eat"}]
To gain this info, I have it execute a php file. Here is some pertinent Java, android code:
.....
result = sb.toString();
Log.d(TAG, "Result of sql: " + result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// parse json data
JSONObject json_data = null;
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
}
return json_data;
It turns results into a jsonObject, to which I can play with.
So here is a step before, the query part in php:
include 'connectMySQL.php';
mysql_select_db("card_db");
$q=mysql_query("SELECT * FROM ".$packname);
while($e=mysql_fetch_assoc($q)){
$output[]=$e;
}
print(json_encode($output));
mysql_close();
The problem is I only seem to have access to the FINAL... eh row. That is, in the above data, I can only seem to access id:6 row.
I'm looking at the auto_complete and JSONOBJECTs but I don't have enough experience to figure this out at the moment, and it is late.
Any ideas on how to loop through the jsonObject in java?
Let me take a minute and analyze the structure for a second before turning in. I don't know much about JSON, but here is what it looks like:
I query the database with tables I've set up, blah blah.
It returns rows of data.
I suppose my question then is how does a row of key value pairs get encoded into a JSON OBJECT, and how can I access different 'rows'?
You're overwriting the JSONObject referenced by json_data in each iteration of the loop. So at the end, it always returns the last element in jArray.
Since you need to return multiple objects, you could:
simply return the jArray to the calling function. However, this means that the caller will have to deal with the details of the data transfer implementation and if you decided to change libraries or move over to XML, it'll break a lot of code and make it much harder.
return an array or List of the actual objects that the calling code is aware of and should be dealing with. For example, you might declare a value-object (VO) that has id, front_text, back_text and for each JSONObject in jArray, you'd create a new VO and put it into an array and return that.
public class MyVO
{
final public String id;
final public String frontText;
final public String backText;
public MyVO(String id, String ft, String bt)
{
this.id = id;
this.frontText = ft;
this.backText = bt;
}
}
List<MyVo> vos = new ArrayList<MyVO>();
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
vos.add(new MyVO(json_data.getString("id"), json_data.getString("front_text"), json_data.getString("back_text"));
}
In the calling code, you could then go over the VOs:
for(MyVO vo : vos)
{
//vo.id or vo.frontText or vo.backText
}

Categories