Search code examples
androidtitanium

Titanium Properties getString says: null, how to show the value without shutting the application?


I'm new to Titanium, now what I want is to appear whatever I type in textfield in Window2's label when I hit 'save' button without needing to shut the application and re-open it again, what happens is that the value of getString (myname) doesn't appear when I hit 'save' button in window2, here's my code, thanks in advance.

    var window1 = Ti.UI.createWindow({
        title: 'Window',
        backgroundColor: 'white'
    });

    var textfield = Ti.UI.createTextField({
        width: 200,
        hintText: 'TYPE'
    });

    var button1 = Ti.UI.createButton({
        top: '10%',
        title: 'save'
    });

    button1.addEventListener('click', function(e){
        Ti.App.Properties.setString('NAME', textfield.value);
        window2.open();
        window1.close();
    });
    window1.add(textfield);
    window1.add(button1);
    var myname = Ti.App.Properties.getString('NAME');

    var window2 = Ti.UI.createWindow({
        title: 'Window2',
        backgroundColor: 'white'
    });
    var label = Ti.UI.createLabel({
        text: myname,
        top: '20%'
    });
    window2.add(label);
    window1.open();

Solution

  • What you doing wrong is that you are setting the property 'NAME' ie.,

    Ti.App.Properties.setString('NAME', textfield.value);
    

    inside the click listener of your button. So this property get set only when you click the button.

    But you actually trying to retrieve your property before clicking the button.

    One Solution to your problem is this - Try adding a event listener for method 'open' to your window2 like this -

    var myname;
    window2.addEventListener('open', function(e){
        myname = Ti.App.Properties.getString('NAME');
        label.setText(myname);
    });
    

    Hope it helps!

    Also you can add a event listener of method 'close' to your window1. There are many ways you can do this.