React native listview does not show all the rows - android

I have a questionnaire application which works fine on Android. However on iOS, the ListView never shows all the questions. Of the 11 questions in the questionnaire. only about 2 or 2.5 of them are rendered. A small amount of scrolling does seem to happen based on the size off the emulator window. I have tried all the suggestion posted including:
- setting the height of the ListView item using Dimensions
- setting flex:1 up the container hierarchy.
But nothing seems to work.
I am posting a much abridged and modified version of the code that uses NativeBase's RadionButton. My original code uses my own home-brewed radio buttons, but all of them have the same problem. I would appreciate any help I can get on this problem. Thanks in advance.
Here is my code:
import React, { Component } from 'react';
import {
Alert,
StyleSheet,
// Text,
TextInput,
View,
ListView,
TouchableHighlight,
Dimensions,
} from 'react-native';
import Svg,{
Rect,
} from 'react-native-svg';
import { Actions } from 'react-native-router-flux';
import realm from './realm';
import Utils from './Utils';
import moment from 'moment';
import { Container, Content, InputGroup, Input,
List, ListItem, Text, Radio } from 'native-base';
require('Dimensions');
const windowDims = Dimensions.get('window');
///////////////////////////////////////////////////////////////////////////////
const WhenSymptom = 0;
const FrequencySymptom = 1;
const FeelingSymptom = 2;
const YesNoSymptom = 3;
const ValueSymptom = 4;
global.junk = "hello";
var SymptomValues = new Array
(
// WhenSymptom
[ "none", "only after inactivity", "mostly AM", "AM and PM", "all the time" ],
// FrequencySymptom
[ "None", "Less than usual", "Usual", "More than usual", "Very bothersome" ],
// FeelingSymptom
[ "Great", "Fair", "So-so", "Poor", "Terrible" ],
// YesNoSymptom
[ "No", "", "", "", "Yes" ],
// ValueSymptom
[]
);
// var questions = new Array
global.questions = new Array
(
{ rowIndex: 0,
chartTitle: "Tremors",
answer: 0},
{ rowIndex: 1,
chartTitle: "Speech-slurring",
answer: 1},
{ rowIndex: 2,
chartTitle: "Feeling-stuck",
answer: 2},
{ rowIndex: 3,
chartTitle: "Instability",
answer: 3},
{ rowIndex: 4,
chartTitle: "Anxiety",
answer: 4},
{ rowIndex: 5,
chartTitle: "# of steps",
answer: 1},
{ rowIndex: 6,
chartTitle: "Pain or aches",
answer: 3},
{ rowIndex: 7,
chartTitle: "Day drowsiness",
answer: 2},
{ rowIndex: 8,
chartTitle: "Urinary urgency",
answer: 1},
{ rowIndex: 9,
chartTitle: "Constipation",
answer: 0},
{ rowIndex: 10,
chartTitle: "Overall feeling",
answer: 2}
);
var colors = new Array( "green", "#dbdb70", "yellow", "orange", "red" );
var styles = StyleSheet.create({
list: {
flexDirection: 'column',
flex:1,
//height: windowDims.height-30,
marginTop: 52,
},
questionText: {
flex:1,
fontSize: 14,
// color: 'white',
color: 'black',
alignSelf: 'flex-start'
},
});
var junk = 0;
// const mySaveAction = () => console.log('Back From the Questions page ');
///////////////////////////////////////////////////////////////////////////////
export default class QuestionsPage extends Component {
constructor(props){
super(props);
console.log("numToPop: " + this.props.numToPop);
var ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 != r2
//rowHasChanged: (r1, r2) => true
});
// if it is a new panel, set all the answers to -1
let answersIn = new Array(questions.length);
if (this.props.panel == null) {
for (let i in questions) {
answersIn[i] = -1;
questions[i].answer = -1;
}
}
else {
answersIn = this.props.panel.symptoms.split(",");
for (let i in questions) {
questions[i].answer = answersIn[i];
}
}
this.state = {
ds: questions,
dataSource:ds,
editAllowed: 0,
initialAnswers: answersIn,
behavior: 'position'
// there is three ways to adjust (position , height , padding )
}
}
///////////////////////////////////////////////////////////////////////////////
componentDidMount(){
this.setState({
dataSource:this.state.dataSource.cloneWithRows(this.state.ds),
});
// When we come in here with newPanel == 1, the route was
// MenuPage => QuestionsPage; so cancel should just be
// Actions.pop(). If newPanel == 0, , the route was
// MenuPage => Calendar => QuestionsPage; so cancel should call Actions.pop(2)
Actions.refresh({ onRight: () => { this._saveButtonPressed(); },
onBack: () => { this._cancelButtonPressed(); },
title: (this.props.panel == null ?
"New panel" :
(" Panel of " +
Utils.readableDate(this.props.panel.panelDate)))
});
}
///////////////////////////////////////////////////////////////////////////////
_saveButtonPressed() {
var finalAnswers = new Array(questions.length);
var panelChanged = 0;
var dateString;
for (let i=0; i<finalAnswers.length; i++) {
finalAnswers[i] = questions[i].answer;
if (finalAnswers[i] != this.state.initialAnswers[i])
panelChanged = 1;
}
var symptoms = "" + finalAnswers[0];
for (let i=1; i<finalAnswers.length; i++) {
symptoms = (symptoms + "," + finalAnswers[i]);
}
console.log("_saveButtonPressed panelChanged: " + panelChanged);
if (this.props.panel == null) {
if (panelChanged) {
let myPanelKey = Utils.newPanelKey();
this._updateDB(myPanelKey, symptoms);
}
Actions.pop();
}
else {
if (panelChanged) {
this._updateDB(this.props.panel.panelDate, symptoms);
}
// Kluge:
this._returnFromScreen();
}
}
///////////////////////////////////////////////////////////////////////////////
_updateDB(myPanelDate, symptoms) {
console.log("_updateDB dt: " + moment(myPanelDate).toString() +
" symptoms: " + symptoms);
// var dateString = Utils._myISOString(myPanelDate);
realm.write(() => {
realm.create('Symptoms', {panelDate: myPanelDate, symptoms: symptoms}, true);
});
console.log("Trace");
let after = realm.objects('Symptoms');
for (let i=0; i<after.length; i++) {
console.log("panelDate: " + moment(after[i].panelDate).toString() +
" (" + after[i].panelDate + " )" +
"; symptoms: " + after[i].symptoms);
}
}
///////////////////////////////////////////////////////////////////////////////
_returnFromScreen() {
if (this.props.numToPop == 1)
Actions.pop();
else
Actions.pop({popNum: 2});
}
///////////////////////////////////////////////////////////////////////////////
_cancelButtonPressed() {
console.log("_cancelButtonPressed in QuestionsPage numToPop: " +
this.props.numToPop);
this._returnFromScreen();
}
///////////////////////////////////////////////////////////////////////////////
_rowPressed(rowData){
console.log("In _rowPressed");
}
///////////////////////////////////////////////////////////////////////////////
_buttonPressed(rowIndex, value, forceEdit = 0){
// console.log("In _buttonPressed " + rowIndex + " " + value);
let newDs = this.state.ds.slice();
newDs[rowIndex] = {
...this.state.ds[rowIndex],
answer: value,
};
// This is absolutely essential to do!!!!!
questions[rowIndex].answer = value;
this.setState({
dataSource:this.state.dataSource.cloneWithRows(newDs),
})
// this.forceUpdate();
// console.log("answers: " + this.state.answers);
}
///////////////////////////////////////////////////////////////////////////////
_renderButton(rowIndex, column){
return (
<ListItem>
<Radio selected={this.state.ds[rowIndex].answer == column ? true : false} />
<Text>{SymptomValues[0][column]}</Text>
</ListItem>
);
}
///////////////////////////////////////////////////////////////////////////////
_renderRow(rowData){
// console.log("renderRow " + this.state.ds[rowData.rowIndex].answer);
return (
<View style={styles.list}>
<Text style={styles.questionText}>Question {rowData.rowIndex+1}.</Text>
<Container>
<Content>
<List>
{ this._renderButton(rowData.rowIndex, 0) }
{ this._renderButton(rowData.rowIndex, 1) }
{ this._renderButton(rowData.rowIndex, 2) }
{ this._renderButton(rowData.rowIndex, 3) }
{ this._renderButton(rowData.rowIndex, 4) }
</List>
</Content>
</Container>
</View>
);
}
///////////////////////////////////////////////////////////////////////////////
render(){
// console.log("render");
return (
<ListView style={styles.list}
dataSource = {this.state.dataSource}
renderRow = {this._renderRow.bind(this)}>
</ListView>
);
}
}
module.exports = QuestionsPage;
// Util.js
import moment from 'moment';
let Utils = {
// toISOString returns (YYYY-MM-DDTHH:mm:ss.sssZ
newPanelKey: function() {
let myPanelDate = moment();
myPanelDate.milliseconds(0);
myPanelDate.seconds(0);
myPanelDate.minutes(0);
return myPanelDate.valueOf();
},
readableDate: function(utc) {
return moment(utc).format("MMM D, YYYY#ha");
},
readableDateNoTime: function(utc) {
return moment(utc).format("MMM D, YYYY");
},
shortDate: function(utc) {
let mom = moment(utc);
let date = mom.format("DDMMM:hha");
return date.substring(0,date.length-1);
}
}
module.exports = Utils;

Related

Get average of values in a field in realm react native

This is telling me 'Can't find variable: gpa'
It is also saying unresolved variable Double. I want to fetch all the values submitted in a particular field and compute the average. The average is to be displayed in an alert box. The code is in a function named dbtotal below.
class MainActivity extends Component {
static navigationOptions =
{
title: 'MyGPA',
};
GoToSecondActivity = () =>
{
this.props.navigation.navigate('Second');
};
constructor() {
super();
this.state = {
Student_Name : '',
Semester : '',
GPA : ''
};
realm = new Realm({
schema: [{name: 'CalcGP',
properties:
{
student_id: {type: 'int', default: 0},
student_name: 'string',
semester: 'int',
gpa: 'double'
}
}]
});
}
add_Student = () => {
realm.write(() => {
let ID = realm.objects('CalcGP').length + 1;
realm.create('CalcGP', {
student_id: ID,
student_name: this.state.Student_Name,
semester: this.state.Semester,
gpa : this.state.GPA,
});
});
Alert.alert("Details Added Successfully.");
};
let mydata = realm.objects('CalcGP');
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource: ds.cloneWithRows(mydata),
};
}
GoToEditActivity (student_id, student_name, semester, gpa) {
this.props.navigation.navigate('Third', {
ID : student_id,
NAME : student_name,
CLASS : semester,
SUBJECT : gpa,
});
}
dbtotal() {
let cgpa: Double = realm.objects('CalcGP').avg(gpa) ;
Alert.alert(cgpa);
}
<TouchableOpacity onPress={this.dbtotal} activeOpacity={0.7} style={styles.button} >
<Text style={styles.TextStyle}> CALCULATE </Text>
</TouchableOpacity>
avg(gpa) should be avg('gpa').
And let cgpa: Double = can be let cgpa =.
This is working fine
`let average = realm.objects('CalcGP').avg('gpa');
this.state = {
aver: Alert.alert(Your CGPA is + average.toString())
};`

AsyncStorage+firebase read data hang up application

i'm using React native AsyncStroare with written on firebase when device connected with internet
but i am facing unknown problem which hang up my application which doesn't allow even click event
Anyone has ever faced this kind of problem ever?
i'm sharing code,
import React, { Component, PropTypes } from 'react';
import { StyleSheet, View, Text, Dimensions, AppRegistry, TouchableOpacity, Animated, Button, Alert, Vibration, AsyncStorage, NetInfo} from 'react-native';
import BackgroundGeolocation from 'react-native-mauron85-background-geolocation';
import MapView, { MAP_TYPES } from 'react-native-maps';
import * as firebase from "firebase";
const onStartPress = () => {
BackgroundGeolocation.start(
function (locations) {
Alert.alert('Tracking has been started');
Vibration.vibrate();
}
);
};
const onStopPress = () => {
BackgroundGeolocation.stop(
function (locations) {
Alert.alert('Tracking has been stop');
Vibration.vibrate();
}
);
};
// Initialize Firebase
const firebaseConfig = {
apiKey: "xxxx",
authDomain: "first-project-910a2.firebaseapp.com",
databaseURL: "https://first-project-910a2.firebaseio.com",
storageBucket: "gs://first-project-910a2.appspot.com",
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const rootRef = firebase.database().ref();
const itemsRef = rootRef.child('gps');
const email = "test#email.com";
const password = "test121";
var uid = 0;
var currentDistance = 0;
var eventOccur = 0;
firebaseApp.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
console.log( errorCode + ": "+ errorMessage );
});
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
uid = JSON.stringify(user.uid);
} else {
uid = 0;
}
});
var SchoolJS = require('./SchoolJS.js');
const { width, height } = Dimensions.get('window');
const ASPECT_RATIO = width / height;
const LATITUDE = 23.0123937;
const LONGITUDE = 72.5227731;
const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
let id = 0;
let arb = 0.01;
let busGpsCoordinates = [];
let prevlatOffline = 0;
let prevlongOffline = 0;
export default class MyScene extends Component {
constructor(props) {
super(props);
this.state = {
region: {
latitude: LATITUDE,
longitude: LONGITUDE,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
},
};
}
componentWillMount() {
BackgroundGeolocation.configure({
desiredAccuracy: 10,
stationaryRadius: 50,
distanceFilter: 50,
locationTimeout: 30,
notificationTitle: 'Background tracking',
notificationText: 'enabled',
debug: false,
startOnBoot: false,
stopOnTerminate: false,
locationProvider: BackgroundGeolocation.provider.ANDROID_ACTIVITY_PROVIDER,
interval: 5000,
fastestInterval: 2000,
activitiesInterval: 5000,
stopOnStillActivity: false,
});
BackgroundGeolocation.on('location', (location) => {
// since I can connect from multiple devices or browser tabs, we store each connection instance separately
// any time that connectionsRef's value is null (i.e. has no children) I am offline
var myConnectionsRef = firebase.database().ref('users/'+uid+'/connections');
// stores the timestamp of my last disconnect (the last time I was seen online)
var lastOnlineRef = firebase.database().ref('users/'+uid+'/lastOnline');
var connectedRef = firebase.database().ref('.info/connected');
connectedRef.on('value', function(snap) {
if (snap.val() === true) {
// We're connected (or reconnected)! Do anything here that should happen only if online (or on reconnect)
// add this device to my connections list
// this value could contain info about the device or a timestamp too
var con = myConnectionsRef.push(true);
// when I disconnect, remove this device
con.onDisconnect().remove();
// when I disconnect, update the last time I was seen online
lastOnlineRef.onDisconnect().set(firebase.database.ServerValue.TIMESTAMP);
//sync with firebase when reconnect
/*BackgroundGeolocation.start(() => {
console.log('[DEBUG] BackgroundGeolocation start successfully');
});*/
AsyncStorage.getItem(uid+"offline").then((value) => {
busGpsJsonObj = JSON.parse(value);
console.log("BUS OBJ : " + busGpsJsonObj);
if(busGpsJsonObj != null){
busGpsJsonObj.forEach(function(locationObj) {
newPostKey = firebase.database().ref().child('gps').push().key;
todaydate = SchoolJS.today();
newPostKey = (newPostKey != "") ? "/"+todaydate+"/"+newPostKey : "";
firebaseApp.database().ref('gps/' + uid+newPostKey).set({
speed : locationObj.speed,
accuracy: locationObj.accuracy,
bearing: locationObj.bearing,
longitude: locationObj.longitude,
altitude: locationObj.altitude,
latitude: locationObj.latitude,
time: locationObj.time,
locationProvider: locationObj.locationProvider,
});
});
AsyncStorage.removeItem(uid+"offline");
busGpsCoordinates = [];
}
}).done();
}
});
//handle your locations here
timekey = JSON.stringify(location.time);
speed = JSON.stringify(location.speed),
accuracy = JSON.stringify(location.accuracy),
bearing = JSON.stringify(location.bearing),
longitude = JSON.stringify(location.longitude),
altitude = JSON.stringify(location.altitude),
latitude = JSON.stringify(location.latitude),
time = JSON.stringify(location.time),
locationProvider = JSON.stringify(location.locationProvider),
timekey = timekey.toString();
newPostKey = firebase.database().ref().child('gps').push().key;
todaydate = SchoolJS.today();
newPostKey = (newPostKey != "") ? "/"+todaydate+"/"+newPostKey : "";
latitude = latitude.replace(/^"(.*)"$/, '$1');
longitude = longitude.replace(/^"(.*)"$/, '$1');
NetInfo.isConnected.fetch().then(isConnected => {
if(!isConnected)
{
if(busGpsCoordinates.length == 0)
{
busGpsCoordinates.push({
speed : speed,
accuracy: accuracy,
bearing: bearing,
longitude: longitude,
altitude: altitude,
latitude: latitude,
time: time,
locationProvider: locationProvider,
});
AsyncStorage.setItem(uid+"offline", JSON.stringify(busGpsCoordinates ) );
}
else
{
prevData = JSON.stringify(busGpsCoordinates[busGpsCoordinates.length - 1] );
prevData = JSON.parse(prevData);
currentDistance = SchoolJS.distance(prevData.latitude,prevData.longitude,latitude,longitude);
if(currentDistance > 30)
{
busGpsCoordinates.push({
speed : speed,
accuracy: accuracy,
bearing: bearing,
longitude: longitude,
altitude: altitude,
latitude: latitude,
time: time,
locationProvider: locationProvider,
});
AsyncStorage.setItem(uid+"offline", JSON.stringify(busGpsCoordinates ) );
}
}
}
});
this.animateRandom(parseFloat(latitude),parseFloat(longitude));
// retrieve the last record from `ref`
if(uid != 0)
{
itemsRef.once("value", function(snapshot) {
var totalChild = snapshot.child(uid).child(todaydate).numChildren();
if(totalChild == 0)
{
firebaseApp.database().ref('gps/' + uid+newPostKey).set({
speed : speed,
accuracy: accuracy,
bearing: bearing,
longitude: longitude,
altitude: altitude,
latitude: latitude,
time: time,
locationProvider: locationProvider,
});
}
});
itemsRef.child(uid).child(todaydate).limitToLast(1).on('child_added', function(snapshot) {
previousLatitude = JSON.stringify(snapshot.val().latitude);
previousLongitude = JSON.stringify(snapshot.val().longitude);
previousLatitude = previousLatitude.replace(/^"(.*)"$/, '$1');
previousLongitude = previousLongitude.replace(/^"(.*)"$/, '$1');
latitude = latitude.replace(/^"(.*)"$/, '$1');
longitude = longitude.replace(/^"(.*)"$/, '$1');
currentDistance = SchoolJS.distance(previousLatitude,previousLongitude,latitude,longitude);
eventOccur++;
if(currentDistance > 30)
{
firebaseApp.database().ref('gps/' + uid+newPostKey).set({
speed : speed,
accuracy: accuracy,
bearing: bearing,
longitude: longitude,
altitude: altitude,
latitude: latitude,
time: time,
locationProvider: locationProvider,
});
}
});
}
});
BackgroundGeolocation.on('stationary', (stationaryLocation) => {
//handle stationary locations here
console.log(JSON.stringify(stationaryLocation));
});
BackgroundGeolocation.on('error', (error) => {
console.log('[ERROR] BackgroundGeolocation error:', error);
});
BackgroundGeolocation.isLocationEnabled((success, fail) => {
if(success != 1 && fail == "undefined")
{
BackgroundGeolocation.stop(() => {
console.log('[DEBUG] BackgroundGeolocation stop successfully');
});
}
});
}
onRegionChange(region) {
this.setState({ region });
}
jumpRandom() {
this.setState({ region: this.randomRegion() });
}
animateRandom(newLatitude = LATITUDE ,newLongitude = LONGITUDE) {
this.map.animateToRegion(this.randomRegion(newLatitude, newLongitude));
}
randomRegion(newLatitude = LATITUDE ,newLongitude = LONGITUDE) {
const { region } = this.state;
return {
...this.state.region,
latitude: newLatitude,
longitude: newLongitude,
};
}
render() {
return (
<View style={styles.container}>
<MapView
showsUserLocation = { true }
provider={this.props.provider}
ref={ref => { this.map = ref; }}
mapType={MAP_TYPES.TERRAIN}
style={styles.map}
initialRegion={this.state.region}
onRegionChange={region => this.onRegionChange(region)}
>
<MapView.Marker.Animated
coordinate={this.state.region}
/>
</MapView>
<View style={styles.buttonContainer}>
<TouchableOpacity
onPress={onStartPress}
style={[styles.bubble, styles.button]}
>
<Text>Start</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={onStopPress}
style={[styles.bubble, styles.button]}
>
<Text>Stop</Text>
</TouchableOpacity>
</View>
</View>
)
}
}
MyScene.propTypes = {
provider: MapView.ProviderPropType,
};
const styles = StyleSheet.create({
container: {
...StyleSheet.absoluteFillObject,
justifyContent: 'flex-end',
alignItems: 'center',
},
map: {
...StyleSheet.absoluteFillObject,
},
bubble: {
backgroundColor: 'rgba(255,255,255,0.7)',
paddingHorizontal: 18,
paddingVertical: 12,
borderRadius: 20,
},
latlng: {
width: 200,
alignItems: 'stretch',
},
button: {
width: 80,
paddingHorizontal: 12,
alignItems: 'center',
marginHorizontal: 10,
},
buttonContainer: {
flexDirection: 'row',
marginVertical: 20,
backgroundColor: 'transparent',
},
});
anyone can help me out from this problem.

Appcelerator Titanium - why isn't my button showing?

In Titanium, I have the following code:
var dbWindow = Ti.UI.currentWindow;
var Cloud = require('ti.cloud');
var data = [];
var rowid;
var rowindex;
var table;
var db;
/**
* Creates TableView from database
*/
function makeTable() {
db = Ti.Database.open('myDb');
try {
var rows = db.execute('SELECT * from boatData');
var boatName;
var rowLabel;
while (rows.isValidRow()) {
tableRow = Ti.UI.createTableViewRow({
backgroundSelectedColor : 'red',
rowid : rows.fieldByName('id'),
loa : rows.fieldByName('loa'),
lwl : rows.fieldByName('lwl'),
beam : rows.fieldByName('beam'),
displacement : rows.fieldByName('displacement'),
sailArea : rows.fieldByName('sailArea')
});
boatName = rows.fieldByName('boatName');
rowLabel = Ti.UI.createLabel({
text : boatName,
color : 'black',
font : {
fontSize : 22
},
touchEnabled : false
});
tableRow.add(rowLabel);
tableRow.Label = rowLabel;
data.push(tableRow);
rows.next();
}
rows.close();
db.close();
table = Titanium.UI.createTableView({
data : data,
backgroundColor : 'pink',
headerTitle : 'Boats',
height : '75%',
allowsSelection : true
});
} catch (e) {//database table not found
db.close();
var alertWindow = Titanium.UI.createAlertDialog({
message : 'No data found! Please save data first',
buttonNames : ['OK']
});
alertWindow.addEventListener('click', function(e) {
dbWindow.close();
});
alertWindow.show();
}
}
makeTable();
table.addEventListener('click', function(e) {
rowid = e.rowData.rowid;
rowindex = e.index;
Ti.App.loaBox.value = e.rowData.loa;
Ti.App.lwlBox.value = e.rowData.lwl;
Ti.App.beamBox.value = e.rowData.beam;
Ti.App.displacementBox.value = e.rowData.displacement;
Ti.App.saBox.value = e.rowData.sailArea;
openButton.title = 'Get Data';
selected.text = 'Your selection: ' + e.row.Label.text;
deleteButton.visible = true;
});
var parentView = Titanium.UI.createView({
width : '100%',
height : '100%',
layout : 'vertical'
});
parentView.add(table);
var selectionView = Ti.UI.createView({
top : 5,
height : '10%',
layout : 'vertical'
});
var info = Ti.UI.createLabel({
text : 'Click on a boat name to get data or delete.',
color : 'black',
font : {
fontSize : 25
}
});
var selected = Ti.UI.createLabel({
color : 'red',
font : {
fontSize : 25
}
});
selectionView.add(info);
selectionView.add(selected);
parentView.add(selectionView);
var buttons = Ti.UI.createView({
top : 5,
layout : 'horizontal'
});
var lowerButtons = Ti.UI.createView({
top : 5,
layout : 'horizontal'
});
var openButton = Ti.UI.createButton({
backgroundColor : 'pink',
borderColor : 'red',
borderWidth : 2,
font : {
fontSize : 22
},
title : 'Back',
right : 5
});
openButton.addEventListener('click', function(e) {
dbWindow.close();
});
var deleteButton = Ti.UI.createButton({
backgroundColor : 'pink',
borderColor : 'red',
borderWidth : 2,
font : {
fontSize : 22
},
title : 'Delete',
left : 5
});
deleteButton.visible = false;
deleteButton.addEventListener('click', function(e) {
var db = Ti.Database.open('myDb');
db.execute('DELETE FROM boatData WHERE id=' + rowid);
db.close();
table.deleteRow(rowindex);
Ti.App.loaBox.value = '';
Ti.App.lwlBox.value = '';
Ti.App.beamBox.value = '';
Ti.App.displacementBox.value = '';
Ti.App.saBox.value = '';
deleteButton.visible = false;
openButton.title = 'Back';
selected.text = '';
});
var saveToCloudButton = Ti.UI.createButton({
backgroundColor : 'pink',
borderColor : 'red',
borderWidth : 2,
font : {
fontSize : 22
},
title : 'Save boats to cloud',
left : 5
});
saveToCloudButton.addEventListener('click', function(e) {
saveToCloud();
});
buttons.add(openButton);
buttons.add(deleteButton);
lowerButtons.add(saveToCloudButton);
parentView.add(buttons);
parentView.add(lowerButtons);
dbWindow.add(parentView);
/**
* Saves database to cloud
*/
function saveToCloud() {
var dbName = 'myDb';
var dbPath;
var dbFile;
if (Ti.Platform.osname == 'android') {
dbPath = 'file:///data/data/' + Ti.App.getID() + '/databases/';
dbFile = Ti.Filesystem.getFile(dbPath + dbName);
} else {
dbPath = Ti.Filesystem.applicationSupportDirectory + '/database/';
dbFile = Ti.Filesystem.getFile( dbPath + dbName + '.sql' );
}
Cloud.Users.secureLogin({
title : 'Sign In'
}, function(e) {
if (e.success) {
Cloud.Files.create({
name : dbName,
file : dbFile
}, function(e) {
if (e.success) {
var file = e.files[0];
alert('Boats successfully backed up to cloud!');
} else {
alert('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
}
});
} else {
alert('Error:\\n' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
However, for some odd reason, my saveToCloudButton does not appear. I tried manually setting the visibility, and that didn't work. Does anyone know what am I doing wrong?
EDIT: Added full code.
Make the top different for both the views
var buttons = Ti.UI.createView({
top : 5,
layout : 'horizontal'
});
var lowerButtons = Ti.UI.createView({
top : 60,
layout : 'horizontal'
});
Thanks
I figured out my problem. I needed to set height values to buttons and lowerButtons.

Auto-complete Textfield in titanium ios & Android

I want autocomplete textbox like if i press a it should shows related words like apple,aeroplane etc.,i want to make like similar google search.is there any control like this operation in ios and android on titanium.Help with examples codes or it's not possible in titanium?
The following code will work for you. Try it and modify as per your need. Here I Used array(searchArray) as data storage(You can replace it with database field or source whatever as per your requirement).
//Table view showing your autocomplete values
var tblvAutoComplete = Ti.UI.createTableView({
width : '100%',
backgroundColor : '#EFEFEF',
height : 0,
maxRowHeight : 35,
minRowHeight : 35,
allowSelection : true
});
//Starts auto complete
txtAutoComplete.addEventListener('change', function(e){
var pattern = e.source.value;
var tempArray = PatternMatch(searchArray, pattern);
CreateAutoCompleteList(tempArray);
});
//You got the required value and you clicks the word
tblvAutoComplete.addEventListener('click', function(e){
txtAutoComplete.value = e.rowData.result;
});
//Returns the array which contains a match with the pattern
function PatternMatch(arrayToSearch, pattern){
var searchLen = pattern.length;
arrayToSearch.sort();
var tempArray = [];
for(var index = 0, len = arrayToSearch.length; index< len; index++){
if(arrayToSearch[index].substring(0,searchLen).toUpperCase() === pattern.toUpperCase()){
tempArray.push(arrayToSearch[index]);
}
}
return tempArray;
}
//setting the tableview values
function CreateAutoCompleteList(searchResults){
var tableData = [];
for(var index=0, len = searchResults.length; index < len; index++){
var lblSearchResult = Ti.UI.createLabel({
top : 2,
width : '40%',
height : 34,
left : '5%',
font : { fontSize : 14 },
color : '#000000',
text : searchResults[index]
});
//Creating the table view row
var row = Ti.UI.createTableViewRow({
backgroundColor : 'transparent',
focusable : true,
height : 50,
result : searchResults[index]
});
row.add(lblSearchResult);
tableData.push(row);
}
tblvAutoComplete.setData(tableData);
tblvAutoComplete.height = tableData.length * 35;
}
This code worked for me in both ios and android. Hope your problems get resolved:D
cool i can give some example for you with android auto address suggestion bar
var search = Titanium.UI.createTextField({
height : '40sp',
hintText : 'Search',
top : '3sp',
right : '0%',
width : '73%',
textAlign : 'left',
font : {
fontFamily : 'Verdana',
fontSize : '13sp',
},
});
your result dispaly as table row
var resulttable = Ti.UI.createTableView({
top : '0%',
left : '0%',
width : '100%',
height : '100%',
separatorColor : '#000000',
});
and add event listner as change and any change call function with your value and if value is empty remove table from your view
search.addEventListener("change", function(event, type) {
Titanium.API.info("in change event listener");
if ('' != search.value) {
tabgroupContentView.add(resulttable);
if (resulttable.data.length > 0) {
for (var i = resulttable.data[0].rows.length - 1; i >= 0; i--) {
resulttable.deleteRow(i);
}
}
auto_complete(search.value);
} else {
tabgroupContentView.remove(resulttable);
}
});
call following function to auto complte
function auto_complete(search_term) {
loader.open("GET", "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=" + search_term + "&types=geocode&language=en&sensor=true&key=bar blar blar this is my key use ur one");
loader.onload = function() {
var histryresult = eval('(' + this.responseText + ')');
jsonArry = histryresult.predictions;
jsonArryterms = histryresult.terms;
for (var i = 0; i < jsonArry.length; i++) {
var service_row = Ti.UI.createTableViewRow({
height : '70sp',
width : '100%',
backgroundColor : '#ffffff',
backgroundFocusedColor : '#FF8F2F',
backgroundSelectedColor : '#FF8F2F',
hasChild : false
});
var lbl_oderid = Ti.UI.createLabel({
left : '3%',
top : '10%',
text : jsonArry[i].terms[1].value,
color : '#A70CAF',
font : {
fontSize : '17sp',
fontWeight : 'bold'
},
height : 'auto',
width : 'auto'
});
var descriptiontext;
if (jsonArry[i].description == undefined) {
descriptiontext = 'Not Valable';
} else {
descriptiontext = jsonArry[i].description;
}
var lbl_description = Ti.UI.createLabel({
left : '5%',
top : '50%',
text : descriptiontext,
color : '#000000',
font : {
fontSize : '12sp',
},
height : 'auto',
width : 'auto'
});
service_row.add(lbl_oderid);
service_row.add(lbl_description);
service_row.addEventListener('click', function(e) {
var locaName = jsonArry[e.index].description;
if (jsonArry[e.index].description == undefined) {
} else {
reversGeoloader.open("GET", "http://maps.googleapis.com/maps/api/geocode/json?address=" + locaName + "&sensor=false");
reversGeoloader.onload = function() {
var geoResult = eval('(' + this.responseText + ')');
jsonArry = geoResult.results;
var newlat = jsonArry[0].geometry.location.lat;
var newlng = jsonArry[0].geometry.location.lng;
curentlatitude = newlat;
curentlongitude = newlng;
getReversGeo(curentlatitude, curentlongitude, 'str');
usercurentlocation.setText('Set by serch');
tabTestWindow.close();
};
reversGeoloader.send();
}
});
resulttable.appendRow(service_row);
}
};
loader.send();
}
textField.addEventListener('change', function(e) {
// you can fill a tableView in this event with the suggested data
});
or this tutorial link might solve your problem
AutoCompleteTextField

Android Geolocation Null in Titanium

I can't get geolocations in the emulator or on a physical phone.
I'm using Titanium SDK 1.6.2, ADK 2.2.
I've followed the approaches used here to no avail.
What am I missing? Thanks in advance.
Error:
Says that e.coords is null when doing this assignment. f_lng = e.coords.longitude;
Code:
function get_geolocation() {
try {
Ti.Geolocation.preferredProvider = 'gps';
Titanium.Geolocation.accuracy = Titanium.Geolocation.ACCURACY_BEST;
Titanium.Geolocation.distanceFilter = 10;
if( Titanium.Geolocation.locationServicesEnabled === false ) {
throw('Your device has GPS turned off. Please turn it on.');
}
var f_lat, f_lng;
Titanium.Geolocation.getCurrentPosition(function(e) {
if( ! e.success || e.error ) {
alert("Unable to get your location.");
}
f_lng = e.coords.longitude;
f_lat = e.coords.latitude;
});
return {
's_status': 'success',
'f_lat': f_lat,
'f_lng': f_lng
};
} catch( s_error ) {
return {
's_status': 'error',
's_message': s_error
};
}
}
Ti.App.GeoApp = {};
Ti.Geolocation.preferredProvider = Titanium.Geolocation.PROVIDER_GPS;
Ti.Geolocation.purpose = "testing";
Titanium.Geolocation.accuracy = Titanium.Geolocation.ACCURACY_BEST;
Titanium.Geolocation.distanceFilter = 10;
if( Titanium.Geolocation.locationServicesEnabled === false ) {
Ti.API.debug('Your device has GPS turned off. Please turn it on.');
}
function updatePosition(e) {
if( ! e.success || e.error ) {
alert("Unable to get your location.");
Ti.API.debug(JSON.stringify(e));
Ti.API.debug(e);
return;
}
Ti.App.fireEvent("app:got.location", {
"coords" : e.coords
});
};
Ti.App.addEventListener("app:got.location", function(d) {
Ti.App.GeoApp.f_lng = d.longitude;
Ti.App.GeoApp.f_lat = d.latitude;
Ti.API.debug(JSON.stringify(d));
Ti.Geolocation.removeEventListener('location', updatePosition);
alert(JSON.stringify(d));
});
var tabGroup = Titanium.UI.createTabGroup();
//
// create base UI tab and root window
//
var window = Titanium.UI.createWindow({
backgroundColor:'#fff',
barColor:'#003333',
});
var tab1 = Titanium.UI.createTab({
icon:'KS_nav_views.png',
title:'Tab 1',
window:window
});
tabGroup.open();
Titanium.Geolocation.getCurrentPosition( updatePosition );
Titanium.Geolocation.addEventListener( 'location', updatePosition );
see more details here http://blog.clearlyinnovative.com/post/5384374513/titanium-appcelerator-quickie-get-location-android
Piggy-backing off of Aaron's answer, here is what worked for me on IPhone Simulator, IPhone, and Android phone (not Android simulator). Keep in mind that I use redux so the code will be a little different.
var path = Ti.Platform.name == 'android' ? Ti.Filesystem.resourcesDirectory : "../../";
var map = {
top: 0,
bottom: 0,
latitude: 0,
longitude: 0,
latitudeDelta: 0.1,
longitudeDelta: 0.1,
display: "map",
init: function (annotations, latitude, longitude, top, bottom, delta) {
if (top)
map.top = top;
if (bottom)
map.bottom = bottom;
if (delta) {
map.latitudeDelta = delta;
map.longitudeDelta = delta;
}
map.createMap(annotations, latitude, longitude);
map.createOptions();
map.getLocation();
},
createMap: function (annotations, latitude, longitude) {
map.mapView = Ti.Map.createView({
mapType: Ti.Map.STANDARD_TYPE, animate: true, regionFit: false, userLocation: true,
region: { latitude: latitude, longitude: longitude, latitudeDelta: map.latitudeDelta, longitudeDelta: map.longitudeDelta },
annotations: annotations, bottom: map.bottom, top: map.top, borderWidth: 1
});
if (!isAndroid) {
map.mapView.addAnnotation(annotations[0]);
}
map.mapView.selectAnnotation(annotations[0]);
win.add(map.mapView);
},
createOptions: function () {
//map/satellite displays.
var mapDisplay = new ImageView({ image: path + 'images/map/satellite-view.png', width: 70, height: 49, zIndex: 2, top: map.top + 5, right: 5 });
mapDisplay.addEventListener('click', function () {
if (map.display == "map") {
map.mapView.setMapType(Titanium.Map.SATELLITE_TYPE);
mapDisplay.image = path + "images/map/map-view.png";
map.display = "satellite";
}
else {
map.mapView.setMapType(Titanium.Map.STANDARD_TYPE);
mapDisplay.image = path + "images/map/satellite-view.png";
map.display = "map";
}
});
win.add(mapDisplay);
//crosshairs.
if(Ti.Geolocation.locationServicesEnabled) {
var centerDisplay = new ImageView({ image: path + 'images/map/crosshairs.png', width: 49, height: 49, zIndex: 2, top: map.top + 5, right: 80 });
centerDisplay.addEventListener('click', function () {
if(map.latitude != 0 && map.longitude != 0) {
info("setting user location to " + map.latitude + " / " + map.longitude);
//center map.
var userLocation = {
latitude: map.latitude,
longitude: map.longitude,
latitudeDelta: map.latitudeDelta,
longitudeDelta: map.longitudeDelta,
animate: true
};
map.mapView.setLocation(userLocation);
}
});
win.add(centerDisplay);
}
},
createAnnotation: function (title, subtitle, latitude, longitude, isLocation, addToMap) {
var mapAnnotation = Ti.Map.createAnnotation({
latitude: latitude, longitude: longitude,
title: title,
subtitle: subtitle,
animate: true
});
if (isAndroid) {
mapAnnotation.pinImage = path + (isLocation ? "images/map/blue-pin.png" : "images/map/purple-pin.png");
}
else {
mapAnnotation.pincolor = isLocation ? Ti.Map.ANNOTATION_PURPLE : Ti.Map.ANNOTATION_RED;
}
if (addToMap)
map.mapView.addAnnotation(mapAnnotation);
return mapAnnotation;
},
updateAnnotation: function (mapAnnotation, title, subtitle, latitude, longitude, isLocation) {
if (mapAnnotation) {
map.mapView.removeAnnotation(mapAnnotation);
mapAnnotation = map.createAnnotation(title, subtitle, latitude, longitude, isLocation);
map.mapView.addAnnotation(mapAnnotation);
map.mapView.selectAnnotation(mapAnnotation);
}
},
addAnnotation: function (mapAnnotation) {
map.mapView.addAnnotation(mapAnnotation);
},
removeAnnotation: function (mapAnnotation) {
map.mapView.removeAnnotation(mapAnnotation);
},
selectAnnotation: function (mapAnnotation) {
map.mapView.selectAnnotation(mapAnnotation);
},
createRoute: function (name, points) {
var route = {
name: name, points: points, color: "#7c74d4", width: 4
};
map.mapView.addRoute(route);
setTimeout(function () { map.mapView.regionFit = true; }, 700);
},
getLocation: function() {
Ti.Geolocation.preferredProvider = Ti.Geolocation.PROVIDER_GPS;
Ti.Geolocation.purpose = "testing";
Ti.Geolocation.accuracy = Ti.Geolocation.ACCURACY_BEST;
Ti.Geolocation.distanceFilter = 10;
if(!Ti.Geolocation.locationServicesEnabled) {
//alert('Your device has GPS turned off. Please turn it on.');
return;
}
function updatePosition(e) {
if(!e.success || e.error) {
info("Unable to get your location - " + e.error);
return;
}
info(JSON.stringify(e.coords));
map.latitude = e.coords.latitude;
map.longitude = e.coords.longitude;
Ti.Geolocation.removeEventListener('location', updatePosition);
};
Ti.Geolocation.getCurrentPosition(updatePosition);
Ti.Geolocation.addEventListener('location', updatePosition);
}
};
Have you tried setting a timeout to make sure the e.coords is set before you use it, it has been suggested as a temporary fix?
setTimeout(function() {
return e.coords
}, 1000);

Categories

Resources