I am learning secha touch, I want to create a page where after user enter login credentials the JSON response will be received which is as follows
{"items":[{"id":"78e221c8-bbc1-4754-8471-48c863886869","createTime":"2014-05-22T14:57:39.039Z","createUser":"Jon","status":"SAVED","changeTime":"2014-05-22T14:57:39.039Z","changeUser":"Jon","projectId":"63886869-bbc1-4754-8471-48c878e221c8","reportVersionNumber":"1","reportVersionName":"First Version","reportName":"FooBarBaz","reportHash":"qiyh4XPJGsOZ2MEAyLkfWqeQ"}],"totalItems":1
}
currently i have created a page where i have used a listItem and displaying the items in it from the Simple array where data has been given harcoded
and using itemTPL to get it
like this <div class="arHeadline">{projectId}
my current store is
data: [
{
Headline: 'Panel',
Author: 'Sencha',
Content: 'Panels are most useful as Overlays - containers that float over your appl..'
}
but i want to get the data from the json so i created a JSON store
Ext.define('MobileChecklist.store.MyJsonPStore', {
extend: 'Ext.data.Store',
requires: [
'MobileChecklist.model.MyModel',
'Ext.data.proxy.JsonP',
'Ext.data.reader.Json',
'Ext.data.Field'
],
config: {
autoLoad: true,
data: [
{
items: [
{
id: '78e221c8-bbc1-4754-8471-48c863886869',
createTime: '2014-05-22T14:57:39.039Z',
createUser: 'Jon',
status: 'SAVED',
changeTime: '2014-05-22T14:57:39.039Z',
changeUser: 'Jon',
projectId: '63886869-bbc1-4754-8471-48c878e221c8',
reportVersionNumber: '1',
reportVersionName: 'First Version',
reportName: 'FooBarBaz',
reportHash: 'qiyh4XPJGsOZ2MEAyLkfWqeQ'
}
],
totalItems: 1
}
],
model: 'MobileChecklist.model.MyModel',
storeId: 'MyJsonPStore',
proxy: {
type: 'jsonp',
url: 'data/getPort.json',
reader: {
type: 'json',
idProperty: 'id',
rootProperty: 'items',
totalProperty: 'totalItems',
record: 'items'
}
},
fields: [
{
name: 'reportName'
},
{
name: 'projectId'
}
]
}
});
and my model is
Ext.define('MobileChecklist.model.MyModel', {
extend: 'Ext.data.Model',
requires: [
'Ext.data.Field'
],
config: {
fields: [
{
mapping: 'items.reportName',
name: 'reportName',
type: 'string'
},
{
mapping: 'items.projectId',
name: 'projectId',
type: 'string'
}
]
}
});
I want to decode the json response and display it in the ListItem the way i did with the string array
how can I do it please help
EDIT:
if I remove the items from my json response and make it like an array rather than object it works and displays it in the list view
[{"id":"78e221c8-bbc1-4754-8471-48c863886869","createTime":"2014-05-22T14:57:39.039Z","createUser":"Jon","status":"SAVED","changeTime":"2014-05-22T14:57:39.039Z","changeUser":"Jon","projectId":"63886869-bbc1-4754-8471-48c878e221c8","reportVersionNumber":"1","reportVersionName":"First Version","reportName":"FooBarBaz","reportHash":"qiyh4XPJGsOZ2MEAyLkfWqeQ"}],"totalItems":1}]
Set the store data with data.items in your controller, like this: -
Ext.Ajax.request({
url: someurl,
params: {
format: "json"
},
success: function(response) {
Ext.getStore("MyJsonPStore").setData(response.items);
},
failure: function(err) {
console.log("Error", err);
}
});
This is the way to work with json data.
Found your problem, change your store proxy to this:-
proxy: {
type: 'rest', //change it
url: 'data/getPort.json',
reader: {
type: 'json',
idProperty: 'id',
rootProperty: 'items',
totalProperty: 'totalItems'
}
}
No need to map the datas.
I've never worked with the secha touch framework before but JSON Parsing is quite simple. If you already have the JSON coming to your device, try this:
http://developer.android.com/reference/android/util/JsonReader.html
Then create an adapter to your ListView
Related
Recently,I got the problem when I tried to implement a comment function in an Android APP.
The definition of comments in user.js is as follow
comnents: [{
ownerID: {
type: String,
required: true,
},
commenterID: {
type: String,
required: true,
},
commenterName: String,
content: {
type: String,
require: true,
}
}],
And I have a request like that:
{
"_id":"60d204d6efc6c70022b08dc4",
"comments":[
{
"ownerID":"60d204d6efc6c70022b08dc4",
"commenterID":"60d205afefc6c70022b08dc8",
"commenterName":"Bob",
"content":"Hello World!"
},
{
"ownerID":"60d204d6efc6c70022b08dc4",
"commenterID":"60d20892efc6c70022b08dd2",
"commenterName":"Alice",
"content":"Hello Earth!"
}
]
}
Here is my API
router.post("/writecomment",jsonParser,
async(req,res,next)=>{
const errors=validationResult(req);
if(!errors.isEmpty()){
return res.status(400).json({erros:errors.array()});
}
User.findOneAndUpdate(
{ "_id": req.body._id},
{
$set: {
comments:req.body.comments
}
},
{overwrite:true},
function(err,resp){
if(err) throw err;
if(resp) {
return res.send({
msg:' change successfully'
});
}else{
return res.status(403).json({ success: false, message: 'Failed to change'});
}
}
)
}
)
How do I convert "comments" from request to comments array? Or have a better way to implement this function?
PS: I use Mongoose + Express Framework to develope.
const commentArray = [...req.body.comments]
Will make this for you:
[
{
"ownerID": "60d204d6efc6c70022b08dc4",
"commenterID": "60d205afefc6c70022b08dc8",
"commenterName": "Bob",
"content": "Hello World!"
},
{
"ownerID": "60d204d6efc6c70022b08dc4",
"commenterID": "60d20892efc6c70022b08dd2",
"commenterName": "Alice",
"content": "Hello Earth!"
}
]
Basically what is happening here is, we are iterating over the response you are getting and saving the result in an array. If you want to learn more about the ... operator, check out this link:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
MissingSchemaError: Schema hasn't been registered for model products
getCartItems MissingSchemaError: Schema hasn't been registered for model "products".
Use mongoose.model(name, schema)
at NativeConnection.Connection.model (F:\ecommerceApp\ecommerce-backend\node_modules\mongoose\lib\connection.js:1242:11)
This is the controller
Cart
const mongoose = require('mongoose');
const cartSchema = new mongoose.Schema({
user: { type: mongoose.Schema.Types.ObjectId, ref: 'user', required: true },
cartItems: [
{
product : {
type :mongoose.Schema.Types.ObjectId,
ref : "product",
required:true
},
quantity : {
type:Number,
default:1
}
}
]
} ,{timestamps:true});
module.exports = mongoose.model('Cart' , cartSchema , 'cart');
Products
const mongoose = require('mongoose');
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
slug: {
type: String,
required: true,
unique: true
},
quantity: {
type: Number,
required: true
},
price: {
type: Number,
required: true
},
description: {
type: String,
required: true,
trim: true
},
offer: { type: Number },
productPictures: [{
img: { type: String }
}],
reviews: [{
userid: { type: mongoose.Schema.Types.ObjectId, ref: "User", review: String }
}],
category: { type: mongoose.Schema.Types.ObjectId, ref: "Categories" },
createdby: {
type: mongoose.Schema.Types.ObjectId, ref: "User", required: true
},
updatedAT: {
type: Date
}
}, { timestamps: true });
module.exports = mongoose.model('Product', productSchema);
Document
Products
{"_id":{"$oid":"6027d3a8cf712436607e6a6f"},"name":"Samsung Galaxy S21 Plus (Phantom Silver, 256 GB) (8 GB RAM)","slug":"Samsung-Galaxy-S21-Plus-(Phantom-Silver-256-GB)-(8-GB-RAM)","price":5000,"quantity":10,"description":"With the Samsung Galaxy S21 Plus Smartphone, you can click amazing shots and record stunning videos at up to 8K resolution as it comes with a 64 MP camera setup. This smartphone is 5G-ready, enabling you to stream videos and download content from the Web with minimal lag. Moreover, its powerful processor and long-lasting battery make it a delight to use this smartphone.","productPictures":[{"_id":{"$oid":"6027d3a8cf712436607e6a70"},"img":"wGFfBkAhQ-samsung-galaxy-j6-sm-j600gzbgins-original-imaf6zpf6q8tjcva.jpeg"}],"category":{"$oid":"6020d53117616c5228246ac4"},"createdby":{"$oid":"601400873e5a422f9c81ae1c"},"reviews":[],"createdAt":{"$date":"2021-02-13T13:27:04.135Z"},"updatedAt":{"$date":"2021-02-13T13:27:04.135Z"},"__v":0}
Cart
{"_id":{"$oid":"6027d3bacf712436607e6a71"},"user":{"$oid":"60238bea8f89fb538c845f5b"},"cartItems":[{"quantity":2,"_id":{"$oid":"6027d3d4cf712436607e6a73"},"product":{"$oid":"6027d3a8cf712436607e6a6f"}}],"createdAt":{"$date":"2021-02-13T13:27:22.393Z"},"updatedAt":{"$date":"2021-02-13T13:27:48.217Z"},"__v":0}
Router export method , Here is the error which is not populating the population not happening
Throws in when called from PostMan
exports.getCartItems = (req, res) => {
//const { user } = req.body.payload;
//if(user){
console.log('req.user._id' , req.user._id);
Cart.findOne({ user: req.user._id })
.populate("cartItems.product", "_id name price productPictures")
.exec((error, cart) => {
console.log('getCartItems' , error);
if (error) return res.status(400).json({ error });
if (cart) {
let cartItems = {};
cart.cartItems.forEach((item, index) => {
cartItems[item.product._id.toString()] = {
_id: item.product._id.toString(),
name: item.product.name,
img: item.product.productPictures[0].img,
price: item.product.price,
qty: item.quantity,
};
});
res.status(200).json({ cartItems });
}
});
//}
};
You have a typo. You mean products but typed proucts
I have this response, i have problem when i want to convert to pojo.
"equity": {
"0": {
"name": [
"Abc"
],
"code": [
"3410"
],
"ending_balance": [
301834470
]
},
"1": {
"name": [
"Xyz"
],
"code": [
"2180"
],
"ending_balance": [
0
]
},
"2": {
"name": [
"Pqr"
],
"code": [
"9220"
],
"ending_balance": [
0
]
},
"total_equity": 301834470
}
}
I'm confused about giving the right data type, because there are arrays("0","1","2") that contain objects and "total_equity" that contain number.
I've tried to give the map data type, but it will be error for "total_equity"
var equity: Map<String, EquityDto?>
If you know the solution for this problem please help me. Thank you
You can use
var equity: Map<String, Any>
While accessing the Any Data type u can compare the varrriable type(instance of) and use the value as following
if (valueofMap is Int){
//here is integer value
}
if (valueofMap is yourDataClass){
//your custom class
}
There can be a solution to this, but it will be a lengthy one.
One solution can be to transform the response to Map<String, Any> then you will have to check the type every time you have to use it and it can really annoying when you are using it in multiple classes.
Another solution can be to create a custom Custom Type Adapter which you can pass to the Retrofit Instance in the addConverterFactory method.
To create a custom adapter, you just have to follow the following steps:
Create a model in which you want to store the data. In your case it can be :
data class ApiResponse(
val data: Map<String, EquityDto?>,
val totalEquity:Int
)
Create the Adapter:
class StudentAdapter : TypeAdapter<ApiResponse?>() {
#Throws(IOException::class)
fun read(reader: JsonReader): ApiResponse {
val student:ApiResponse? = null
reader.beginObject()
var fieldname: String? = null
while (reader.hasNext()) {
var token = reader.peek()
if (token == JsonToken.NAME) {
//get the current token
fieldname = reader.nextName()
}
if ("total_equity" == fieldname) {
token = reader.peek()
student?.totalEquity = reader.nextInt()
}else {
token = reader.peek()
student?.data?.set(fieldname.toString(), reader.nextString())
}
}
reader.endObject()
return student
}
#Throws(IOException::class)
fun write(writer: JsonWriter, student: ApiResponse) {
writer.beginObject()
writer.name("data")
writer.value(student.data.toString())
writer.name("totalEquity")
writer.value(student.totalEquity)
writer.endObject()
}
}
If you know a better way to create a type adapter then you can surely use that.
I am creating an app using sencha-touch 2 and phonegap. The app is for an online newspaper. I have a jsonp request for the store of articles. The JSON request is from WordPress using the JSON API. When I view the app on a web browser the number of articles is correct but when I build it on the android phone only 5 articles appear, no matter the "count" parameter I input into the request.
Here is my ArticleList.js (which includes a piece of static information)
Ext.define('Commentator.store.Article', {
extend: 'Ext.data.Store',
requires: [
'Commentator.model.Article',
'Ext.data.proxy.JsonP'
],
config: {
storeId: 'ArticleStore',
autoLoad: false,
model: 'Commentator.model.Article',
proxy: {
timeout: 3000,
type: 'jsonp',
url: 'http://[site]/?json=get_category_posts?id=features&post_status=publish',
reader: {
type: 'json',
rootProperty: 'posts'
}
}
}
});
Here is my Main.js
Ext.define('Commentator.controller.Main', {
extend: 'Ext.app.Controller',
config: {
refs: {
list: 'articles',
side_list: 'side_menu',
navBtn : 'button[name="burgerButton]',
topbar: 'TopBar'
},
control: {
list: {
onDataRefresh: 'updateList',
tap: 'updateList'
},
topbar: {
initialize: 'swipeBar'
}
}
},
swipeBar: function(evt) {
evt.element.on({
swipe: function(e, node, options){
if (Ext.Viewport.getMenus().left._hidden) {
if(e.direction == "right") {
Ext.Viewport.showMenu("left");
}
} else {
Ext.Viewport.hideMenu("left");
}
}
});
},
updateList: function() {
console.log(this.getList());
},
//called when the Application is launched, remove if not needed
launch: function(app) {
Ext.getStore("ArticleStore").load(function(records, options, success) {
console.log(records);
if(!success) {
for(var i = 0; i < 5; i++) {
console.log("errror");
Ext.getStore("ArticleStore").load();
}
}
});
Commentator.view.SubNavigation.setMenu();
//});
}
});
Article.js (the store)
Ext.define('Commentator.store.Article', {
extend: 'Ext.data.Store',
requires: [
'Commentator.model.Article',
'Ext.data.proxy.JsonP'
],
config: {
storeId: 'ArticleStore',
autoLoad: false,
model: 'Commentator.model.Article',
proxy: {
timeout: 3000,
type: 'jsonp',
url: 'http://[site]/?json=get_category_posts?id=features&post_status=publish',
reader: {
type: 'json',
rootProperty: 'posts'
}
}
}
});
I found the solution to our problem. It was a problem with the WordPress JSON API. We switched over to Thermal API and now it works perfectly.
I was trying to parse the json data , to list in for android app
The response is as follows
{"records":[{"reg_no":"444444","name":"xyz, pqr","address":"Kathmandu-64, Kathmandu","sex":"Male","qualification":"B..E","university":"T.U","year":"2010","faculty":"Computer","date":"2012-08-17 11:29:38"}]}
Sencha code is as follows
{
xtype: 'nestedlist',
title: 'List',
iconCls: 'star',
displayField: 'name',
store: {
type: 'tree',
fields: [
'name', 'reg_no', 'faculty', 'address', 'university',
{name: 'leaf', defaultValue: true}
],
root: {
leaf: false
},
proxy: {
type: 'jsonp',
url: 'http://timus.com/api.php?name=serish',
reader: {
type: 'json',
rootProperty: 'records'
}
}
},
detailCard: {
xtype: 'panel',
scrollable: true,
styleHtmlContent: true
},
listeners: {
itemtap: function(nestedList, list, index, element, post) {
this.getDetailCard().setHtml(post.get('university'));
}
}
}
but is not parsing json.. the followong error is coming
uncaught syntax error : unexpected token
I had the same problem and reading some articles I realize that the proxy type must be "rest" if the url is a restful service.
I saw at: http://docs.sencha.com/ext-js/4-0/#!/api/Ext.data.reader.Reader