I\'m beginner in android,write simple application to send json array to server,write this code:
JSONArray jsonArray = new JSONArray();
JSONObjec
Another example to show use of Gson
library
make a Record.java
class
import com.google.gson.annotations.SerializedName;
public class Record {
@SerializedName("Name")
private String name;
@SerializedName("password")
private String password;
@SerializedName("item1")
private String item1;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getItem1() {
return item1;
}
public void setItem1(String item1) {
this.item1 = item1;
}
}
make a test for this RecordTestDrive.java
import java.util.ArrayList;
import com.google.gson.Gson;
public class RecordTestDrive {
public static void main(String[] args) {
ArrayList<Record> records = new ArrayList<>();
for (int i = 0; i < 4; i++) {
Record record = new Record();
record.setName("Name_"+i);
record.setPassword("password_"+i);
record.setItem1("item_"+i);
records.add(record);
}
String jsonResult = (new Gson()).toJson(records);
System.out.println(""+jsonResult);
}
}
output==>
[
{
"Name": "Name_0",
"password": "password_0",
"item1": "item_0"
},
{
"Name": "Name_1",
"password": "password_1",
"item1": "item_1"
},
{
"Name": "Name_2",
"password": "password_2",
"item1": "item_2"
},
{
"Name": "Name_3",
"password": "password_3",
"item1": "item_3"
}
]
In this manner once you have data read from the SQLite
database into your objects, after which you can easily make array of JSON
String from the data you have gathered from the database to send it to server
It is only storing the last record because you are not creating a new JSONObject
in your do...while
loop. See my edited code.
JSONArray jsonArray = new JSONArray();
JSONObject obj = new JSONObject();
String DATABASE_NAME = "TEMPFOOD";
String TABLE_NAME = "tempData";
try{
SQLiteDatabase mydb = openOrCreateDatabase(DATABASE_NAME, TempActivity.MODE_PRIVATE,null);
Cursor allrows = mydb.rawQuery("SELECT * FROM "+ TABLE_NAME, null);
if(allrows.moveToFirst()){
do{
obj = new JSONObject();
String Food_Name = allrows.getString(0);
String Value = allrows.getString(1);
String NOBAT = allrows.getString(2);
String TIME = allrows.getString(3);
String DATE = allrows.getString(4);
try {
obj.put("Food_Name", Food_Name)
.put("Value", Value)
.put("NOBAT", NOBAT)
.put("TIME", TIME)
.put("DATE", DATE);
} catch (JSONException e) {
e.printStackTrace();
}
jsonArray.put(obj);
}
while(allrows.moveToNext());
}
mydb.close();
}catch(Exception e){
//Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
}
String jsonText = jsonArray.toString();