I have a kind of POJO class in Dart and I want to map the variables using an API call.
Here is my POJO class in Code.1,
class Elements {
String onApi;
String tlApi;
String pl1Api;
String pl2Api;
String dl1Api;
String dl2Api;
String fnApi;
String lnApi;
String cnApi;
String eidApi;
Elements(
{this.onApi,
this.tlApi,
this.pl1Api,
this.pl2Api,
this.dl1Api,
this.dl2Api,
this.fnApi,
this.lnApi,
this.cnApi,
this.eidApi});
Elements.fromJson(Map<String, dynamic> json) {
onApi = json['on_api'];
tlApi = json['tl_api'];
pl1Api = json['pl1_api'];
pl2Api = json['pl2_api'];
dl1Api = json['dl1_api'];
dl2Api = json['dl2_api'];
fnApi = json['fn_api'];
lnApi = json['ln_api'];
cnApi = json['cn_api'];
eidApi = json['eid_api'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['on_api'] = this.onApi;
data['tl_api'] = this.tlApi;
data['pl1_api'] = this.pl1Api;
data['pl2_api'] = this.pl2Api;
data['dl1_api'] = this.dl1Api;
data['dl2_api'] = this.dl2Api;
data['fn_api'] = this.fnApi;
data['ln_api'] = this.lnApi;
data['cn_api'] = this.cnApi;
data['eid_api'] = this.eidApi;
return data;
}
}
Code.1
Here is the JSON code which I want to map via an API call in Code.2,
{
"on_api": "1",
"tl_api": "10",
"pl1_api": "XYZ Chocolates Lounge",
"pl2_api": "ABC Nagar",
"dl1_api": "EFGH Software Pvt. Ltd.",
"dl2_api": "Random Road, Bengaluru - 5600XX",
"fn_api": "Snehanshu",
"ln_api": "Bhattacharya",
"cn_api": "01234",
"eid_api": "snehanshu#abc.com"
}
Code.2
Here is my API calling class Code.3,
import 'dart:convert';
import 'package:http/http.dart';
import 'package:smoorapplication/src/constants/constants.dart';
import 'package:smoorapplication/src/model/elements.dart';
Future<dynamic> apiGetOrder() async{
var response = await get(Uri.parse(API_LINK));
var jsonData = jsonDecode(response.body);
List<Elements> elements = [];
for(var u in jsonData){
Elements element =
Elements.fromJson(u);
elements.add(element);
}
print(elements.length);
return elements;
}
Code.3
So, I need some help in writing the code for the API call, so that it can map the data successfully.
Thank you
your model class
import 'dart:convert';
Element elementFromJson(String str) => Element.fromJson(json.decode(str));
String elementToJson(Element data) => json.encode(data.toJson());
class Element {
Element({
this.onApi,
this.tlApi,
this.pl1Api,
this.pl2Api,
this.dl1Api,
this.dl2Api,
this.fnApi,
this.lnApi,
this.cnApi,
this.eidApi,
});
String onApi;
String tlApi;
String pl1Api;
String pl2Api;
String dl1Api;
String dl2Api;
String fnApi;
String lnApi;
String cnApi;
String eidApi;
factory Element.fromJson(Map<String, dynamic> json) => Element(
onApi: json["on_api"],
tlApi: json["tl_api"],
pl1Api: json["pl1_api"],
pl2Api: json["pl2_api"],
dl1Api: json["dl1_api"],
dl2Api: json["dl2_api"],
fnApi: json["fn_api"],
lnApi: json["ln_api"],
cnApi: json["cn_api"],
eidApi: json["eid_api"],
);
Map<String, dynamic> toJson() => {
"on_api": onApi,
"tl_api": tlApi,
"pl1_api": pl1Api,
"pl2_api": pl2Api,
"dl1_api": dl1Api,
"dl2_api": dl2Api,
"fn_api": fnApi,
"ln_api": lnApi,
"cn_api": cnApi,
"eid_api": eidApi,
};
}
and here's your getAPiOrder method
Future<dynamic> apiGetOrder() async{
var response = await get(Uri.parse(API_LINK));
///if this line doesn't work
Element element = Element.fromJson(respnse.body);
///try this line
Element element = Element.fromJson(Map.from(respnse.body));
return elements;
}
Hello i want to show Json data on listview.builder. I can take a values from the Json but i cant show them on the listview.
This is the Json data.
{"success":true,"timestamp":1578778505,"base":"EUR","date":"2020-01-11","rates":{"AED":4.084603,"AFN":86.369994,"ALL":122.079994,"AMD":531.079988,"ANG":1.8526,"AOA":538.513234,
"ARS":66.270498,...}}
I want to show "rates" values on Listview.
There is a model for Json.(I used to model for quicktype.io)
Currency currencyFromJson(String str) => Currency.fromJson(json.decode(str));
String currencyToJson(Currency data) => json.encode(data.toJson());
class Currency {
bool success;
int timestamp;
String base;
DateTime date;
Map<String, double> rates;
Currency({
this.success,
this.timestamp,
this.base,
this.date,
this.rates,
});
factory Currency.fromJson(Map<String, dynamic> json) => Currency(
success: json["success"],
timestamp: json["timestamp"],
base: json["base"],
date: DateTime.parse(json["date"]),
rates: Map.from(json["rates"]).map((k, v) => MapEntry<String, double>(k, v.toDouble())),
);
Map<String, dynamic> toJson() => {
"success": success,
"timestamp": timestamp,
"base": base,
"date": "${date.year.toString().padLeft(4, '0')}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}",
"rates": Map.from(rates).map((k, v) => MapEntry<String, dynamic>(k, v)),
};
}
..
class _CurrencyListState extends State<CurrencyList> {
Map<String, double> rates;
String url= "xxxx";
Currency currency;
Future takeCurrency() async{
var response = await http.get(url);
var decodedJson = json.decode(response.body);
currency = Currency.fromJson(decodedJson);
rates = Map.from(decodedJson["rates"]).map((key, value) => MapEntry<String, double>(key, value));
}
void initState() {
// TODO: implement initState
super.initState();
takeCurrency();
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Currency"),),
body: FutureBuilder(future: takeCurrency() ,builder: (BuildContext context, AsyncSnapshot takenCurrency){
print('takenCurrency data is: ${currency.rates}');
return ListView.builder(itemCount: currency.rates.length ,itemBuilder: (context, index){
return Card(
child: ListTile(
title: Text(
I tried to print values on there but i couldnt find a way.
Thanks.
You are trying to print values but you can't? This is because your Future is not returning anything, so the FutureBuilder's snapshot is void.
(This is why it's important to give a type parameter to Future, such as Future<Currency>: the compiler would've caught you were not returning a Currency.)
Since you are using a StatefulWidget I assume you want to cache the result of your future, correct?
This is how:
class _CurrencyListState extends State<CurrencyList> {
Map<String, double> rates;
String url= "xxxx";
Future<Currency> future;
Future<Currency> takeCurrency() async{
var response = await http.get(url);
var decodedJson = json.decode(response.body);
return Currency.fromJson(decodedJson);
}
void initState() {
// TODO: implement initState
super.initState();
future = takeCurrency();
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Currency"),),
body: FutureBuilder(future: future ,builder: (BuildContext context, AsyncSnapshot snapshot){
if (snapshot.hasData) {
final currency = snapshot.data;
print('takenCurrency data is: ${currency.rates}');
return ListView.builder(itemCount: currency.rates.length ,itemBuilder: (context, index){
return Card(
child: ListTile(
title: Text(
When the future completes, now the snapshot will have data.
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:json_parsing/models.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<Data> dataList = List();
bool _isLoading = false;
Rates rates = Rates();
Future<String> loadPersonFromAssets() async {
return await rootBundle.loadString('json/parse.json');
}
Future loadyourData() async {
setState(() {
_isLoading = true;
});
// this is the local json that i have loaded from the assets folder
// you can make the http call here and else everything later is the same.
String jsonString = await loadPersonFromAssets();
final dataRates = dataFromJson(jsonString);
dataList.add(dataRates);
setState(() {
_isLoading = false;
});
}
#override
void initState() {
// TODO: implement initState
super.initState();
loadyourData();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: _isLoading
? CircularProgressIndicator()
: new ListView.builder(
itemCount: dataList.length,
itemBuilder: (BuildContext ctxt, int index) {
return Card(
child: Column(
children: <Widget>[
new Text(dataList[index].rates.tRY.toString()),
new Text(dataList[index].rates.uAH.toString()),
new Text(dataList[index].rates.wST.toString()),
new Text(dataList[index].rates.zMW.toString()),
],
),
);
}),
),
);
}
}
This is the main file where the data gets loaded and its been shown in the list view.
import 'dart:convert';
//// final data = dataFromJson(jsonString);
Data dataFromJson(String str) => Data.fromJson(json.decode(str));
String dataToJson(Data data) => json.encode(data.toJson());
class Data {
bool success;
int timestamp;
String base;
String date;
Rates rates;
Data({this.success, this.timestamp, this.base, this.date, this.rates});
Data.fromJson(Map<String, dynamic> json) {
success = json['success'];
timestamp = json['timestamp'];
base = json['base'];
date = json['date'];
rates = json['rates'] != null ? new Rates.fromJson(json['rates']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['success'] = this.success;
data['timestamp'] = this.timestamp;
data['base'] = this.base;
data['date'] = this.date;
if (this.rates != null) {
data['rates'] = this.rates.toJson();
}
return data;
}
}
class Rates {
double aED;
double aFN;
double aLL;
double aMD;
double aNG;
double aOA;
double aRS;
double aUD;
double aWG;
double aZN;
double bAM;
double bBD;
double bDT;
double bGN;
double bHD;
double bIF;
double bMD;
double bND;
double bOB;
double bRL;
double bSD;
double bTC;
double bTN;
double bWP;
double bYN;
double bYR;
double bZD;
double cAD;
double cDF;
double cHF;
double cLF;
double cLP;
double cNY;
double cOP;
double cRC;
double cUC;
double cUP;
double cVE;
double cZK;
double dJF;
double dKK;
double dOP;
double dZD;
double eGP;
double eRN;
double eTB;
int eUR;
double fJD;
double fKP;
double gBP;
double gEL;
double gGP;
double gHS;
double gIP;
double gMD;
double gNF;
double gTQ;
double gYD;
double hKD;
double hNL;
double hRK;
double hTG;
double hUF;
double iDR;
double iLS;
double iMP;
double iNR;
double iQD;
double iRR;
double iSK;
double jEP;
double jMD;
double jOD;
double jPY;
double kES;
double kGS;
double kHR;
double kMF;
double kPW;
double kRW;
double kWD;
double kYD;
double kZT;
double lAK;
double lBP;
double lKR;
double lRD;
double lSL;
double lTL;
double lVL;
double lYD;
double mAD;
double mDL;
double mGA;
double mKD;
double mMK;
double mNT;
double mOP;
double mRO;
double mUR;
double mVR;
double mWK;
double mXN;
double mYR;
double mZN;
double nAD;
double nGN;
double nIO;
double nOK;
double nPR;
double nZD;
double oMR;
double pAB;
double pEN;
double pGK;
double pHP;
double pKR;
double pLN;
double pYG;
double qAR;
double rON;
double rSD;
double rUB;
double rWF;
double sAR;
double sBD;
double sCR;
double sDG;
double sEK;
double sGD;
double sHP;
double sLL;
double sOS;
double sRD;
double sTD;
double sVC;
double sYP;
double sZL;
double tHB;
double tJS;
double tMT;
double tND;
double tOP;
double tRY;
double tTD;
double tWD;
double tZS;
double uAH;
double uGX;
double uSD;
double uYU;
double uZS;
double vEF;
double vND;
double vUV;
double wST;
double xAF;
double xAG;
double xAU;
double xCD;
double xDR;
double xOF;
double xPF;
double yER;
double zAR;
double zMK;
double zMW;
double zWL;
Rates(
{this.aED,
this.aFN,
this.aLL,
this.aMD,
this.aNG,
this.aOA,
this.aRS,
this.aUD,
this.aWG,
this.aZN,
this.bAM,
this.bBD,
this.bDT,
this.bGN,
this.bHD,
this.bIF,
this.bMD,
this.bND,
this.bOB,
this.bRL,
this.bSD,
this.bTC,
this.bTN,
this.bWP,
this.bYN,
this.bYR,
this.bZD,
this.cAD,
this.cDF,
this.cHF,
this.cLF,
this.cLP,
this.cNY,
this.cOP,
this.cRC,
this.cUC,
this.cUP,
this.cVE,
this.cZK,
this.dJF,
this.dKK,
this.dOP,
this.dZD,
this.eGP,
this.eRN,
this.eTB,
this.eUR,
this.fJD,
this.fKP,
this.gBP,
this.gEL,
this.gGP,
this.gHS,
this.gIP,
this.gMD,
this.gNF,
this.gTQ,
this.gYD,
this.hKD,
this.hNL,
this.hRK,
this.hTG,
this.hUF,
this.iDR,
this.iLS,
this.iMP,
this.iNR,
this.iQD,
this.iRR,
this.iSK,
this.jEP,
this.jMD,
this.jOD,
this.jPY,
this.kES,
this.kGS,
this.kHR,
this.kMF,
this.kPW,
this.kRW,
this.kWD,
this.kYD,
this.kZT,
this.lAK,
this.lBP,
this.lKR,
this.lRD,
this.lSL,
this.lTL,
this.lVL,
this.lYD,
this.mAD,
this.mDL,
this.mGA,
this.mKD,
this.mMK,
this.mNT,
this.mOP,
this.mRO,
this.mUR,
this.mVR,
this.mWK,
this.mXN,
this.mYR,
this.mZN,
this.nAD,
this.nGN,
this.nIO,
this.nOK,
this.nPR,
this.nZD,
this.oMR,
this.pAB,
this.pEN,
this.pGK,
this.pHP,
this.pKR,
this.pLN,
this.pYG,
this.qAR,
this.rON,
this.rSD,
this.rUB,
this.rWF,
this.sAR,
this.sBD,
this.sCR,
this.sDG,
this.sEK,
this.sGD,
this.sHP,
this.sLL,
this.sOS,
this.sRD,
this.sTD,
this.sVC,
this.sYP,
this.sZL,
this.tHB,
this.tJS,
this.tMT,
this.tND,
this.tOP,
this.tRY,
this.tTD,
this.tWD,
this.tZS,
this.uAH,
this.uGX,
this.uSD,
this.uYU,
this.uZS,
this.vEF,
this.vND,
this.vUV,
this.wST,
this.xAF,
this.xAG,
this.xAU,
this.xCD,
this.xDR,
this.xOF,
this.xPF,
this.yER,
this.zAR,
this.zMK,
this.zMW,
this.zWL});
Rates.fromJson(Map<String, dynamic> json) {
aED = json['AED'];
aFN = json['AFN'];
aLL = json['ALL'];
aMD = json['AMD'];
aNG = json['ANG'];
aOA = json['AOA'];
aRS = json['ARS'];
aUD = json['AUD'];
aWG = json['AWG'];
aZN = json['AZN'];
bAM = json['BAM'];
bBD = json['BBD'];
bDT = json['BDT'];
bGN = json['BGN'];
bHD = json['BHD'];
bIF = json['BIF'];
bMD = json['BMD'];
bND = json['BND'];
bOB = json['BOB'];
bRL = json['BRL'];
bSD = json['BSD'];
bTC = json['BTC'];
bTN = json['BTN'];
bWP = json['BWP'];
bYN = json['BYN'];
bYR = json['BYR'];
bZD = json['BZD'];
cAD = json['CAD'];
cDF = json['CDF'];
cHF = json['CHF'];
cLF = json['CLF'];
cLP = json['CLP'];
cNY = json['CNY'];
cOP = json['COP'];
cRC = json['CRC'];
cUC = json['CUC'];
cUP = json['CUP'];
cVE = json['CVE'];
cZK = json['CZK'];
dJF = json['DJF'];
dKK = json['DKK'];
dOP = json['DOP'];
dZD = json['DZD'];
eGP = json['EGP'];
eRN = json['ERN'];
eTB = json['ETB'];
eUR = json['EUR'];
fJD = json['FJD'];
fKP = json['FKP'];
gBP = json['GBP'];
gEL = json['GEL'];
gGP = json['GGP'];
gHS = json['GHS'];
gIP = json['GIP'];
gMD = json['GMD'];
gNF = json['GNF'];
gTQ = json['GTQ'];
gYD = json['GYD'];
hKD = json['HKD'];
hNL = json['HNL'];
hRK = json['HRK'];
hTG = json['HTG'];
hUF = json['HUF'];
iDR = json['IDR'];
iLS = json['ILS'];
iMP = json['IMP'];
iNR = json['INR'];
iQD = json['IQD'];
iRR = json['IRR'];
iSK = json['ISK'];
jEP = json['JEP'];
jMD = json['JMD'];
jOD = json['JOD'];
jPY = json['JPY'];
kES = json['KES'];
kGS = json['KGS'];
kHR = json['KHR'];
kMF = json['KMF'];
kPW = json['KPW'];
kRW = json['KRW'];
kWD = json['KWD'];
kYD = json['KYD'];
kZT = json['KZT'];
lAK = json['LAK'];
lBP = json['LBP'];
lKR = json['LKR'];
lRD = json['LRD'];
lSL = json['LSL'];
lTL = json['LTL'];
lVL = json['LVL'];
lYD = json['LYD'];
mAD = json['MAD'];
mDL = json['MDL'];
mGA = json['MGA'];
mKD = json['MKD'];
mMK = json['MMK'];
mNT = json['MNT'];
mOP = json['MOP'];
mRO = json['MRO'];
mUR = json['MUR'];
mVR = json['MVR'];
mWK = json['MWK'];
mXN = json['MXN'];
mYR = json['MYR'];
mZN = json['MZN'];
nAD = json['NAD'];
nGN = json['NGN'];
nIO = json['NIO'];
nOK = json['NOK'];
nPR = json['NPR'];
nZD = json['NZD'];
oMR = json['OMR'];
pAB = json['PAB'];
pEN = json['PEN'];
pGK = json['PGK'];
pHP = json['PHP'];
pKR = json['PKR'];
pLN = json['PLN'];
pYG = json['PYG'];
qAR = json['QAR'];
rON = json['RON'];
rSD = json['RSD'];
rUB = json['RUB'];
rWF = json['RWF'];
sAR = json['SAR'];
sBD = json['SBD'];
sCR = json['SCR'];
sDG = json['SDG'];
sEK = json['SEK'];
sGD = json['SGD'];
sHP = json['SHP'];
sLL = json['SLL'];
sOS = json['SOS'];
sRD = json['SRD'];
sTD = json['STD'];
sVC = json['SVC'];
sYP = json['SYP'];
sZL = json['SZL'];
tHB = json['THB'];
tJS = json['TJS'];
tMT = json['TMT'];
tND = json['TND'];
tOP = json['TOP'];
tRY = json['TRY'];
tTD = json['TTD'];
tWD = json['TWD'];
tZS = json['TZS'];
uAH = json['UAH'];
uGX = json['UGX'];
uSD = json['USD'];
uYU = json['UYU'];
uZS = json['UZS'];
vEF = json['VEF'];
vND = json['VND'];
vUV = json['VUV'];
wST = json['WST'];
xAF = json['XAF'];
xAG = json['XAG'];
xAU = json['XAU'];
xCD = json['XCD'];
xDR = json['XDR'];
xOF = json['XOF'];
xPF = json['XPF'];
yER = json['YER'];
zAR = json['ZAR'];
zMK = json['ZMK'];
zMW = json['ZMW'];
zWL = json['ZWL'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['AED'] = this.aED;
data['AFN'] = this.aFN;
data['ALL'] = this.aLL;
data['AMD'] = this.aMD;
data['ANG'] = this.aNG;
data['AOA'] = this.aOA;
data['ARS'] = this.aRS;
data['AUD'] = this.aUD;
data['AWG'] = this.aWG;
data['AZN'] = this.aZN;
data['BAM'] = this.bAM;
data['BBD'] = this.bBD;
data['BDT'] = this.bDT;
data['BGN'] = this.bGN;
data['BHD'] = this.bHD;
data['BIF'] = this.bIF;
data['BMD'] = this.bMD;
data['BND'] = this.bND;
data['BOB'] = this.bOB;
data['BRL'] = this.bRL;
data['BSD'] = this.bSD;
data['BTC'] = this.bTC;
data['BTN'] = this.bTN;
data['BWP'] = this.bWP;
data['BYN'] = this.bYN;
data['BYR'] = this.bYR;
data['BZD'] = this.bZD;
data['CAD'] = this.cAD;
data['CDF'] = this.cDF;
data['CHF'] = this.cHF;
data['CLF'] = this.cLF;
data['CLP'] = this.cLP;
data['CNY'] = this.cNY;
data['COP'] = this.cOP;
data['CRC'] = this.cRC;
data['CUC'] = this.cUC;
data['CUP'] = this.cUP;
data['CVE'] = this.cVE;
data['CZK'] = this.cZK;
data['DJF'] = this.dJF;
data['DKK'] = this.dKK;
data['DOP'] = this.dOP;
data['DZD'] = this.dZD;
data['EGP'] = this.eGP;
data['ERN'] = this.eRN;
data['ETB'] = this.eTB;
data['EUR'] = this.eUR;
data['FJD'] = this.fJD;
data['FKP'] = this.fKP;
data['GBP'] = this.gBP;
data['GEL'] = this.gEL;
data['GGP'] = this.gGP;
data['GHS'] = this.gHS;
data['GIP'] = this.gIP;
data['GMD'] = this.gMD;
data['GNF'] = this.gNF;
data['GTQ'] = this.gTQ;
data['GYD'] = this.gYD;
data['HKD'] = this.hKD;
data['HNL'] = this.hNL;
data['HRK'] = this.hRK;
data['HTG'] = this.hTG;
data['HUF'] = this.hUF;
data['IDR'] = this.iDR;
data['ILS'] = this.iLS;
data['IMP'] = this.iMP;
data['INR'] = this.iNR;
data['IQD'] = this.iQD;
data['IRR'] = this.iRR;
data['ISK'] = this.iSK;
data['JEP'] = this.jEP;
data['JMD'] = this.jMD;
data['JOD'] = this.jOD;
data['JPY'] = this.jPY;
data['KES'] = this.kES;
data['KGS'] = this.kGS;
data['KHR'] = this.kHR;
data['KMF'] = this.kMF;
data['KPW'] = this.kPW;
data['KRW'] = this.kRW;
data['KWD'] = this.kWD;
data['KYD'] = this.kYD;
data['KZT'] = this.kZT;
data['LAK'] = this.lAK;
data['LBP'] = this.lBP;
data['LKR'] = this.lKR;
data['LRD'] = this.lRD;
data['LSL'] = this.lSL;
data['LTL'] = this.lTL;
data['LVL'] = this.lVL;
data['LYD'] = this.lYD;
data['MAD'] = this.mAD;
data['MDL'] = this.mDL;
data['MGA'] = this.mGA;
data['MKD'] = this.mKD;
data['MMK'] = this.mMK;
data['MNT'] = this.mNT;
data['MOP'] = this.mOP;
data['MRO'] = this.mRO;
data['MUR'] = this.mUR;
data['MVR'] = this.mVR;
data['MWK'] = this.mWK;
data['MXN'] = this.mXN;
data['MYR'] = this.mYR;
data['MZN'] = this.mZN;
data['NAD'] = this.nAD;
data['NGN'] = this.nGN;
data['NIO'] = this.nIO;
data['NOK'] = this.nOK;
data['NPR'] = this.nPR;
data['NZD'] = this.nZD;
data['OMR'] = this.oMR;
data['PAB'] = this.pAB;
data['PEN'] = this.pEN;
data['PGK'] = this.pGK;
data['PHP'] = this.pHP;
data['PKR'] = this.pKR;
data['PLN'] = this.pLN;
data['PYG'] = this.pYG;
data['QAR'] = this.qAR;
data['RON'] = this.rON;
data['RSD'] = this.rSD;
data['RUB'] = this.rUB;
data['RWF'] = this.rWF;
data['SAR'] = this.sAR;
data['SBD'] = this.sBD;
data['SCR'] = this.sCR;
data['SDG'] = this.sDG;
data['SEK'] = this.sEK;
data['SGD'] = this.sGD;
data['SHP'] = this.sHP;
data['SLL'] = this.sLL;
data['SOS'] = this.sOS;
data['SRD'] = this.sRD;
data['STD'] = this.sTD;
data['SVC'] = this.sVC;
data['SYP'] = this.sYP;
data['SZL'] = this.sZL;
data['THB'] = this.tHB;
data['TJS'] = this.tJS;
data['TMT'] = this.tMT;
data['TND'] = this.tND;
data['TOP'] = this.tOP;
data['TRY'] = this.tRY;
data['TTD'] = this.tTD;
data['TWD'] = this.tWD;
data['TZS'] = this.tZS;
data['UAH'] = this.uAH;
data['UGX'] = this.uGX;
data['USD'] = this.uSD;
data['UYU'] = this.uYU;
data['UZS'] = this.uZS;
data['VEF'] = this.vEF;
data['VND'] = this.vND;
data['VUV'] = this.vUV;
data['WST'] = this.wST;
data['XAF'] = this.xAF;
data['XAG'] = this.xAG;
data['XAU'] = this.xAU;
data['XCD'] = this.xCD;
data['XDR'] = this.xDR;
data['XOF'] = this.xOF;
data['XPF'] = this.xPF;
data['YER'] = this.yER;
data['ZAR'] = this.zAR;
data['ZMK'] = this.zMK;
data['ZMW'] = this.zMW;
data['ZWL'] = this.zWL;
return data;
}
}
This is the model class as you described being generated using the QuickType.io
{
"success": true,
"timestamp": 1579491366,
"base": "EUR",
"date": "2020-01-20",
"rates": {
"AED": 4.076715,
"AFN": 85.483484,
"ALL": 122.193571,
"AMD": 533.250113,
"ANG": 1.861912,
"AOA": 543.149165,
"ARS": 66.554012,
"AUD": 1.612575,
"AWG": 1.997739,
"AZN": 1.891541,
"BAM": 1.956271,
"BBD": 2.244417,
"BDT": 94.256534,
"BGN": 1.95712,
"BHD": 0.418215,
"BIF": 2091.50477,
"BMD": 1.109855,
"BND": 1.496611,
"BOB": 7.686131,
"BRL": 4.617881,
"BSD": 1.111605,
"BTC": 0.000128,
"BTN": 78.853356,
"BWP": 11.933279,
"BYN": 2.358431,
"BYR": 21753.158037,
"BZD": 2.240616,
"CAD": 1.450148,
"CDF": 1870.1058,
"CHF": 1.074151,
"CLF": 0.03116,
"CLP": 859.807674,
"CNY": 7.60562,
"COP": 3698.602892,
"CRC": 626.092058,
"CUC": 1.109855,
"CUP": 29.411158,
"CVE": 110.289846,
"CZK": 25.153089,
"DJF": 197.243828,
"DKK": 7.47292,
"DOP": 59.102242,
"DZD": 132.756482,
"EGP": 17.553574,
"ERN": 16.648484,
"ETB": 35.580878,
"EUR": 1,
"FJD": 2.400845,
"FKP": 0.853386,
"GBP": 0.85344,
"GEL": 3.185507,
"GGP": 0.853386,
"GHS": 6.274513,
"GIP": 0.853386,
"GMD": 56.768832,
"GNF": 10596.012114,
"GTQ": 8.553126,
"GYD": 232.002258,
"HKD": 8.621204,
"HNL": 27.374523,
"HRK": 7.440676,
"HTG": 110.172276,
"HUF": 336.324934,
"IDR": 15156.512862,
"ILS": 3.83415,
"IMP": 0.853386,
"INR": 78.888694,
"IQD": 1326.938867,
"IRR": 46730.444914,
"ISK": 137.600239,
"JEP": 0.853386,
"JMD": 148.788893,
"JOD": 0.786908,
"JPY": 122.268839,
"KES": 111.928983,
"KGS": 77.501466,
"KHR": 4516.341065,
"KMF": 490.944654,
"KPW": 998.924351,
"KRW": 1285.001115,
"KWD": 0.336752,
"KYD": 0.926309,
"KZT": 418.614288,
"LAK": 9866.9219,
"LBP": 1680.878623,
"LKR": 201.462178,
"LRD": 212.54145,
"LSL": 15.97097,
"LTL": 3.277113,
"LVL": 0.67134,
"LYD": 1.554827,
"MAD": 10.670003,
"MDL": 19.504293,
"MGA": 4137.817131,
"MKD": 61.513856,
"MMK": 1635.120186,
"MNT": 3046.383998,
"MOP": 8.894003,
"MRO": 396.218091,
"MUR": 40.453985,
"MVR": 17.158186,
"MWK": 818.560908,
"MXN": 20.714833,
"MYR": 4.503235,
"MZN": 69.304855,
"NAD": 15.971063,
"NGN": 401.213027,
"NIO": 37.499305,
"NOK": 9.876378,
"NPR": 126.171668,
"NZD": 1.677113,
"OMR": 0.427107,
"PAB": 1.11155,
"PEN": 3.693532,
"PGK": 3.790442,
"PHP": 56.486625,
"PKR": 171.854321,
"PLN": 4.241811,
"PYG": 7245.891258,
"QAR": 4.041018,
"RON": 4.781705,
"RSD": 117.639084,
"RUB": 68.328666,
"RWF": 1054.94992,
"SAR": 4.164231,
"SBD": 9.212953,
"SCR": 15.197176,
"SDG": 50.109732,
"SEK": 10.554249,
"SGD": 1.495142,
"SHP": 0.853386,
"SLL": 10793.340217,
"SOS": 643.716193,
"SRD": 8.277332,
"STD": 23929.350626,
"SVC": 9.726191,
"SYP": 571.574016,
"SZL": 16.003797,
"THB": 33.726831,
"TJS": 10.776029,
"TMT": 3.884493,
"TND": 3.118141,
"TOP": 2.546506,
"TRY": 6.540514,
"TTD": 7.515693,
"TWD": 33.222957,
"TZS": 2562.435767,
"UAH": 27.00242,
"UGX": 4084.820116,
"USD": 1.109855,
"UYU": 41.508976,
"UZS": 10587.184569,
"VEF": 11.084676,
"VND": 25718.115031,
"VUV": 128.934974,
"WST": 2.923778,
"XAF": 656.137309,
"XAG": 0.061583,
"XAU": 0.000712,
"XCD": 2.999439,
"XDR": 0.804121,
"XOF": 656.137309,
"XPF": 119.286872,
"YER": 277.851936,
"ZAR": 16.027309,
"ZMK": 9990.030637,
"ZMW": 16.312283,
"ZWL": 357.373312
}
}
And this is you json that you have shown in the question.
Let me know if the Solution works for you.
Thanks
JSON displays data get in Android and shows in TextView and TableLayout.JSON have Nine Records and its parsing using Retrofit2 and RXjava2.
All the data gets in android side and Store in ArrayList.
In ArrayList Size is Nine get All Data.
Textview shows data but in TableLayout only two record display another seven record is not display. in Third record goeson var tax_total its give Error : "kotlin.kotlinnullpointerexception"
What's the problem that the other data is not displayed?
private fun fetchYearData(){
val retrofit = APIClient.apIClient
if (retrofit != null) {
api = retrofit.create(APIInterface::class.java)
}
compositeDisposable!!.add(api.getSalesGSTData(1,1,"04/01/2018","31/03/2019")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe( {
displaySalesGSTData(it.salesGst) },
{
Toast.makeText(this,it.message,Toast.LENGTH_LONG).show() }))
}
private fun displaySalesGSTData(salesGSt : List<SalesGST>) {
salesGST = SalesGST()
tvSalesCompanyName.setText(salesGSt.get(1).Cmp_Name)
tvGSTIN.setText(salesGSt.get(1).GSTIN)
val rowHeader = TableRow(this#Sales)
rowHeader.setBackgroundColor(Color.parseColor("#c0c0c0"))
rowHeader.setLayoutParams(TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT))
val headerText = arrayOf<String>("Sr.No.", "Invoice Type", "Bill No.", "Bill Date", "Firm Name", "GST NO","TAX Total","CGST","SGST","IGST","Net Amount")
for (c in headerText)
{
val tv = TextView(this#Sales)
tv.setLayoutParams(TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT))
tv.setGravity(Gravity.CENTER)
// tv.setBackgroundResource(R.drawable.table_header)
tv.setTextColor(Color.parseColor("#3F51B5"))
tv.setTextSize(18F)
tv.setPadding(5, 5, 5, 5)
tv.setText(c)
rowHeader.addView(tv)
}
tableMarks.addView(rowHeader)
for (j in 0 until salesGSt.size)
{
var fName : String = salesGSt[j].FirmName!!
var invoice : String = salesGSt[j].InvoiceType!!
var bill_no : String = salesGSt[j].ChallanNo!!
var bill_date : String = salesGSt[j].ChallanDate!!
var gst_no : String = salesGSt[j].PartyGST!!
var tax_total : String = salesGSt[j].TaxTotal!!
var cgst : String = salesGSt[j].CGSTTotal!!
var igst : String = salesGSt[j].IGSTTotal!!
var sgst : String = salesGSt[j].SGSTTotal!!
var net_amount : String = salesGSt[j].ChallanAmount!!
var sr : Int = j
// dara rows
val row = TableRow(this#Sales)
row.setLayoutParams(TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT))
val colText = arrayOf<String>(sr.toString(),(invoice), bill_no, bill_date, fName, gst_no,tax_total,cgst,sgst,igst,net_amount)
for (text in colText)
{
val tv = TextView(this#Sales)
tv.setLayoutParams(TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT))
tv.setGravity(Gravity.CENTER)
// tv.setBackgroundResource(R.drawable.table_shape)
tv.setTextSize(18F)
tv.setTextColor(Color.parseColor("#000000"))
tv.setPadding(5, 5, 5, 5)
tv.setText(text)
row.addView(tv)
}
tableMarks.addView(row)
}
JSON :
{"success":1,"salesGst":[{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"1","ChallanDate":"2019-03-15 00:00:00","ChallanAmount":"2778.75","TaxTotal":"2778.75","InvoiceType":"Retail Invoice","CGSTTotal":"0.0","PartyGST":"CDE","SGSTTotal":"0.0","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"1","ChallanDate":"2019-03-13 00:00:00","ChallanAmount":"2203.0","TaxTotal":"2118.5","InvoiceType":"Tax Invoice","CGSTTotal":"52.96","PartyGST":"CDE","SGSTTotal":"52.96","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"VIKAS","ChallanNo":"2","ChallanDate":"2019-03-16 00:00:00","ChallanAmount":"6975.0","TaxTotal":"6975.0","InvoiceType":"Retail Invoice","CGSTTotal":"0.0","PartyGST":null,"SGSTTotal":"0.0","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES MH","ChallanNo":"2","ChallanDate":"2019-03-13 00:00:00","ChallanAmount":"420.0","TaxTotal":"403.75","InvoiceType":"Tax Invoice","CGSTTotal":"0.0","PartyGST":"ABC","SGSTTotal":"0.0","IGSTTotal":"20.19"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"3","ChallanDate":"2019-03-14 00:00:00","ChallanAmount":"4788.0","TaxTotal":"4560.0","InvoiceType":"Tax Invoice","CGSTTotal":"114.0","PartyGST":"CDE","SGSTTotal":"114.0","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"4","ChallanDate":"2019-03-15 00:00:00","ChallanAmount":"241.9","TaxTotal":"230.38","InvoiceType":"Tax Invoice","CGSTTotal":"5.76","PartyGST":"CDE","SGSTTotal":"5.76","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"5","ChallanDate":"2019-03-15 00:00:00","ChallanAmount":"5563.68","TaxTotal":"5101.5","InvoiceType":"Tax Invoice","CGSTTotal":"231.28","PartyGST":"CDE","SGSTTotal":"231.28","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"6","ChallanDate":"2019-03-16 00:00:00","ChallanAmount":"13238.0","TaxTotal":"12459.25","InvoiceType":"Tax Invoice","CGSTTotal":"389.29","PartyGST":"CDE","SGSTTotal":"389.29","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES MH","ChallanNo":"7","ChallanDate":"2019-03-16 00:00:00","ChallanAmount":"2074.0","TaxTotal":"1975.0","InvoiceType":"Tax Invoice","CGSTTotal":"0.0","PartyGST":"ABC","SGSTTotal":"0.0","IGSTTotal":"98.75"}]}
xml :
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:scrollbarStyle="insideInset"
android:fadeScrollbars="true"
android:scrollbarSize="10dp"
android:fitsSystemWindows="true">
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tableMarks"
android:stretchColumns="*"
android:layout_marginTop="20dp"
android:orientation="horizontal"
></TableLayout>
</HorizontalScrollView>
</ScrollView>
JSON Data Parsing Using Retofit2 and Rxjava2. This Data get In ArrayList successfully. its ArrayList Size is Nine but its display only two Record in Table. After Two Record its Kotlin.NullPointerException.
JSON Data:
{"success":1,"salesGst":[{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"1","ChallanDate":"2019-03-15 00:00:00","ChallanAmount":"2778.75","TaxTotal":"2778.75","InvoiceType":"Retail Invoice","CGSTTotal":"0.0","PartyGST":"CDE","SGSTTotal":"0.0","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"1","ChallanDate":"2019-03-13 00:00:00","ChallanAmount":"2203.0","TaxTotal":"2118.5","InvoiceType":"Tax Invoice","CGSTTotal":"52.96","PartyGST":"CDE","SGSTTotal":"52.96","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"VIKAS","ChallanNo":"2","ChallanDate":"2019-03-16 00:00:00","ChallanAmount":"6975.0","TaxTotal":"6975.0","InvoiceType":"Retail Invoice","CGSTTotal":"0.0","PartyGST":null,"SGSTTotal":"0.0","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES MH","ChallanNo":"2","ChallanDate":"2019-03-13 00:00:00","ChallanAmount":"420.0","TaxTotal":"403.75","InvoiceType":"Tax Invoice","CGSTTotal":"0.0","PartyGST":"ABC","SGSTTotal":"0.0","IGSTTotal":"20.19"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"3","ChallanDate":"2019-03-14 00:00:00","ChallanAmount":"4788.0","TaxTotal":"4560.0","InvoiceType":"Tax Invoice","CGSTTotal":"114.0","PartyGST":"CDE","SGSTTotal":"114.0","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"4","ChallanDate":"2019-03-15 00:00:00","ChallanAmount":"241.9","TaxTotal":"230.38","InvoiceType":"Tax Invoice","CGSTTotal":"5.76","PartyGST":"CDE","SGSTTotal":"5.76","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"5","ChallanDate":"2019-03-15 00:00:00","ChallanAmount":"5563.68","TaxTotal":"5101.5","InvoiceType":"Tax Invoice","CGSTTotal":"231.28","PartyGST":"CDE","SGSTTotal":"231.28","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"6","ChallanDate":"2019-03-16 00:00:00","ChallanAmount":"13238.0","TaxTotal":"12459.25","InvoiceType":"Tax Invoice","CGSTTotal":"389.29","PartyGST":"CDE","SGSTTotal":"389.29","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES MH","ChallanNo":"7","ChallanDate":"2019-03-16 00:00:00","ChallanAmount":"2074.0","TaxTotal":"1975.0","InvoiceType":"Tax Invoice","CGSTTotal":"0.0","PartyGST":"ABC","SGSTTotal":"0.0","IGSTTotal":"98.75"}]}
Please Guide Me,After Getting How to Show in TableLayout.
In ArrayList Nine Record but in Table show only Two Record another seven record is not display. in third record taxtotal give kotlin.nullpointerException. what missing?
private fun displaySalesGSTData(salesGSt : List<SalesGST>) {
salesGST = SalesGST()
tvSalesCompanyName.setText(salesGSt.get(1).Cmp_Name)
tvGSTIN.setText(salesGSt.get(1).GSTIN)
val rowHeader = TableRow(this#Sales)
rowHeader.setBackgroundColor(Color.parseColor("#c0c0c0"))
rowHeader.setLayoutParams(TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT))
val headerText = arrayOf<String>("Sr.No.", "Invoice Type", "Bill No.", "Bill Date", "Firm Name", "GST NO","TAX Total","CGST","SGST","IGST","Net Amount")
for (c in headerText)
{
val tv = TextView(this#Sales)
tv.setLayoutParams(TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT))
tv.setGravity(Gravity.CENTER)
// tv.setBackgroundResource(R.drawable.table_header)
tv.setTextColor(Color.parseColor("#3F51B5"))
tv.setTextSize(18F)
tv.setPadding(5, 5, 5, 5)
tv.setText(c)
rowHeader.addView(tv)
}
tableMarks.addView(rowHeader)
for (j in 0 until salesGSt.size)
{
/*val jsonObject1 = jsonArray.getJSONObject(j)
val date = jsonObject1.getString("ExamDate")
val inputFormatter1 = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
val date1 = inputFormatter1.parse(date)
val outputFormatter1 = SimpleDateFormat("dd-MMM-yyyy")
ExamDate = outputFormatter1.format(date1)*/
/* String replaceDate = date.replace("/Date(", "").replace(")/", "");
Long getDate = Long.valueOf(replaceDate);
ExamDate = dateFormat.format(getDate);*/
/*Subject = jsonObject1.getString("subject")
ExamName = jsonObject1.getString("ExamName")
TotalMark = jsonObject1.getLong("TotalMarks")
PassingMark = jsonObject1.getLong("PassingMarks")
Mark = jsonObject1.getLong("Marks")*/
var fName : String = salesGSt.get(j).FirmName!!
var invoice : String = salesGSt.get(j).InvoiceType!!
var bill_no : String = salesGSt.get(j).ChallanNo!!
var bill_date : String = salesGSt.get(j).ChallanDate!!
var gst_no : String = salesGSt.get(j).PartyGST!!
var tax_total : Double = salesGSt.get(j).TaxTotal!!.toDouble()
var cgst : String = salesGSt.get(j).CGSTTotal!!
var igst : String = salesGSt.get(j).IGSTTotal!!
var sgst : String = salesGSt.get(j).SGSTTotal!!
var net_amount : String = salesGSt.get(j).ChallanAmount!!
var sr : Int = j + 1
// dara rows
val row = TableRow(this#Sales)
row.setLayoutParams(TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT))
val colText = arrayOf<String>(sr.toString(),(invoice), bill_no, bill_date, fName, gst_no, tax_total.toString(),cgst,sgst,igst,net_amount)
for (text in colText)
{
val tv = TextView(this#Sales)
tv.setLayoutParams(TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT))
tv.setGravity(Gravity.CENTER)
// tv.setBackgroundResource(R.drawable.table_shape)
tv.setTextSize(18F)
tv.setTextColor(Color.parseColor("#3F51B5"))
tv.setPadding(5, 5, 5, 5)
tv.setText(text)
row.addView(tv)
}
tableMarks.addView(row)
}
}
The 3rd item, salesGst[2], is "PartyGST": null. Your json deserializer library won't handle non-null fields as it's written in Java. I assume you have a data class where PartGST is defined as non-null, yet the deserializer will still parse it as null. Therefore, when you access PartyGST then you will receive a NullPointerException because Kotlin is expecting it to be non-null. This is a good article, which explains in more detail:
I've trusted you! You promised no null pointer exceptions!
A solution to this would be to have two models. The DTO (for JSON response) where all fields are optional and your internal model (used by your app), where you define which fields you want to be optional. Then you can have a mapper to handle the case where a field is null in the DTO, but non-null in your internal model:
// Models for your API response
data class SalesGstsDTO(val gsts: List<GstDTO>)
data class GstDTO(val name: String?, val surname: String?)
// Internal models used by your app
data class SalesGsts(val gsts: List<Gst>)
data class Gst(val name: String, val surname: String?)
class SalesGstDTOMapper {
fun mapToSalesGsts(salesGstsDTO: SalesGstsDTO): SalesGsts {
val gsts = mutableListOf<Gst>()
salesGstsDTO.gsts.map {
val name = it.name ?: return#map // Skips this item. You could handle this how you wish
val surname = it.surname
val gst = Gst(name, surname)
gsts.add(gst)
}
return SalesGsts(gsts)
}
}
This also allows you to decouple your app from the JSON response.