Sending an array to php using retrofit - android

In my android app, I am fetching some data from using mysql using retrofit 1.9. The data i fetched is in json array. Now i want to use all the values in array in my sql query at once. For example this is my json array i fetch from mysql
[{"receivers":"Can23584PtqA"},{"receivers":"New565159nrsN"},{"receivers":"NY H3V9tcig"}]
u can it has three values. Values can be 'n'. There is no limit for array length but now i want to send all these again to my sql at once using retrofit 1.9. If i use loop then everytime only 1 value will go to php. Is there any way i can send whole array and use all values in mysql query
JSONArray jsonArray = new JSONArray(output);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);//returnJson;
String receiver=jsonObject.getString("receivers");// this is the string now i can send it to php but problem is this only one value will be sent at a time. I need all values at same in my sql query
}

JSONArray jsonArray = new JSONArray(output);
//list to store list of all receivers
ArrayList<String> receivers=new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = null;//returnJson;
try {
jsonObject = jsonArray.getJSONObject(i);
String receiver=jsonObject.getString("receivers");
receivers.add(receiver);
} catch (JSONException e) {
e.printStackTrace();
}
}
//now pass this 'receivers' list to your php server via web api
//#FormUrlEncoded
//#POST("index.php?action=item")
//Call<Receiver> sendReceivers(#Field("items[]") List<String> items);

If you want to send it again to php you can use JSON or Gson for sending. I recommend to Gson.
For Example:
Gson gson = new Gson();
ArrayList<Object> array; // Your array recieved from server it will be object array
String stringarray = gson.toJson(array); //So this is a complete array in single string value you can de-serialize it on both php and android.
Please let me know if it is helpful for you

Related

How to get list of data from sqlite and parse into jsonarray and send it to server?

I want to send particular data from database and parse into jsonarray and send it to server. I am able to send dummy data directly to server .Can you tell me the way to send data (parsed jsondata ) into server.?
For your approach you should firstly create a array list with all your necessary data send to server. You can parse into json using Jakeson see Example here. Resultant will be your data.
Firstly you have to put all your data in the arrayList then use this code
private String arrayToJson(ArrayList<HashMap<String, String>> arrayList) {
//Coverting Arraylist to JsonArray
List<JSONObject> jsonList = new ArrayList<JSONObject>();
for (HashMap<String, String> data : arrayList) {
JSONObject jsonObject = new JSONObject(data);
jsonList.add(jsonObject);
}
JSONArray json_array= new JSONArray(jsonList);
String json_string= json_array.toString();
}
then you can send this to server. And decode this json_string and retrive your data

Convert SQLite to JSON

when i add data using SQLite is it possible to convert the data to JSON so that when I retrieve data it should be parsed and fetch data.If possible explain with example.
When you fetch data from your SQLiteDatabase, it is returned in a Cursor. Unfortunately there's no such direct format to convert data from a cursor to JSON, but you can do it with some code like:
private JSONArray convertCursorToJSON(Cursor cursor) {
JSONArray result = new JSONArray();
int columnCount = cursor.getColumnCount();
while (cursor.moveToNext()) {
JSONObject row = new JSONObject();
for (int index = 0; index < columnCount; index++) {
row.put(cursor.getColumnName(index), cursor.getString(index));
}
result.put(row);
}
cursor.close();
return result;
}
you can modify and use the following according to your need.
Gson gson = new GsonBuilder().create();
//wordList should be your arraylistdata or values etc which you want to insert
//Use GSON to serialize Array List to JSON
gson.toJson(wordList);
use this while storing your data
Convert the data to String when you are storing
jsonObject.toString();
On retrieve you can get the json by converting the String.
JSONObject asdf = new JSONObject(<retrieved data>);

How to post multiple rows (or a LIST object) to PHP using JSON (Android)

I am creating an android application in which I am using SQLite. I have one table in which I have 5 fields. There are many rows in that table and I want to send all those rows using JSON to my PHP code so I can receive the object and insert it in the MySQL database.
What is the best way to do it. I am using LIST object but don't know how I can use POST it using JSON.
Please guide!
i am using this code
mCursor =db.rawQuery("SELECT * FROM customer", null);
while (mCursor.moveToNext()) {
// In one loop, cursor read one undergraduate all details
// Assume, we also need to see all the details of each and every undergraduate
// What we have to do is in each loop, read all the values, pass them to the POJO class
//and create a ArrayList of undergraduates
customer = new Customer();
customer.CustomerName = mCursor.getString(0).toString();
customer.Phone = mCursor.getString(1).toString();
customer.BrandName = mCursor.getString(2).toString();
customer.City = mCursor.getString(3).toString();
customer.FamilyMembers = mCursor.getString(4).toString();
customerList.add(customer);
}
for (int i = 0; i < customerList.size(); i++)
{
JSONObject row = new JSONObject();
row.put("Customer", customerList.get(i));
json.put(row);
}
Don't know how to post it to PHP code.
You have to iterate through your List and fill an JSONArray with JSONObjects for each row. In the JSONObject you can have the key as your column-name and the value with the type you need.
JSONArray json = new JSONArray();
for (int i = 0; i < list.size(); i++) {
JSONObject row = new JSONObject();
row.put("key1", list.get(i).value1);
...
json.put(row);
}
(not tested). Then you can post the json.toString() to the server and retrieve it in PHP with
$jsonstring = file_get_contents('php://input', true);

Parse JSON string from remote URL in Android

Well I'm new to Android. I'm getting a JSON string from a remote URL.
[{"key":"myString1","val":"myValue1"},{"key":"myString2","val":"myValue2"},{"key":"myString3","val":"myValue3"},{"key":"myString4","val":"myValue4"},{"key":"myString5","val":"myValue5"}]
I just need to parse this JSON string & display all key-val pair. I tried something like below from one of the tutorial.
JSONArray jArray = new JSONArray(str);
json = jArray.getJSONObject(0); //This will take first pair.
But I don't know the syntax for iterating through whole json object. Any help would be appreciated. Thanks in Advance.
There's nothing special in it. You do it like iterating any other array.
Let's say you have two String arrays to be filled with values: String[] mKey, mValue
Reading from JSON array will be like:
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
mKey[i] = object.getString("key");
mValue[i] = object.getString("val");
}

How to get the multiple text from string in Android?

I am developing the Android for Xively. I get the following text data and store into string.
{"id":111111177,"title":"G-sensor","private":"true","feed":"https://api.xively.com/v2/feeds/111111177.json","auto_feed_url":"https://api.xively.com/v2/feeds/111111177.json","status":"frozen","updated":"2014-08-05T07:14:29.783670Z","created":"2014-08-01T08:29:17.156043Z","creator":"https://xively.com/users/x22819","version":"1.0.0","datastreams":[{"id":"GPIO1","current_value":"1","at":"2014-08-05T07:14:18.991421Z","max_value":"1.0","min_value":"0.0","tags":["xyz"],"unit":{"type":"G","label":"watts"}},{"id":"GPIO2","current_value":"0","at":"2014-08-05T07:14:29.783670Z","max_value":"1.0","min_value":"0.0","tags":["xyz"],"unit":{"type":"G","label":"watts"}},{"id":"GPIO3","current_value":"1","at":"2014-08-05T06:51:08.165217Z","max_value":"1.0","min_value":"1.0"},{"id":"GPIO4","current_value":"0","at":"2014-08-05T06:51:13.029452Z","max_value":"0.0","min_value":"0.0"},{"id":"GPIO5","current_value":"1","at":"2014-08-05T06:51:20.679123Z","max_value":"1.0","min_value":"1.0"},{"id":"GPIO6","current_value":"0","at":"2014-08-05T06:51:27.057369Z","max_value":"0.0","min_value":"0.0"}],"location":{"domain":"physical"},"product_id":"w8tuBsYf835kYTjDFz9w","device_serial":"DWJAXD6N7VDZ"}
There has id and the current_value in the above data , and I want to get the data of id and the current_value from the above text like following text.
GPIO1 1
GPIO2 0
GPIO3 1
GPIO4 0
GPIO5 1
GPIO6 0
How do I capture the the data of id and the current_value from the above text ?
Can somebody teach me how to do ?
Thank in advance.
Try this:
String resultJSON = "datastreams":[{"id":"GPIO1","current_value":"1","at":"2014-08-05T07:14:18.991421Z","max_value":"1.0","min_value":"0.0","tags":["xyz"],"unit":{"type":"G","label":"watts"}},
{"id":"GPIO2","current_value":"0","at":"2014-08-05T07:14:29.783670Z","max_value":"1.0","min_value":"0.0","tags":["xyz"],"unit":{"type":"G","label":"watts"}},
{"id":"GPIO3","current_value":"1","at":"2014-08-05T06:51:08.165217Z","max_value":"1.0","min_value":"1.0"},
{"id":"GPIO4","current_value":"0","at":"2014-08-05T06:51:13.029452Z","max_value":"0.0","min_value":"0.0"},
{"id":"GPIO5","current_value":"1","at":"2014-08-05T06:51:20.679123Z","max_value":"1.0","min_value":"1.0"},
{"id":"GPIO6","current_value":"0","at":"2014-08-05T06:51:27.057369Z","max_value":"0.0","min_value":"0.0"}],"location":{"domain":"physical"},"product_id":"w8tuBsYf835kYTjDFz9w","device_serial":"DWJAXD6N7VDZ"};
JSONObject jsonRoot = new JSONObject(resultJSON);
JSONArray jsonData = jsonRoot.getJSONArray("Data");
for(int i=0; i<jsonData.lenght;i++) {
JSONObject jsonOBject = jsonData.getJSONObject(i);
Log.d(TAG, "json ("+i+") = "+jsonOBject.toString());
// do what you want with your JSONObject , i.e :add it to an ArrayList of paresed result
String ID = jsonOBject.getString("id");
}
Hope this may help you
dataList = new ArrayList<HashMap<String, String>>();
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
myarray = jsonObj.getJSONArray("datastreams");
// looping through All myarray
for (int i = 0; i < myarray.length(); i++) {
JSONObject c = myarray.getJSONObject(i);
String id = c.getString("id");
String date = c.getString("at");
// tmp hashmap for single data
HashMap<String, String> data = new HashMap<String, String>();
// adding each child node to HashMap key => value
data.put(TAG_ID, id);
data.put(TAG_DATE, date);
// adding data to data list
dataList.add(data);
}
The data you have is actually a JSON so you can simply parse it to java POJO. I would suggest to use one of 2 most popular open source parsers GSON or Jackson.
What you have to do is:
Create java POJOs for chosen parser. To make it easier use this online tool http://www.jsonschema2pojo.org/
Copy generated java classes to your project.
Use JSON parser e.g. GSON
Let's say you named your main class as Example, with GSON you can parse it like this:
Gson gson = new Gson();
String data = ....//your JSON data
Example example = gson.fromJson(data, Example.class);
Data you would like to get will have own Java representation and will be available through getter method, e.g.:
List<Datastream> datastreams = example.getDatastreamList();
for (DataStream data : datastreams) {
String id = data.getId();
String currentValue = data.getCurrentValue();
}
Then you can do whatever you like. Please know that GSON can also read streams, so if you already parse stream to string you can skip it and pass that stream to Gson object directly.
If you don't want redundant POJOs or their parameters, you can remove them. GSON will handle it and simply ignore these values. Just make sure that data you are interested in keep the generated structure.
That's how I would do it.

Categories

Resources