My code is 100% working. I dont understand when i store the receiving output from Volley onresponse, i cant seem to store them correctly into my object. The raw output is correct. When i store it into my object, and then try to read the object, it showing wrong information.
For example, there is no data for contact and data for position is output at wrong place.
Log.d("TAG", "onResponse : "+ response.toString());
myProfile.set_firstname(response.optString("firstname", ""));
myProfile.set_lastname(response.optString("lastname", ""));
myProfile.set_contact(response.optString("contact", ""));
myProfile.set_email(response.optString("email", ""));
myProfile.set_position(response.optString("position", ""));
myProfile.set_areaname(response.optString("area", ""));
myProfile.set_deptname(response.optString("department", ""));
Log.d("TAG", "myProfile SET : " +
"firstname: "+myProfile.get_firstname() + " " +
"lastname: "+myProfile.get_lastname() + " " +
"contact: "+myProfile.get_contact() + " " +
"email: "+myProfile.get_email() + " " +
"position: "+myProfile.get_position() + " " +
"area: "+myProfile.get_areaname() + " " +
"dept: "+myProfile.get_deptname()
);
Raw JSON response from Volley and Log.d
onResponse : {"firstname":"kirpal","lastname":"SINGH","contact":"0164028083","email":"kirpal#gmail.com","position":"Technician","area":"Nextrack","department":"nexpro"}
myProfile SET : firstname: kirpal lastname: SINGH contact: Technician email: kirpal#gmail.com position: area: Nextrack dept: nexpro
MyProfile.java
public class MyProfile {
private String id="";
private String firstname="";
private String lastname="";
private String areaname ="";
private String deptname ="";
private String contact ="";
private String email ="";
private String position ="";
//SET
public void set_id(String id){this.id = id;}
public void set_firstname(String firstname){this.firstname = firstname;}
public void set_lastname(String lastname){this.lastname = lastname;}
public void set_areaname(String areaname){this.areaname = areaname;}
public void set_deptname(String deptname){this.deptname = deptname;}
public void set_contact(String contact){this.contact = contact;}
public void set_email(String email){this.email = email;}
public void set_position(String position){this.contact = position;}
//GET
public String get_id(){return this.id;}
public String get_firstname(){return this.firstname;}
public String get_lastname(){return this.lastname;}
public String get_areaname(){return this.areaname;}
public String get_deptname(){return this.deptname;}
public String get_contact(){return this.contact;}
public String get_email(){return this.email;}
public String get_position(){return this.position;}
}
Wrong info shows because you set position on contact and also set position on position.
public void set_position(String position){this.contact = position;}
change to
public void set_position(String position){this.position = position;}
Related
I am trying to read values from csv file with Java spring boot with dependency of opencsv. But the values of first column are not geting readed while other columns are fine. It returns them as null.
Reader reader = Files.newBufferedReader(Paths.get(path));
CsvToBean<CsvBikeTrips> csvToBean = new CsvToBeanBuilder(reader)
.withType(CsvBikeTrips.class)
.withIgnoreLeadingWhiteSpace(false)
.build();
List<CsvBikeTrips> csvBikeTrips = csvToBean.parse();
public class CsvBikeTrips {
#CsvBindByName(column = "Departure")
private String departureTimestamp;
#CsvBindByName(column = "Return")
private String returnTimestamp;
#CsvBindByName(column = "Departure station id")
private String departureStationId;
#CsvBindByName(column = "Return station id")
private String returnStationId;
#CsvBindByName(column = "Departure station name")
private String departureStationName;
#CsvBindByName(column = "Return station name")
private String returnStationName;
#CsvBindByName(column = "Covered distance (m)")
private String coveredDistance;
#CsvBindByName(column = "Duration (sec.)")
private String duration;
public String getDepartureTimestamp() {
return departureTimestamp;
}
public void setDepartureTimestamp(String departureTimestamp) {
this.departureTimestamp = departureTimestamp;
}
public String getReturnTimestamp() {
return returnTimestamp;
}
public void setReturnTimestamp(String returnTimestamp) {
this.returnTimestamp = returnTimestamp;
}
public String getDepartureStationId() {
return departureStationId;
}
public void setDepartureStationId(String departureStationId) {
this.departureStationId = departureStationId;
}
public String getReturnStationId() {
return returnStationId;
}
public void setReturnStationId(String returnStationId) {
this.returnStationId = returnStationId;
}
public String getDepartureStationName() {
return departureStationName;
}
public void setDepartureStationName(String departureStationName) {
this.departureStationName = departureStationName;
}
public String getReturnStationName() {
return returnStationName;
}
public void setReturnStationName(String returnStationName) {
this.returnStationName = returnStationName;
}
public String getCoveredDistance() {
return coveredDistance;
}
public void setCoveredDistance(String coveredDistance) {
this.coveredDistance = coveredDistance;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
#Override
public String toString() {
return "CsvBikeTrips{" +
"departureTimestamp='" + departureTimestamp + '\'' +
", returnTimestamp='" + returnTimestamp + '\'' +
", departureStationId='" + departureStationId + '\'' +
", returnStationId='" + returnStationId + '\'' +
", departureStationName='" + departureStationName + '\'' +
", returnStationName='" + returnStationName + '\'' +
", coveredDistance='" + coveredDistance + '\'' +
", duration='" + duration + '\'' +
'}';
}
}
And the row of csv files look like this:
Departure,Return,Departure station id,Departure station name,Return station id,Return station name,Covered distance (m),Duration (sec.)
2021-05-31T23:57:25,2021-06-01T00:05:46,094,Laajalahden aukio,100,Teljäntie,2043,500
2021-05-31T23:56:59,2021-06-01T00:07:14,082,Töölöntulli,113,Pasilan asema,1870,611
Ive tried something like this:
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(path), "UTF-8"));
And also to save the file in different txt editors but no success.
It happens that the file, in the beginning, had something like : ZWNBSP
Intelli J editor couldn't see that easily. It seems that it is related to BOM.
Unicode of that is \uFEFF
Fix:
InputStream input = new FileInputStream(path);
Reader reader = new InputStreamReader(new BOMInputStream(input), StandardCharsets.UTF_8);
I am trying to send the data of source and destination.
public void sendPost(final SearchSendModel searchSendModel){
//public void sendPost( String source, String destination){
Call call = mAPIService.sendSearch(searchSendModel);
//Call call = mAPIService.sendSearch(source, destination);
call.enqueue(new Callback<SearchModel>() {
#Override
public void onResponse(Call<SearchModel> call, Response<SearchModel> response) {
Toast.makeText(Search.this, " Responce " +response.body(), Toast.LENGTH_SHORT).show();
Log.v("Responce", "Responce "+response.body());
if (response.isSuccessful()){
SearchModel searchResponse = response.body();
assert searchResponse != null;
String content = "";
content += "Code: " +response.code() +"\n";
content += "vech_id: " + searchResponse.getVechId() +"\n";
content += "model_no: " + searchResponse.getModelNo() +"\n";
content += "reg_no: " +searchResponse.getRegNo() +"\n";
content += "delivery_start_date: " +searchResponse.getDeliveryStartDate() +"\n";
content += "delivery_end_date: " +searchResponse.getDeliveryEndDate() +"\n";
content += "full_percent: " +searchResponse.getFullPercent() +"\n";
content += "approval_status: " +searchResponse.getApprovalStatus() +"\n";
content +="source: " +searchResponse.getSource() +"\n";
content += "destination: " +searchResponse.getDestination() +"\n\n";
Toast.makeText(getApplicationContext(),content,Toast.LENGTH_LONG).show();
searchModelList.add(searchResponse);
}else {
Toast.makeText(getApplicationContext(),"Something is error",Toast.LENGTH_SHORT).show();
}
This is the Json response which i am expecting:
[
{
"vech_id": "30",
"model_no": "8956",
"reg_no": "98765",
"delivery_start_date": "2020-03-18",
"delivery_end_date": "2020-06-24",
"full_percent": "0.14",
"approval_status": "1",
"source": "ranchi",
"destination": "garwah"
}
]
Interface for API is:
#POST("search_vehicle.php")
#FormUrlEncoded
Call<SearchSendModel> sendSearch(#Body SearchSendModel searchSendModel);
SearchSendModel.java
public class SearchSendModel {
public SearchSendModel(String source, String destination) {
this.source = source;
this.destination = destination;
}
#SerializedName("source")
private String source;
#SerializedName("destination")
private String destination;
public String getSource() {
return source;
}
public String getDestination() {
return destination;
}
}
But I am getting this error always:
java.lang.IllegalStateException:Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 2 column 2 path$
I think your onResponse should use List<SearchModel> instead of SearchModel. Your response format is array.
I want to post new data to server with this JSON:
{
"tgl_Lahir": "1990-12-18 00:00:00",
"nama": "Joe",
"keterangan": "Employee",
"tempatLahir": "Los Angeles",
"noPegawai": "111111",
"golDarah": "0",
"statusNikah": "0",
"hubungans": {
"id": "10"
},
"agama": {
"id_Agama": "1"
},
"jeniskelamin": {
"jenisKelamin": "1"
}
}
Here's my ApiClientPOST.java:
public class ApiClientPOST {
private static Retrofit retrofit = null;
public static Retrofit getClient(String url){
if(retrofit == null){
retrofit = new Retrofit.Builder().baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
Here's my APIUtils.java:
public class APIUtils {
private APIUtils(){
};
public static final String API_URL = "IPAddress/employee/family/add";
public static MainInterface getUserService(){
return ApiClientPOST.getClient(API_URL).create(MainInterface.class);
}
}
Here's my familylistresponsePOST.java:
public class familylistresponsePOST {
#SerializedName("noPegawai")
private String noPegawai;
#SerializedName("date_otor")
private Object dateOtor;
#SerializedName("jeniskelamin")
private Jeniskelamin jeniskelamin;
#SerializedName("keterangan")
private String keterangan;
#SerializedName("hubungans")
private Hubungans hubungans;
#SerializedName("tgl_Lahir")
private String tglLahir;
#SerializedName("nama")
private String nama;
#SerializedName("agama")
private Agama agama;
#SerializedName("statusNikah")
private String statusNikah;
#SerializedName("tempatLahir")
private String tempatLahir;
#SerializedName("id")
private int id;
#SerializedName("golDarah")
private String golDarah;
public void setNoPegawai(String noPegawai){
this.noPegawai = noPegawai;
}
public String getNoPegawai(){
return noPegawai;
}
public void setDateOtor(Object dateOtor){
this.dateOtor = dateOtor;
}
public Object getDateOtor(){
return dateOtor;
}
public void setJeniskelamin(Jeniskelamin jeniskelamin){
this.jeniskelamin = jeniskelamin;
}
public Jeniskelamin getJeniskelamin(){
return jeniskelamin;
}
public void setKeterangan(String keterangan){
this.keterangan = keterangan;
}
public String getKeterangan(){
return keterangan;
}
public void setHubungans(Hubungans hubungans){
this.hubungans = hubungans;
}
public Hubungans getHubungans(){
return hubungans;
}
public void setTglLahir(String tglLahir){
this.tglLahir = tglLahir;
}
public String getTglLahir(){
return tglLahir;
}
public void setNama(String nama){
this.nama = nama;
}
public String getNama(){
return nama;
}
public void setAgama(Agama agama){
this.agama = agama;
}
public Agama getAgama(){
return agama;
}
public void setStatusNikah(String statusNikah){
this.statusNikah = statusNikah;
}
public String getStatusNikah(){
return statusNikah;
}
public void setTempatLahir(String tempatLahir){
this.tempatLahir = tempatLahir;
}
public String getTempatLahir(){
return tempatLahir;
}
public void setId(int id){
this.id = id;
}
public int getId(){
return id;
}
public void setGolDarah(String golDarah){
this.golDarah = golDarah;
}
public String getGolDarah(){
return golDarah;
}
#Override
public String toString(){
return
"ListUserResponse2{" +
"noPegawai = '" + noPegawai + '\'' +
",date_otor = '" + dateOtor + '\'' +
",jeniskelamin = '" + jeniskelamin + '\'' +
",keterangan = '" + keterangan + '\'' +
",hubungans = '" + hubungans + '\'' +
",tgl_Lahir = '" + tglLahir + '\'' +
",nama = '" + nama + '\'' +
",agama = '" + agama + '\'' +
",statusNikah = '" + statusNikah + '\'' +
",tempatLahir = '" + tempatLahir + '\'' +
",id = '" + id + '\'' +
",golDarah = '" + golDarah + '\'' +
"}";
}
}
I've tried to create this method and use it on my Button.setOnClickListener:
public void addFamily(String noPegawai,String agama, String hubungan, String jenisKelamins, String tgl_Lahir, String nama, String keterangan, String tempatLahir, String golDarah, String statusNikah){
SharedPreferences preferences = getSharedPreferences("MyPref",0);
String tokens = preferences.getString("userToken",null);
Call<familylistresponse> call = apiService.addFams(noPegawai,agama, hubungan, jenisKelamins, tgl_Lahir , nama, keterangan, tempatLahir, golDarah, statusNikah, "Bearer" + tokens);
call.enqueue(new Callback<familylistresponse>() {
#Override
public void onResponse(Call<familylistresponse> call, Response<familylistresponse> response) {
// if (response.isSuccessful()){
familylistresponse resultsData = new familylistresponse();
resultsData= response.body();
Toast.makeText(TambahDataKeluarga.this,"Data Berhasil Ditambahkan!" + resultsData, Toast.LENGTH_SHORT).show();
// }
}
#Override
public void onFailure(Call<familylistresponse> call, Throwable t) {
Log.e("ERROR: ", t.getMessage());
}
});
}
This one is my tambah Button:
tambah.setOnClickListener(v -> {
SharedPreferences preferences = getSharedPreferences("MyPref",0);
String noPegawai = preferences.getString("noPegawai",null);
String snopeg = etNoPegawai.getText().toString().trim();
String snama = etNama.getText().toString().trim();
String stmpLahir = etTmptLahir.getText().toString().trim();
String stglLahir = etTglLahir.getText().toString().trim();
String sketerangan = etKeterangan.getText().toString().trim();
String sgoldar = etGoldar.getText().toString().trim();
String sstatusnikah = etStatusNikah.getText().toString().trim();
valueJenisKelamin = jeniskelamin.getSelectedItem().toString();
valueHubungan = spHubungans.getSelectedItem().toString();
valueAgama = spAgama.getSelectedItem().toString();
familylistresponse f = new familylistresponse();
f.setNoPegawai(snopeg);
agamas.setAgama(spAgama.getSelectedItem().toString().trim());
jks.setJenisKelamin(jeniskelamin.getSelectedItem().toString().trim());
hubungans.setHubungan(spHubungans.getSelectedItem().toString().trim());
addFamily(snopeg, valueAgama, valueHubungan, valueJenisKelamin, stglLahir, snama, sketerangan, stmpLahir, sgoldar, sstatusnikah);
Log.d(f.getNama(),f.getGolDarah());
Toast.makeText(TambahDataKeluarga.this,"No pegawai "+ noPegawai + " Nama Pegawai "+ snama+ " Tgl Lahir "+ stglLahir
+ " Agama " + valueAgama
+ " Hubungan " + valueHubungan
+ " Jenis Kelamin " + valueJenisKelamin
+ " Tgl Lahir " + stglLahir
+ " Keterangan " + sketerangan
+ " Tempat Lahir " + stmpLahir
+ " Goldar " + sgoldar
+ " Status Nikah " + sstatusnikah,Toast.LENGTH_LONG).show();
});
The toast says that the data is successfully stored but in fact, it isn't. The toast also says that response.body() is null and there is no error in logcat even in the debugger. Please kindly help me. Thanks in advance for any help
I do not see where you are defining Hubungans, Agama and Jeniskelamin classes although you are using it as datatype inside your familylistresponsePOST.java
After creating these three classes, I hope your issue will be solved.
I have encountered a problem in my Android application. The problem is that when I try to retrieve data from my database, I get code that I cannot read. I am an amateur programmer and don't know too much about Android programming. Here is my output:
[com.example.foodsaver2.Food#42ae3420,
com.example.foodsaver2.Food#42ae3720,
com.example.foodsaver2.Food#42ae3968,
com.example.foodsaver2.Food#42ae3bd0,
com.example.foodsaver2.Food#42ae3e18,
com.example.foodsaver2.Food#42ae4060,
com.example.foodsaver2.Food#42ae42a8, com.example.foodsaver2.Food#42ae4510, com.example.foodsaver2.Food#42ae4758, com.example.foodsaver2.Food#42ae49a0, com.example.foodsaver2.Food#42ae4c08, com.example.foodsaver2.Food#42ae4e50, com.example.foodsaver2.Food#42ae50b8, com.example.foodsaver2.Food#42ae5360, com.example.foodsaver2.Food#42ae55a8, com.example.foodsaver2.Food#42ae5810, com.example.foodsaver2.Food#42ae5a58, com.example.foodsaver2.Food#42ae5ca0, com.example.foodsaver2.Food#42ae5ee8, com.example.foodsaver2.Food#42ae61d0, com.example.foodsaver2.Food#42ae6418, com.example.foodsaver2.Food#42ae6660, com.example.foodsaver2.Food#42ae68c8, com.example.foodsaver2.Food#42ae6b10, com.example.foodsaver2.Food#42ae6d58, com.example.foodsaver2.Food#42ae6fa0, com.example.foodsaver2.Food#42ae7208, com.example.foodsaver2.Food#42ae7450, com.example.foodsaver2.Food#42ae7790, com.example.foodsaver2.Food#42ae79d8, com.example.foodsaver2.Food#42ae7c60, com.example.foodsaver2.Food#42ae7ea8, com.example.foodsaver2.Food#42ae8130, com.example.foodsaver2.Food#42ae8378, com.example.foodsaver2.Food#42ae85e0, com.example.foodsaver2.Food#42ae8848, com.example.foodsaver2.Food#42ae8ab0, com.example.foodsaver2.Food#42ae8d18, com.example.foodsaver2.Food#42ae8f80, com.example.foodsaver2.Food#42ae91e8, com.example.foodsaver2.Food#42ae9450, com.example.foodsaver2.Food#42ae97c0, com.example.foodsaver2.Food#42ae9a28, com.example.foodsaver2.Food#42ae9c70, com.example.foodsaver2.Food#42ae9ee0, com.example.foodsaver2.Food#42aea128, com.example.foodsaver2.Food#42aea370, com.example.foodsaver2.Food#42aea5d8, com.example.foodsaver2.Food#42aea820, com.example.foodsaver2.Food#42aeaa88, com.example.foodsaver2.Food#42aeacd0, com.example.foodsaver2.Food#42aeaf38, com.example.foodsaver2.Food#42aeb180, com.example.foodsaver2.Food#42aeb3e8, com.example.foodsaver2.Food#42aeb630, com.example.foodsaver2.Food#42aeb878, com.example.foodsaver2.Food#42aebae0, com.example.foodsaver2.Food#42aebd28, com.example.foodsaver2.Food#42aebf90, com.example.foodsaver2.Food#42aec1d8, com.example.foodsaver2.Food#42aec440, com.example.foodsaver2.Food#42aec808, com.example.foodsaver2.Food#42aeca70, com.example.foodsaver2.Food#42aeccb8, com.example.foodsaver2.Food#42aecf00, com.example.foodsaver2.Food#42aed168, com.example.foodsaver2.Food#42aed3b0, com.example.foodsaver2.Food#42aed618, com.example.foodsaver2.Food#42aed860, com.example.foodsaver2.Food#42aedaa8, com.example.foodsaver2.Food#42aedd10, com.example.foodsaver2.Food#42aedf58, com.example.foodsaver2.Food#42aee1a0, com.example.foodsaver2.Food#42aee408, com.example.foodsaver2.Food#42aee650, com.example.foodsaver2.Food#42aee8b8, com.example.foodsaver2.Food#42aeeb00, com.example.foodsaver2.Food#42aeed68, com.example.foodsaver2.Food#42aeefb0, com.example.foodsaver2.Food#42aef218, com.example.foodsaver2.Food#42aef460, com.example.foodsaver2.Food#42aef6c8, com.example.foodsaver2.Food#42aef910, com.example.foodsaver2.Food#42aefb58, com.example.foodsaver2.Food#42aefdc0, com.example.foodsaver2.Food#42af0008, com.example.foodsaver2.Food#42af0250, com.example.foodsaver2.Food#42af04b8, com.example.foodsaver2.Food#42af0700, com.example.foodsaver2.Food#42af0948, com.example.foodsaver2.Food#42af0bb0, com.example.foodsaver2.Food#42af1028, com.example.foodsaver2.Food#42af1270, com.example.foodsaver2.Food#42af14d8, com.example.foodsaver2.Food#42af1720, com.example.foodsaver2.Food#42af1968, com.example.foodsaver2.Food#42af1bd0, com.example.foodsaver2.Food#42af1e18, com.example.foodsaver2.Food#42af2060, com.example.foodsaver2.Food#42af22c8, com.example.foodsaver2.Food#42af2510, com.example.foodsaver2.Food#42af2778, com.example.foodsaver2.Food#42af29c0, com.example.foodsaver2.Food#42af2c08, com.example.foodsaver2.Food#42af2e70, com.example.foodsaver2.Food#42af30b8, com.example.foodsaver2.Food#42af3300, com.example.foodsaver2.Food#42af3568]
Here is what I did:
public void send (View v) {
List<String> strlist = new ArrayList<String>();
strlist = mDbHelper.getAllComments();
GmailSender sender = new GmailSender("omitted", "omitted");
try {
sender.sendMail("DietWatcher Feedback",
strlist + "",
"ommited",
"omitted");
Toast.makeText(getApplicationContext(), "Sent!", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Cannot send message!", Toast.LENGTH_SHORT).show();
}
}
Here is some of my database code:
public List getAllComments() {
List customers = new ArrayList();
String inputText = "";
String query =
KEY_CUSTOMER + /*"INTEGER," + */ "," +
KEY_NAME + "," +
KEY_ADDRESS1 + "," +
KEY_ADDRESS2 + "," +
KEY_CITY + "," +
KEY_STATE + "," +
KEY_ZIP + "," +
KEY_SEARCH + "," +
TOTAL_CARB + "," +
FIBER +
SUGAR +
PROTEIN+
SODIUM +
TOTALCALORIES +
FTS_VIRTUAL_TABLE +
KEY_SEARCH;
Log.w(TAG, query);
//Cursor mCursor = mDb.rawQuery(query,null);
Cursor cursor = mDb.query(FTS_VIRTUAL_TABLE, new String[]{KEY_CUSTOMER + "," +
KEY_NAME + "," +
KEY_ADDRESS1 + "," +
KEY_ADDRESS2 + "," +
KEY_CITY + "," +
KEY_STATE + "," +
KEY_ZIP + "," +
TOTAL_CARB /*+
FIBER +
SUGAR +
PROTEIN+
SODIUM +
TOTALCALORIES +
FTS_VIRTUAL_TABLE +
KEY_SEARCH */}, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Food customer = cursorToCustomer(cursor);
customers.add(customer);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return customers;
}
private Food cursorToCustomer(Cursor cursor) {
Food customer = new Food();
customer.setCustomer(cursor.getString(0));
customer.setName(cursor.getString(1));
customer.setAddress1(cursor.getString(2));
customer.setAddress2(cursor.getString(3));
customer.setCity(cursor.getString(4));
customer.setState(cursor.getString(5));
customer.setZipCode(cursor.getString(6));
return customer;
}
Here is Food.java:
package com.example.foodsaver2;
public class Food {
String customer = null;
String name = null;
String address1 = null;
String address2 = null;
String city = null;
String state = null;
String zipCode = null;
String carb = null;
String fiber = null;
String sugar = null;
String protein = null;
String sodium = null;
public String getCustomer() {
return customer;
}
public void setCustomer(String customer) {
this.customer = customer;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getCarb() {return carb;}
public void setCarb(String carb) {this.carb = carb;}
public String getFiber() {return fiber;}
public void setFiber() {this.fiber = fiber;}
public String getSugar() {return sugar;}
public void setSugar() {this.sugar = sugar;}
public String getProtein() {return protein;}
public void setProtein() {this.protein = protein;}
public String getSodium() {return sodium;}
public void setSodium() {this.sodium = sodium;}
}
So what did I do wrong here? Any help regarding this problem would be greatly appreciated.
mDbHelper.getAllComments() return List of Food class object's instead of String so response is not readable format. if you want to pass details from strlist to sender.sendMail then you will need to prepare another List which Store values from strlist as String. try is as:
ArrayList<Food> arrallcomments = mDbHelper.getAllComments();
List<String> strlist = new ArrayList<String>();
for(Food object: list){
strlist.add("Name : "+object.getName() +
" Customer :"+object.getCustomer()+...);
}
now use strlist for sending ArrayList with Mail.
I have a JSON object like this:
{
"user1": {
"timeSpent": "20.533333333333335h",
"worklog": [
{
"date": "06/26/2013",
"issues": [
{
"issueCode": "COC-2",
"comment": "\ncccccc",
"timeSpent": "20.533333333333335h"
}
],
"dayTotal": "20.533333333333335h"
}
]
},
"admin": {
"timeSpent": "601.1h",
"worklog": [
{
"date": "06/25/2013",
"issues": [
{
"issueCode": "COC-1",
"comment": "",
"timeSpent": "113.1h"
}
],
"dayTotal": "113.1h"
},
{
"date": "06/26/2013",
"issues": [
{
"issueCode": "COC-1",
"comment": "",
"timeSpent": "8h"
},
{
"issueCode": "COC-2",
"comment": "",
"timeSpent": "480h"
}
],
"dayTotal": "488h"
}
]
}
}
and trying to parse it with Gson:
Gson gson = new Gson();
Book responseBean = gson.fromJson(jsonString, Book.class);
But the 'responceBean' is always 'null'
Here are all the other classes:
public class Book {
private List<User> user = new LinkedList<User>();
public List<User> getUser() {
return user;
}
public void setUser(List<User> user) {
this.user = user;
}
}
public class User {
private String timeSpent;
private List<WorkLog> worklogs = new LinkedList<WorkLog>();;
public List<WorkLog> getWorklogs() {
return worklogs;
}
public void setWorklogs(List<WorkLog> worklogs) {
this.worklogs = worklogs;
}
public String getTimeSpent() {
return timeSpent;
}
public void setTimeSpent(String timeSpent) {
this.timeSpent = timeSpent;
}
}
public class WorkLog{
private String date;
private String dayTotal;
private List<Issues> issues;
public String getDate(){
return this.date;
}
public void setDate(String date){
this.date = date;
}
public String getDayTotal(){
return this.dayTotal;
}
public void setDayTotal(String dayTotal){
this.dayTotal = dayTotal;
}
public List<Issues> getIssues(){
return this.issues;
}
public void setIssues(List<Issues> issues){
this.issues = issues;
}
}
public class Issues{
private String comment;
private String issueCode;
private String timeSpent;
public String getComment(){
return this.comment;
}
public void setComment(String comment){
this.comment = comment;
}
public String getIssueCode(){
return this.issueCode;
}
public void setIssueCode(String issueCode){
this.issueCode = issueCode;
}
public String getTimeSpent(){
return this.timeSpent;
}
public void setTimeSpent(String timeSpent){
this.timeSpent = timeSpent;
}
}
This is my latest attempt. Somehow I cannot figure out the right way. Will be very appreciative for any help.
Your JSON model does not match your object model.
You need an intermediate layer to fill the gap: a TypeAdapter.
Moreover there is no naming information for the user.
And finally there is a name mismatch: "worklog" in JSON, "worklogs" in Java.
Here is a fixed version:
Java model:
class User {
private String timeSpent;
#SerializedName("worklog")
private List<WorkLog> worklogs = new LinkedList<WorkLog>();
private String name;
public List<WorkLog> getWorklogs() {
return worklogs;
}
public void setWorklog(List<WorkLog> worklogs) {
this.worklogs = worklogs;
}
public String getTimeSpent() {
return timeSpent;
}
public void setTimeSpent(String timeSpent) {
this.timeSpent = timeSpent;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The plumbing to fill the gap:
class BookTypeAdapter implements JsonSerializer<Book>, JsonDeserializer<Book>
{
Gson gson = new Gson();
public JsonElement serialize(Book book, Type typeOfT, JsonSerializationContext context)
{
JsonObject json = new JsonObject();
for (User user : book.getUser())
{
json.addProperty(user.getName(), gson.toJson(user));
}
return json;
}
public Book deserialize(JsonElement element, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
JsonObject json = element.getAsJsonObject();
Book book = new Book();
for (Entry<String, JsonElement> entry : json.entrySet())
{
String name = entry.getKey();
User user = gson.fromJson(entry.getValue(), User.class);
user.setName(name);
book.getUser().add(user);
}
return book;
}
}
And a roundtrip:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Book.class, new BookTypeAdapter());
Gson gson = builder.create();
Book book = gson.fromJson("{" +
" \"user1\": {" +
" \"timeSpent\": \"20.533333333333335h\"," +
" \"worklog\": [" +
" {" +
" \"date\": \"06/26/2013\"," +
" \"issues\": [" +
" {" +
" \"issueCode\": \"COC-2\"," +
" \"comment\": \"\ncccccc\"," +
" \"timeSpent\": \"20.533333333333335h\"" +
" }" +
" ]," +
" \"dayTotal\": \"20.533333333333335h\"" +
" }" +
" ]" +
" }," +
" \"admin\": {" +
" \"timeSpent\": \"601.1h\"," +
" \"worklog\": [" +
" {" +
" \"date\": \"06/25/2013\"," +
" \"issues\": [" +
" {" +
" \"issueCode\": \"COC-1\"," +
" \"comment\": \"\"," +
" \"timeSpent\": \"113.1h\"" +
" }" +
" ]," +
" \"dayTotal\": \"113.1h\"" +
" }," +
" {" +
" \"date\": \"06/26/2013\"," +
" \"issues\": [" +
" {" +
" \"issueCode\": \"COC-1\"," +
" \"comment\": \"\"," +
" \"timeSpent\": \"8h\"" +
" }," +
" {" +
" \"issueCode\": \"COC-2\"," +
" \"comment\": \"\"," +
" \"timeSpent\": \"480h\"" +
" }" +
" ]," +
" \"dayTotal\": \"488h\"" +
" }" +
" ]" +
" }" +
"}", Book.class);
String json = gson.toJson(book);
Have a look at my tutorial to get an idea of what is possible with Gson: Java/JSON mapping with Gson
Enjoy! :)
I had some problem before a month. As far as I remember it was because, same as you, I forgot to make "new" to objects. I mean that it should look:
public class User {
private String timeSpent;
private List<WorkLog> worklogs = new List < WorkLog >();
}
Try this and I hope that it will help.
P.S.
Also as Erik Pragt said you have array of Users, not just single one. So you will have to make 1 more class that contains a List < Users >.