Post from Android to CSV with Columns - php

i want to post from Android to a CSV File correctly. Now the php posts the Question, Answer and the User in one column. With \n i can switch to a new row in the CSV File. \t doesn't work.
Now it look like this:
Column1
Question1Answer1User1
Question2Answer2User2
...
It should view like this:
Column1| Column2| Column3
Question1| Answer1 | User1
Question2| Answer2 | User2
..
The Java Code inside the Android App.
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
for (int i = 0; i < dbHandler.getAllStimmungen().size(); i++) {
params.add(new BasicNameValuePair("question"+i, dbHandler.getAllStimmungen().get(i).getQuestion()));
params.add(new BasicNameValuePair("answer"+i, dbHandler.getAllStimmungen().get(i).getAnswer()));
params.add(new BasicNameValuePair("user"+i, httpHandler.getContact(1).getuserName()+"\n"));
}
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
return null;
}
The PHP Code
<?php
$timestamp = date("d.m.y-H:i:s");
$filename= 'myTextFile-'.$timestamp.'.csv';
$lastIndex = 0;
// receive data from app's http request
$data=($_POST);
// write data from my android app to a text file
file_put_contents($filename,$data);
?>
Sorry for my English!

CSV stands for Comma Separated Value. It means that columns are separated by commas. Said that, a new line character \n switches to a new row and has nothing to do with columns. You have to put commas between every single value in the csv file.
column1,column2,column3, \n
value1,value2,value3, \n
value11, value22, value33,

Related

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.

sending array from android to php

I have an array
ArrayList<String> selectedItems = new ArrayList<String>();
and few strings
private String sq,tr;
am sending these values to a remote server via POST request
nameValuePair = new ArrayList<NameValuePair>(3);
nameValuePair.add(new BasicNameValuePair("sq", sq));
nameValuePair.add(new BasicNameValuePair("tr", tr));
nameValuePair.add(new BasicNameValuePair("sub[]", selectedItems);
My problem is am able to send strings but when I try to send the array am getting errors
Please suggest me the best way to send array as well as strings via post method or guide me if am making some mistake.
try to put that in loop
for (int i = 0; i < selectedItems.length; i++) {
nameValuePairs.add(new BasicNameValuePair("sub[]",selectedItems[i]));
}

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

how to send long array from android to php server

I try to send long array from android to PHP via JSON. I did the same thing with Javascript and worked but with JAVA it gets confusing. When I send the parameters, long array list changes.
This is the part that creates the list.
JSONArray list = new JSONArray();
for (int i = 0; i < users.size(); i++) {
list.put(users.get(i).getId());
}
This is the code in JAVA that send the data.
public JSONObject sendFacebookFriendList(JSONArray list) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("list", list.toString()));
JSONParser jsonParser = new JSONParser();
JSONObject json = jsonParser.getJSONFromUrl(accountServer, params);
return json;
}
And this is the code that receives the data in PHP.
$list = $_POST['list'];
$result = array("success" => 1, "list" => $list);
While sending with Javascript the $list variable was becoming long array directly but I couldn't send it same way with JAVA.
When I send the list back to JAVA from PHP without any change I see that each array element has \" at the head and the end
So this list:
list= ["517565130","523709375","524503024","524620558","524965930", ...
becomes this:
"list":"[\"517565130\",\"523709375\",\"524503024\",\"524620558\", ...
So I cannot parse this array in PHP.
I couldn't find any way to send the long/int array in a proper way.
I appreciate if someone can fix this or suggest another way.
Thanks
I solved the problem. The thing I skipped was decoding the json array that encoded at android part. So after getting the posted data it is needed to be decoded like this;
$list = $_POST['list'];
$obj = json_decode($list);
And then I can use $obj as array.

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