Error: Undefined variable in Titanium when trying to display a custom object

If you're new to Titanium and web development, you might be struggling with retrieving a custom object stored on ACS. Spending hours trying to figure it out can be frustrating, especially when you encounter errors like your table view not displaying correctly. The issue may lie within the "Cloud.Objects.Query" block where you expect 4 entries each with specific data fields like date, place, and review, but nothing seems to show up as intended. Your code compiles, but the expected content is missing. Alerts are showing undefined variables adding to the confusion. If anyone could spare some time to review and provide hints, it would be greatly appreciated.

    //Importing the module
var Cloud = require('ti.cloud');
Cloud.debug = true;  // optional; setting to false for production recommended

// Setting the master UIView background color when no windows/tab groups present
Titanium.UI.setBackgroundColor('#000');

exports.getDiaryWin = function() {

    //Creating the window
    var diary_window = Titanium.UI.createWindow({
        backgroundColor:'#FFF',
        title: "Travel Diary"
    });

    //Creating the title
    var title = Titanium.UI.createLabel({
        text: "My Travel Diary",
        top:10,
        color: '#008000',
        textAlign: 'center',
        font: {fontSize:55}
    });

    var tableView = Ti.UI.createTableView({
        top: '10%',
        scrollable: true,
        width: '100%',
        minRowHeight: '50',
        bottom: '10%'
    });

    //Fetching diary entries, populating the table view, and displaying it  
    var idList = [];
    var tableData = [];
    var displayData = [];
    var entry;

    //Retrieving diary ID 
    Cloud.Objects.query({
        classname: 'diaries',
        page: 1,
        per_page: 10
    },function(e){
        if (e.success){
            alert('Count: '+e.diaries.length);

        for (var i=0; i<e.diaries.length; i++)
            {
                entry = e.diaries[i];
                /*
                alert('id: ' + entry.id + '\n' +
                'date: ' + entry.date + '\n' +
                'place: ' + entry.place + '\n' +
                'review: ' + entry.review + '\n' +
                'created_at: ' + entry.created_at);
                */
                tableData.push({
                    date: entry.date,
                    place: entry.place,
                    review: entry.review
                });

                alert('tableData:' + tableData.date);   //ALERT: tableData: UNDEFINED

            }   
        } else {
            alert('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
        }   
    });


    /*
    tableData.push({
        date: 'Can u see this?'
    });
    */

    for (var i=0; i < tableData.length; i++){
        var row = Ti.UI.createTableViewRow({
            height:150,
            backgroundColor : '#FF9900',
            font: {fontSize:35},
            title: tableData[i].date
        });

        /*
        var dateField = Ti.UI.createLabel({
            text:tableData[i].date,
            font: {fontSize:35}, 
            color:'#888', 
            left:5, 
            width:Ti.UI.FILL
        });
        row.add(dateLabel);

        var placeLabel = Ti.UI.createLabel({
            text:tableData[i].place,
            font: {fontSize:35}, 
            color:'#888', left:5, width:Ti.UI.FILL
        });
        row.add(placeLabel);

        var reviewLabel = Ti.UI.createLabel({
            text:tableData[i].review,
            font: {fontSize:35}, 
            color:'#888', 
            left:5, 
            width:Ti.UI.FILL
        });
        row.add(reviewLabel);
        */
        displayData.push(row);
    }

    tableView.setData(displayData);

    //Adding a 'back' button
    var back_button = Titanium.UI.createButton({
        title: "Back",  
        buttom:20,
        height:200,
        left:40,
        right:40    
    });     

    //Adding Event Listener
    back_button.addEventListener('click', function(){
        //Calling an export function
        var win = require('home').getHomeWin;

        //Creating a new instance
        var nextWin = new win();
        nextWin.open();
    });


    diary_window.add(title);
    diary_window.add(tableView);
    diary_window.add(back_button);
    return diary_window;

};

------------EDITED CODE --------------

//Import the module
var Cloud = require('ti.cloud');
Cloud.debug = true;  // optional; if you add this line, set it to false for production 

// this sets the background color of the master UIView (when there are no windows/tab groups on it)
Titanium.UI.setBackgroundColor('#000');

exports.getDiaryWin = function() {

    //create window
    var diary_window = Titanium.UI.createWindow({
        backgroundColor:'#FFF',
        title: "Travel Diary"
    });

    //create title
    var title = Titanium.UI.createLabel({
        text: "My Travel Diary",
        top:10,
        color: '#008000',
        textAlign: 'center',
        font: {fontSize:55}
    });

    var tableView = Ti.UI.createTableView({
        top: '10%',
        scrollable: true,
        width: '100%',
        minRowHeight: '50',
        bottom: '10%'
    });

    //Get diary entries, add them to the table view and display it  
    var idList = [];
    var tableData = [];
    var displayData = [];
    var entry;

    //Get diary id 
    Cloud.Objects.query({
       classname: 'diaries',
       page: 1,
       per_page: 10
    }, function(e) {
        var row, dateLabel, placeLabel, reviewLabel;
        var displayData = [];

        if (e.success){    
            alert('Count: '+e.diaries.length);

            for (var i=0; i<e.diaries.length; i++) {
                entry = e.diaries[i];
                row = Ti.UI.createTableViewRow({
                    height:150,
                    backgroundColor : '#FF9900',
                    font: {fontSize:35},
                    title: entry.date
                });

                dateLabel = Ti.UI.createLabel({
                    text: entry.date,
                    font: {fontSize:35}, 
                    color:'#888', 
                    left:5, 
                    width:Ti.UI.FILL
                });
                row.add(dateLabel);

                placeLabel = Ti.UI.createLabel({
                    text: entry.place,
                    font: {fontSize:35}, 
                    color:'#888', left:5, width:Ti.UI.FILL
                });
                row.add(placeLabel);

                reviewLabel = Ti.UI.createLabel({
                    text: entry.review,
                    font: {fontSize:35}, 
                    color:'#888', 
                    left:5, 
                    width:Ti.UI.FILL
                });
                row.add(reviewLabel);

                displayData.push(row);
            }

            tableView.setData(displayData);
        } else {
            alert('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
        }   
    });

    //add a 'back' button
    var back_button = Titanium.UI.createButton({
        title: "Back",  
        buttom:20,
        height:200,
        left:40,
        right:40    
    });     

    //Add Event Listener
    back_button.addEventListener('click', function(){
        //call an export function
        var win = require('home').getHomeWin;

        //create new instance
        var nextWin = new win();
        nextWin.open();
    });


    diary_window.add(title);
    diary_window.add(tableView);
    diary_window.add(back_button);
    return diary_window;

};

Answer №1

An issue with the error "the variable is undefined" arises when trying to access the date property on the entire array instead of one of the objects within the array. To resolve this, adjust the code as follows:

alert('tableData:' + tableData[0].date);

Additionally, ensure that the entire for loop is inside the callback function. It is necessary to wait for a response from the Cloud API before populating the TableView:

Cloud.Objects.query({
       classname: 'diaries',
       page: 1,
       per_page: 10
}, function(e) {
    var row, dateField, placeLabel, reviewLabel;
    var displayData = [];

    if (e.success){    
        alert('Count: '+e.diaries.length);

        for (var i=0; i<e.diaries.length; i++) {
            entry = e.diaries[i];
            row = Ti.UI.createTableViewRow({
                height:150,
                backgroundColor : '#FF9900',
                font: {fontSize:35},
                title: entry.date
            });

            dateField = Ti.UI.createLabel({
                text: entry.date,
                font: {fontSize:35}, 
                color:'#888', 
                left:5, 
                width:Ti.UI.FILL
            });
            row.add(dateLabel);

            placeLabel = Ti.UI.createLabel({
                text: entry.place,
                font: {fontSize:35}, 
                color:'#888', left:5, width:Ti.UI.FILL
            });
            row.add(placeLabel);

            reviewLabel = Ti.UI.createLabel({
                text: entry.review,
                font: {fontSize:35}, 
                color:'#888', 
                left:5, 
                width:Ti.UI.FILL
            });
            row.add(reviewLabel);

            displayData.push(row);
        }

        tableView.setData(displayData);
    } else {
        alert('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
    }   
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vue Component Rendering Before Vuex Data is Ready

I am facing a challenge with my Vue2 component that depends on Vuex to fetch the currently selected node (infoNode) and display its data to the user. In my beforeCreate function, Axios is used to retrieve the top level nodes and set the 'infoNode&apos ...

ng-touched remains unchanged after calling .markAsUntouched on a Custom Control

Editing a field in an Angular 2 form with a custom control and resetting it using .markAsUntouched does not remove the ng-touched class. The sample form structure is as follows: <form #editForm="ngForm"> <input [(ngModel)]="title" name="titl ...

Unauthorized access detected during ajax request triggered by onpaste event

Recently, I encountered an issue with my asp.net mvc website where an ajax call to the server stopped working in IE 11, despite previously working fine in IE 8. The error message pointed to an access denied exception in jQuery 1.7.1 at h.open(c.type,c.url, ...

What sets canvas and webgl renderer apart in the world of three.js?

Attempting to showcase a sphere using three.js, but encountering issues when rendering with canvasRenderer due to the appearance of grey lines on the sphere. View the code here: http://jsfiddle.net/jzpSJ/ See the screenshot here: However, when rendering ...

The Angular binding for loading does not correctly reflect changes in the HTML

Whenever a user clicks the save button, I want to display a loading indicator. The state changes correctly when the button is clicked, but for some reason, reverting back the value of the loading property on scope to false doesn't update the UI. Coul ...

Angular JS implementation of the undo redo feature allows users to reverse or

My challenge involves a large object stored in $rootScope with over 100 objects, each containing hierarchies of objects and arrays. I am seeking to watch the entire $rootScope using deepWatching (setting the 3rd parameter of $watch to TRUE). The issue ari ...

I'm having trouble with the $locationProvider not functioning properly on my Angular webpage

I am facing an issue in my angular page where I am using a $locationProvider. However, it seems to not be functioning correctly on my web page. The console is showing an error message that says "$location in HTML5 mode requires a <base> tag to be pre ...

React Native - A button positioned with a lower zIndex will always be displayed on top of a view with a higher

I am facing an interesting scenario where a button with zIndex: 5 is positioned on top of an Interactable.View with zIndex: 19. EDIT: Although the button appears to be on top, it is visible but not responsive (lack of tap functionality). Below is the cod ...

Whenever I'm rendering my handlebars template, it unexpectedly gets terminated on its own

I have encountered an issue with my handlebar template. For some reason, a closing tag is being automatically inserted just before any closing tag in the template, causing it to be recognized as plain text. If you visit the following page: For example: { ...

An incessant stream of onclick events is being triggered

My HTML code consists of a jQuery script and a button that triggers a function to display random answers. However, after clicking the button once, the answers cycle automatically without any input. I want each click to show a different answer. What could ...

I'm curious about using NextJS to fetch an API with a specific router ID. Can anyone provide guidance on how to achieve this and then render the data as HTML?

Greetings! I am currently coding in NextJS and working on a user page that fetches user-specific information from an API. My goal is to extract the ID query from the URL and use it to make an API request. The API endpoint follows this structure: /Users/{i ...

How to Implement Drupal.behaviors for Specific Pages?

Currently, I have a module that showcases an alert to users within a block. For those interested, you can find my code on GitHub here: https://github.com/kevinquillen/User-Alerts If you would like more information about the module and its functionality, ...

Issue encountered with linker command resulting in exit code 1 within Android studio?

I'm utilizing the Bitmap Operation native library in Android Studio. The compilation is successful, but at runtime, I encounter a Linker command failure with exit-code 1 (use -v to see invocation). Below is the C code that I've included. #inclu ...

Avoid activating automatic save feature in Material UI data grid

After creating a data-grid and attempting to add records, I encountered an issue where pressing the TAB key automatically saved the data when focusing on the save button without manually pressing enter. How can this behavior be prevented so that manual con ...

I'm intrigued: what type of syntax is Facebook's polling service utilizing in the callback?

While monitoring the Network Monitor on Chrome's developer tool, I observed how Facebook updates content on their news feed. All AJAX responses start with the following: for (;;);{"__ar":1,"payload":[]} I'm curious about what the for(;;); piec ...

Use Google Maps filters in combination with checkboxes

I am seeking assistance with the following task: I need to develop a map that displays markers when the user clicks on an input checkbox. For example: When I click on "hotels," only hotels are displayed on the map. If I uncheck the "hotels" option, the ho ...

`The onItemSelected() method is not being triggered in this file, although it is functioning correctly in

The spinner function is working correctly, however, the item selection feature is not functioning as expected. It's worth noting that a similar implementation in another file is operating smoothly. The main goal is to retrieve the selected item from t ...

Can you identify the mistake in this situation?

int i = 10000; Integer.toBinaryString(i); Is there a way to modify the Integer.toBinaryString method to include leading zeroes? For instance, when i = 1000, I would like the output to display as 00000000000000000000001111101000 instead of just 1111101000. ...

Combining JSONObject and JSONArray methods for optimal efficiency in Java

I'm relatively new to working with Java. Whenever I attempt to chain method calls together, my IDE keeps showing errors. Here's an example: int motoYear = (int) modelYear.get("yearsRange").get(0); In this case, modelYear is of type JSONObject. ...

Chrome throwing Dom Mutation warnings related to Angular violations

Recently in our Angular 6 project, I've started noticing some unexpected [Violation] warnings showing up in Chrome. These warnings seem to be originating from line 1666 of zone.js with the message: [Violation] Added synchronous DOM mutation listener ...