OpenCSV with Java spring boot can't read values of first column - java

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);

Related

Actual and formal argument lists differ in length error in main

Im working on a project where I have 3 text files with data of doctors, patients and home visits. When Im trying to upload the doctors file, upload all the data to a new object I get an error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Id_pacjenta Nazwisko Imie PESEL Data_urodzenia"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:658)
at java.base/java.lang.Integer.parseInt(Integer.java:776)
at com.company.Main.main(Main.java:40)
Below I'll paste my main as well as the classes & a snapshot of the text file used for imports:
Could anyone advise how to avoid this issue? Thanks!
public class Main {
public static void main(String[] args) {
List<Lekarz> lekarz = new ArrayList<>();
try{
File fileLekarze = new File("src/com/company/lekarze.txt");
Scanner readerLekarze = new Scanner(fileLekarze);
while(readerLekarze.hasNextLine()){
String[] data =readerLekarze.nextLine().split(" ");
lekarz.add(new Lekarz(Integer.parseInt(data[0]),data[1],data[2],data[3],new SimpleDateFormat("yyyy-MM-dd").parse(data[4]),data[5],data[6]));
}
readerLekarze.close();
} catch (FileNotFoundException e) {
System.out.println("Error File Lekarze");
e.printStackTrace();
} catch (ParseException e){
e.printStackTrace();
}
List<Pacjenci> pacjent = new ArrayList<>();
try{
File pacjenciFile = new File("src/com/company/pacjenci.txt");
Scanner readerPacjenci = new Scanner(pacjenciFile);
while(readerPacjenci.hasNextLine()){
String[] data = readerPacjenci.nextLine().split(" ");
pacjent.add(new Pacjenci(Integer.parseInt(data[0]),data[1],data[2],data[3],new SimpleDateFormat("yyyy-MM-dd").parse(data[4])));
}
readerPacjenci.close();
}catch (FileNotFoundException e) {
System.out.println("Error File Pacjenci");
e.printStackTrace();
} catch (ParseException e){
e.printStackTrace();
}
}
}
public class Pacjenci {
private int idPacjenta;
private String nazwisko;
private String imie;
private String pesel;
private Date dataUrodzenia;
public Pacjenci(int idPacjenta, String nazwisko, String imie, String pesel, Date dataUrodzenia) {
this.idPacjenta = idPacjenta;
this.nazwisko = nazwisko;
this.imie = imie;
this.pesel = pesel;
this.dataUrodzenia = dataUrodzenia;
}
public int getIdPacjenta() {
return idPacjenta;
}
public void setIdPacjenta(int idPacjenta) {
this.idPacjenta = idPacjenta;
}
public String getNazwisko() {
return nazwisko;
}
public void setNazwisko(String nazwisko) {
this.nazwisko = nazwisko;
}
public String getImie() {
return imie;
}
public void setImie(String imie) {
this.imie = imie;
}
public String getPesel() {
return pesel;
}
public void setPesel(String pesel) {
this.pesel = pesel;
}
public Date getDataUrodzenia() {
return dataUrodzenia;
}
public void setDataUrodzenia(Date dataUrodzenia) {
this.dataUrodzenia = dataUrodzenia;
}
#Override
public String toString() {
return "Pacjenci{" +
"idPacjenta=" + idPacjenta +
", nazwisko='" + nazwisko + '\'' +
", imie='" + imie + '\'' +
", pesel='" + pesel + '\'' +
", dataUrodzenia=" + dataUrodzenia +
", wizyty=" +
", lekarze=" +
'}';
}
}
public class Wizyty {
private Lekarz idLekarza;
private Pacjenci idPacjenta;
private Date dataWizyty;
public Wizyty(Lekarz idLekarza, Pacjenci idPacjenta, Date dataWizyty) {
this.idLekarza = idLekarza;
this.idPacjenta = idPacjenta;
this.dataWizyty = dataWizyty;
}
public Lekarz getIdLekarza() {
return idLekarza;
}
public void setIdLekarza(Lekarz idLekarza) {
this.idLekarza = idLekarza;
}
public Pacjenci getIdPacjenta() {
return idPacjenta;
}
public void setIdPacjenta(Pacjenci idPacjenta) {
this.idPacjenta = idPacjenta;
}
public Date getDataWizyty() {
return dataWizyty;
}
public void setDataWizyty(Date dataWizyty) {
this.dataWizyty = dataWizyty;
}
#Override
public String toString() {
return "Wizyty{" +
"idLekarza=" + idLekarza +
", idPacjenta=" + idPacjenta +
", dataWizyty=" + dataWizyty +
'}';
}
}
Id_pacjenta Nazwisko Imie PESEL Data_urodzenia
100 Kowal Waldemar 01211309876 2001-1-13
Because of the data spacing in the file, try this:
while(readerLekarze.hasNextLine()){
String line = readerLekarze.nextLine();
// Remove leading and trailing whitespaces (if any).
line = line.trim()
// "\\s+" Takes care of any multi-spacing within the data line when splitting.
String[] data =line.split("\\s+");
lekarz.add(new Lekarz(Integer.parseInt(data[0]),data[1],data[2],data[3],new SimpleDateFormat("yyyy-MM-dd").parse(data[4]),data[5],data[6]));
}
You could also just do:
String[] data = readerLekarze.nextLine().trim().split("\\s+");
As a complement to the #DevilsHnd, you only need to add a code to avoid the first line, because the first line is the "header information" of your file.
boolean headerRead = false;
while(readerLekarze.hasNextLine()) {
if (!headerRead) {
// extract the first line -> Id_pacjenta Nazwisko Imie PESEL Data_urodzenia
readerLekarze.nextLine();
headerRead = true;
continue;
}
String line = readerLekarze.nextLine();
// Remove leading and trailing whitespaces (if any).
line = line.trim();
// "\\s+" Takes care of any multi-spacing within the data line when splitting.
String[] data =line.split("\\s+");
lekarz.add(new Lekarz(
Integer.parseInt(data[0]),
data[1],
data[2],
data[3],
new SimpleDateFormat("yyyy-MM-dd").parse(data[4])));
}

POST data with retrofit2, Bearer token Unauthorized android

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.

Volley response Cannot store data into objects java android

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;}

Gson to parse string of arrays

I need to parse the below JSON content. Currently I have stored it inflat file and reading it. I have given the sample POJO classes which are created and the code which I tried below.
Tried two different approach and both are giving the following error
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 3 path $
Json file
{
"DeviceCommon": {
"ASIdentifier": "123",
"DatadeliveyMechanism": "notify",
"MobileOriginatorCallbackReference": {
"url": "http://application.example.com/inbound/notifications/modatanotification/"
},
"AccessiblityCallbackReference": {
"url": "http://application.example.com/inbound/notifications/accessibilitystatusnotification"
}
},
"DeviceList": [{
"ExternalIdentifer": "123456#mydomain.com",
"msisdn": "123456",
"senderName": "Device1",
"MobileOriginatorCallbackReference": {
"notifyURL": "http://application.example.com/inbound/notifications/modatanotification/"
},
"ConfigurationResultCallbackReference": {
"notifyURL": "http://application.example.com/inbound/notifications/configurationResult"
},
"ASreferenceID": "AS000001",
"NIDDduration": "1d"
}]
}
POJO classes:
Note: I have mentioned only two classes here.
package com.As.jsonmodel.configrequest;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown = true)
public class ConfigurationRequest
{
private DeviceList[] DeviceList;
private DeviceCommon DeviceCommon;
public DeviceList[] getDeviceList ()
{
return DeviceList;
}
public void setDeviceList (DeviceList[] DeviceList)
{
this.DeviceList = DeviceList;
}
public DeviceCommon getDeviceCommon ()
{
return DeviceCommon;
}
public void setDeviceCommon (DeviceCommon DeviceCommon)
{
this.DeviceCommon = DeviceCommon;
}
#Override
public String toString()
{
return "ClassPojo [DeviceList = "+DeviceList+", DeviceCommon = "+DeviceCommon+"]";
}
}
package com.As.jsonmodel.configrequest;
public class DeviceList
{
private MobileOriginatorCallbackReference MobileOriginatorCallbackReference;
private String NIDDduration;
private String ASreferenceID;
private String senderName;
private String ExternalIdentifer;
private String msisdn;
private ConfigurationResultCallbackReference ConfigurationResultCallbackReference;
public MobileOriginatorCallbackReference getMobileOriginatorCallbackReference ()
{
return MobileOriginatorCallbackReference;
}
public void setMobileOriginatorCallbackReference (MobileOriginatorCallbackReference MobileOriginatorCallbackReference)
{
this.MobileOriginatorCallbackReference = MobileOriginatorCallbackReference;
}
public String getNIDDduration ()
{
return NIDDduration;
}
public void setNIDDduration (String NIDDduration)
{
this.NIDDduration = NIDDduration;
}
public String getASreferenceID ()
{
return ASreferenceID;
}
public void setASreferenceID (String ASreferenceID)
{
this.ASreferenceID = ASreferenceID;
}
public String getSenderName ()
{
return senderName;
}
public void setSenderName (String senderName)
{
this.senderName = senderName;
}
public String getExternalIdentifer ()
{
return ExternalIdentifer;
}
public void setExternalIdentifer (String ExternalIdentifer)
{
this.ExternalIdentifer = ExternalIdentifer;
}
public String getMsisdn ()
{
return msisdn;
}
public void setMsisdn (String msisdn)
{
this.msisdn = msisdn;
}
public ConfigurationResultCallbackReference getConfigurationResultCallbackReference ()
{
return ConfigurationResultCallbackReference;
}
public void setConfigurationResultCallbackReference (ConfigurationResultCallbackReference ConfigurationResultCallbackReference)
{
this.ConfigurationResultCallbackReference = ConfigurationResultCallbackReference;
}
#Override
public String toString()
{
return "ClassPojo [MobileOriginatorCallbackReference = "+MobileOriginatorCallbackReference+", NIDD duration = "+NIDDduration+", AS referenceID = "+ASreferenceID+", senderName = "+senderName+", ExternalIdentifer = "+ExternalIdentifer+", msisdn = "+msisdn+", ConfigurationResultCallbackReference = "+ConfigurationResultCallbackReference+"]";
}
}
Json Reader
Approach1:
BufferedReader br = null;
try {
br = new BufferedReader(
new FileReader("/home/raj/apache-tomcat-8.0.3/webapps/file.json"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JsonReader jsonReader = new JsonReader(new FileReader("/home/raj/apache-tomcat-8.0.3/webapps/file.json"));
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
if (name.equals("DeviceCommon")) {
readApp(jsonReader);
}
}
jsonReader.endObject();
jsonReader.close();
}
public static void readApp(JsonReader jsonReader) throws IOException{
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
System.out.println(name);
if (name.contains("ASIdentifier")){
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String n = jsonReader.nextName();
if (n.equals("MobileOriginatorCallbackReference")){
System.out.println(jsonReader.nextString());
}
if (n.equals("AccessiblityCallbackReference")){
System.out.println(jsonReader.nextInt());
}
if (n.equals("DeviceList")){
jsonReader.beginArray();
while (jsonReader.hasNext()) {
System.out.println(jsonReader.nextString());
}
jsonReader.endArray();
}
}
jsonReader.endObject();
}
}
jsonReader.endObject();
}
// TODO Auto-generated method stub
Aproach2:
Gson gson = new Gson();
DeviceList [] myTypes = gson.fromJson(new FileReader("/home/raj/apache-tomcat-8.0.3/webapps/file.json"), DeviceList[].class);
System.out.println(gson.toJson(myTypes));
Any pointers on how to parse this file will be helpful.
Here's how to do it with Gson:
import java.io.FileReader;
import java.util.Arrays;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
public class Main {
public static void main(String[] args) throws Exception {
Data data = new Gson().fromJson(new FileReader("data.json"), Data.class);
System.out.println(data);
}
}
class Data {
#SerializedName("DeviceCommon")
DeviceCommon deviceCommon;
#SerializedName("DeviceList")
DeviceListEntry[] deviceList;
#Override
public String toString() {
return "Data{" +
"\n deviceCommon=" + deviceCommon +
"\n deviceList=" + Arrays.toString(deviceList) +
"\n}";
}
}
class DeviceCommon {
#SerializedName("ASIdentifier")
String asIdentifier;
#SerializedName("DatadeliveyMechanism")
String datadeliveyMechanism;
#SerializedName("MobileOriginatorCallbackReference")
Url mobileOriginatorCallbackReference;
#SerializedName("AccessiblityCallbackReference")
Url accessiblityCallbackReference;
#Override
public String toString() {
return "DeviceCommon{" +
"\n asIdentifier='" + asIdentifier + '\'' +
"\n datadeliveyMechanism='" + datadeliveyMechanism + '\'' +
"\n mobileOriginatorCallbackReference=" + mobileOriginatorCallbackReference +
"\n accessiblityCallbackReference=" + accessiblityCallbackReference +
"\n }";
}
}
class DeviceListEntry {
#SerializedName("ExternalIdentifer")
String externalIdentifer;
String msisdn;
String senderName;
#SerializedName("MobileOriginatorCallbackReference")
NotifyUrl mobileOriginatorCallbackReference;
#SerializedName("ConfigurationResultCallbackReference")
NotifyUrl configurationResultCallbackReference;
#SerializedName("ASreferenceID")
String asReferenceID;
#SerializedName("NIDDduration")
String nidDduration;
#Override
public String toString() {
return "DeviceListEntry{" +
"\n externalIdentifer='" + externalIdentifer + '\'' +
"\n msisdn='" + msisdn + '\'' +
"\n senderName='" + senderName + '\'' +
"\n mobileOriginatorCallbackReference=" + mobileOriginatorCallbackReference +
"\n configurationResultCallbackReference=" + configurationResultCallbackReference +
"\n asReferenceID='" + asReferenceID + '\'' +
"\n nidDduration='" + nidDduration + '\'' +
"\n }";
}
}
class Url {
String url;
#Override
public String toString() {
return url;
}
}
class NotifyUrl {
String notifyURL;
#Override
public String toString() {
return notifyURL;
}
}
Running Main will result in the following output:
Data{
deviceCommon=DeviceCommon{
asIdentifier='123'
datadeliveyMechanism='notify'
mobileOriginatorCallbackReference=http://application.example.com/inbound/notifications/modatanotification/
accessiblityCallbackReference=http://application.example.com/inbound/notifications/accessibilitystatusnotification
}
deviceList=[DeviceListEntry{
externalIdentifer='123456#mydomain.com'
msisdn='123456'
senderName='Device1'
mobileOriginatorCallbackReference=http://application.example.com/inbound/notifications/modatanotification/
configurationResultCallbackReference=http://application.example.com/inbound/notifications/configurationResult
asReferenceID='AS000001'
nidDduration='1d'
}]
}

Database returning indecipherable code

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.

Categories

Resources