code
stringlengths 1
2.01M
| repo_name
stringlengths 3
62
| path
stringlengths 1
267
| language
stringclasses 231
values | license
stringclasses 13
values | size
int64 1
2.01M
|
|---|---|---|---|---|---|
// NOTICE!! DO NOT USE ANY OF THIS JAVASCRIPT
// IT'S ALL JUST JUNK FOR OUR DOCS!
// ++++++++++++++++++++++++++++++++++++++++++
!function ($) {
$(function(){
var $window = $(window)
// Disable certain links in docs
$('section [href^=#]').click(function (e) {
e.preventDefault()
})
// side bar
$('.bs-docs-sidenav').affix({
offset: {
top: function () { return $window.width() <= 980 ? 290 : 210 }
, bottom: 270
}
})
// make code pretty
window.prettyPrint && prettyPrint()
// add-ons
$('.add-on :checkbox').on('click', function () {
var $this = $(this)
, method = $this.attr('checked') ? 'addClass' : 'removeClass'
$(this).parents('.add-on')[method]('active')
})
// add tipsies to grid for scaffolding
if ($('#gridSystem').length) {
$('#gridSystem').tooltip({
selector: '.show-grid > div'
, title: function () { return $(this).width() + 'px' }
})
}
// tooltip demo
$('.tooltip-demo').tooltip({
selector: "a[rel=tooltip]"
})
$('.tooltip-test').tooltip()
$('.popover-test').popover()
// popover demo
$("a[rel=popover]")
.popover()
.click(function(e) {
e.preventDefault()
})
// button state demo
$('#fat-btn')
.click(function () {
var btn = $(this)
btn.button('loading')
setTimeout(function () {
btn.button('reset')
}, 3000)
})
// carousel demo
$('#myCarousel').carousel()
// javascript build logic
var inputsComponent = $("#components.download input")
, inputsPlugin = $("#plugins.download input")
, inputsVariables = $("#variables.download input")
// toggle all plugin checkboxes
$('#components.download .toggle-all').on('click', function (e) {
e.preventDefault()
inputsComponent.attr('checked', !inputsComponent.is(':checked'))
})
$('#plugins.download .toggle-all').on('click', function (e) {
e.preventDefault()
inputsPlugin.attr('checked', !inputsPlugin.is(':checked'))
})
$('#variables.download .toggle-all').on('click', function (e) {
e.preventDefault()
inputsVariables.val('')
})
// request built javascript
$('.download-btn .btn').on('click', function () {
var css = $("#components.download input:checked")
.map(function () { return this.value })
.toArray()
, js = $("#plugins.download input:checked")
.map(function () { return this.value })
.toArray()
, vars = {}
, img = ['glyphicons-halflings.png', 'glyphicons-halflings-white.png']
$("#variables.download input")
.each(function () {
$(this).val() && (vars[ $(this).prev().text() ] = $(this).val())
})
$.ajax({
type: 'POST'
, url: /\?dev/.test(window.location) ? 'http://localhost:3000' : 'http://bootstrap.herokuapp.com'
, dataType: 'jsonpi'
, params: {
js: js
, css: css
, vars: vars
, img: img
}
})
})
})
// Modified from the original jsonpi https://github.com/benvinegar/jquery-jsonpi
$.ajaxTransport('jsonpi', function(opts, originalOptions, jqXHR) {
var url = opts.url;
return {
send: function(_, completeCallback) {
var name = 'jQuery_iframe_' + jQuery.now()
, iframe, form
iframe = $('<iframe>')
.attr('name', name)
.appendTo('head')
form = $('<form>')
.attr('method', opts.type) // GET or POST
.attr('action', url)
.attr('target', name)
$.each(opts.params, function(k, v) {
$('<input>')
.attr('type', 'hidden')
.attr('name', k)
.attr('value', typeof v == 'string' ? v : JSON.stringify(v))
.appendTo(form)
})
form.appendTo('body').submit()
}
}
})
}(window.jQuery)
|
069ka-ambition-cms
|
trunk/bkp/ambition_before_session/assets/js/application.js
|
JavaScript
|
mit
| 3,954
|
/*
Holder - 1.6 - client side image placeholders
(c) 2012 Ivan Malopinsky / http://imsky.co
Provided under the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0
Commercial use requires attribution.
*/
var Holder = Holder || {};
(function (app, win) {
var preempted = false,
fallback = false,
canvas = document.createElement('canvas');
//getElementsByClassName polyfill
document.getElementsByClassName||(document.getElementsByClassName=function(e){var t=document,n,r,i,s=[];if(t.querySelectorAll)return t.querySelectorAll("."+e);if(t.evaluate){r=".//*[contains(concat(' ', @class, ' '), ' "+e+" ')]",n=t.evaluate(r,t,null,0,null);while(i=n.iterateNext())s.push(i)}else{n=t.getElementsByTagName("*"),r=new RegExp("(^|\\s)"+e+"(\\s|$)");for(i=0;i<n.length;i++)r.test(n[i].className)&&s.push(n[i])}return s})
//getComputedStyle polyfill
window.getComputedStyle||(window.getComputedStyle=function(e,t){return this.el=e,this.getPropertyValue=function(t){var n=/(\-([a-z]){1})/g;return t=="float"&&(t="styleFloat"),n.test(t)&&(t=t.replace(n,function(){return arguments[2].toUpperCase()})),e.currentStyle[t]?e.currentStyle[t]:null},this})
//http://javascript.nwbox.com/ContentLoaded by Diego Perini with modifications
function contentLoaded(n,t){var l="complete",s="readystatechange",u=!1,h=u,c=!0,i=n.document,a=i.documentElement,e=i.addEventListener?"addEventListener":"attachEvent",v=i.addEventListener?"removeEventListener":"detachEvent",f=i.addEventListener?"":"on",r=function(e){(e.type!=s||i.readyState==l)&&((e.type=="load"?n:i)[v](f+e.type,r,u),!h&&(h=!0)&&t.call(n,null))},o=function(){try{a.doScroll("left")}catch(n){setTimeout(o,50);return}r("poll")};if(i.readyState==l)t.call(n,"lazy");else{if(i.createEventObject&&a.doScroll){try{c=!n.frameElement}catch(y){}c&&o()}i[e](f+"DOMContentLoaded",r,u),i[e](f+s,r,u),n[e](f+"load",r,u)}};
//https://gist.github.com/991057 by Jed Schmidt with modifications
function selector(a){
a=a.match(/^(\W)?(.*)/);var b=document["getElement"+(a[1]?a[1]=="#"?"ById":"sByClassName":"sByTagName")](a[2]);
var ret=[]; b!=null&&(b.length?ret=b:b.length==0?ret=b:ret=[b]); return ret;
}
//shallow object property extend
function extend(a,b){var c={};for(var d in a)c[d]=a[d];for(var e in b)c[e]=b[e];return c}
function text_size(width, height, template) {
var dimension_arr = [height, width].sort();
var maxFactor = Math.round(dimension_arr[1] / 16),
minFactor = Math.round(dimension_arr[0] / 16);
var text_height = Math.max(template.size, maxFactor);
return {
height: text_height
}
}
function draw(ctx, dimensions, template, ratio) {
var ts = text_size(dimensions.width, dimensions.height, template);
var text_height = ts.height;
var width = dimensions.width * ratio, height = dimensions.height * ratio;
canvas.width = width;
canvas.height = height;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = template.background;
ctx.fillRect(0, 0, width, height);
ctx.fillStyle = template.foreground;
ctx.font = "bold " + text_height + "px sans-serif";
var text = template.text ? template.text : (dimensions.width + "x" + dimensions.height);
if (ctx.measureText(text).width / width > 1) {
text_height = template.size / (ctx.measureText(text).width / width);
}
ctx.font = "bold " + (text_height * ratio) + "px sans-serif";
ctx.fillText(text, (width / 2), (height / 2), width);
return canvas.toDataURL("image/png");
}
function render(mode, el, holder, src) {
var dimensions = holder.dimensions,
theme = holder.theme,
text = holder.text;
var dimensions_caption = dimensions.width + "x" + dimensions.height;
theme = (text ? extend(theme, {
text: text
}) : theme);
var ratio = 1;
if(window.devicePixelRatio && window.devicePixelRatio > 1){
ratio = window.devicePixelRatio;
}
if (mode == "image") {
el.setAttribute("data-src", src);
el.setAttribute("alt", text ? text : theme.text ? theme.text + " [" + dimensions_caption + "]" : dimensions_caption);
el.style.width = dimensions.width + "px";
el.style.height = dimensions.height + "px";
if (fallback) {
el.style.backgroundColor = theme.background;
}
else{
el.setAttribute("src", draw(ctx, dimensions, theme, ratio));
}
} else {
if (!fallback) {
el.style.backgroundImage = "url(" + draw(ctx, dimensions, theme, ratio) + ")";
el.style.backgroundSize = dimensions.width+"px "+dimensions.height+"px";
}
}
};
function fluid(el, holder, src) {
var dimensions = holder.dimensions,
theme = holder.theme,
text = holder.text;
var dimensions_caption = dimensions.width + "x" + dimensions.height;
theme = (text ? extend(theme, {
text: text
}) : theme);
var fluid = document.createElement("table");
fluid.setAttribute("cellspacing",0)
fluid.setAttribute("cellpadding",0)
fluid.setAttribute("border",0)
var row = document.createElement("tr")
.appendChild(document.createElement("td")
.appendChild(document.createTextNode(theme.text)));
fluid.style.backgroundColor = theme.background;
fluid.style.color = theme.foreground;
fluid.className = el.className + " holderjs-fluid";
fluid.style.width = holder.dimensions.width + (holder.dimensions.width.indexOf("%")>0?"":"px");
fluid.style.height = holder.dimensions.height + (holder.dimensions.height.indexOf("%")>0?"":"px");
fluid.id = el.id;
var frag = document.createDocumentFragment(),
tbody = document.createElement("tbody"),
tr = document.createElement("tr"),
td = document.createElement("td");
tr.appendChild(td);
tbody.appendChild(tr);
frag.appendChild(tbody);
if (theme.text) {
td.appendChild(document.createTextNode(theme.text))
fluid.appendChild(frag);
} else {
td.appendChild(document.createTextNode(dimensions_caption))
fluid.appendChild(frag);
fluid_images.push(fluid);
setTimeout(fluid_update, 0);
}
el.parentNode.replaceChild(fluid, el);
}
function fluid_update() {
for (i in fluid_images) {
var el = fluid_images[i];
var label = el.getElementsByTagName("td")[0].firstChild;
label.data = el.offsetWidth + "x" + el.offsetHeight;
}
}
function parse_flags(flags, options) {
var ret = {
theme: settings.themes.gray
}, render = false;
for (sl = flags.length, j = 0; j < sl; j++) {
var flag = flags[j];
if (app.flags.dimensions.match(flag)) {
render = true;
ret.dimensions = app.flags.dimensions.output(flag);
} else if (app.flags.fluid.match(flag)) {
render = true;
ret.dimensions = app.flags.fluid.output(flag);
ret.fluid = true;
} else if (app.flags.colors.match(flag)) {
ret.theme = app.flags.colors.output(flag);
} else if (options.themes[flag]) {
//If a theme is specified, it will override custom colors
ret.theme = options.themes[flag];
} else if (app.flags.text.match(flag)) {
ret.text = app.flags.text.output(flag);
}
}
return render ? ret : false;
};
if (!canvas.getContext) {
fallback = true;
} else {
if (canvas.toDataURL("image/png")
.indexOf("data:image/png") < 0) {
//Android doesn't support data URI
fallback = true;
} else {
var ctx = canvas.getContext("2d");
}
}
var fluid_images = [];
var settings = {
domain: "holder.js",
images: "img",
elements: ".holderjs",
themes: {
"gray": {
background: "#eee",
foreground: "#aaa",
size: 12
},
"social": {
background: "#3a5a97",
foreground: "#fff",
size: 12
},
"industrial": {
background: "#434A52",
foreground: "#C2F200",
size: 12
}
},
stylesheet: ".holderjs-fluid {font-size:16px;font-weight:bold;text-align:center;font-family:sans-serif;border-collapse:collapse;border:0;vertical-align:middle;margin:0}"
};
app.flags = {
dimensions: {
regex: /(\d+)x(\d+)/,
output: function (val) {
var exec = this.regex.exec(val);
return {
width: +exec[1],
height: +exec[2]
}
}
},
fluid: {
regex: /([0-9%]+)x([0-9%]+)/,
output: function (val) {
var exec = this.regex.exec(val);
return {
width: exec[1],
height: exec[2]
}
}
},
colors: {
regex: /#([0-9a-f]{3,})\:#([0-9a-f]{3,})/i,
output: function (val) {
var exec = this.regex.exec(val);
return {
size: settings.themes.gray.size,
foreground: "#" + exec[2],
background: "#" + exec[1]
}
}
},
text: {
regex: /text\:(.*)/,
output: function (val) {
return this.regex.exec(val)[1];
}
}
}
for (var flag in app.flags) {
app.flags[flag].match = function (val) {
return val.match(this.regex)
}
}
app.add_theme = function (name, theme) {
name != null && theme != null && (settings.themes[name] = theme);
return app;
};
app.add_image = function (src, el) {
var node = selector(el);
if (node.length) {
for (var i = 0, l = node.length; i < l; i++) {
var img = document.createElement("img")
img.setAttribute("data-src", src);
node[i].appendChild(img);
}
}
return app;
};
app.run = function (o) {
var options = extend(settings, o),
images_nodes = selector(options.images),
elements = selector(options.elements),
preempted = true,
images = [];
for (i = 0, l = images_nodes.length; i < l; i++) images.push(images_nodes[i]);
var holdercss = document.createElement("style");
holdercss.type = "text/css";
holdercss.styleSheet ? holdercss.styleSheet.cssText = options.stylesheet : holdercss.textContent = options.stylesheet;
document.getElementsByTagName("head")[0].appendChild(holdercss);
var cssregex = new RegExp(options.domain + "\/(.*?)\"?\\)");
for (var l = elements.length, i = 0; i < l; i++) {
var src = window.getComputedStyle(elements[i], null)
.getPropertyValue("background-image");
var flags = src.match(cssregex);
if (flags) {
var holder = parse_flags(flags[1].split("/"), options);
if (holder) {
render("background", elements[i], holder, src);
}
}
}
for (var l = images.length, i = 0; i < l; i++) {
var src = images[i].getAttribute("src") || images[i].getAttribute("data-src");
if (src != null && src.indexOf(options.domain) >= 0) {
var holder = parse_flags(src.substr(src.lastIndexOf(options.domain) + options.domain.length + 1)
.split("/"), options);
if (holder) {
if (holder.fluid) {
fluid(images[i], holder, src);
} else {
render("image", images[i], holder, src);
}
}
}
}
return app;
};
contentLoaded(win, function () {
if (window.addEventListener) {
window.addEventListener("resize", fluid_update, false);
window.addEventListener("orientationchange", fluid_update, false);
} else {
window.attachEvent("onresize", fluid_update)
}
preempted || app.run();
});
})(Holder, window);
|
069ka-ambition-cms
|
trunk/bkp/ambition_before_session/assets/js/holder/holder.js
|
JavaScript
|
mit
| 10,517
|
.com { color: #93a1a1; }
.lit { color: #195f91; }
.pun, .opn, .clo { color: #93a1a1; }
.fun { color: #dc322f; }
.str, .atv { color: #D14; }
.kwd, .prettyprint .tag { color: #1e347b; }
.typ, .atn, .dec, .var { color: teal; }
.pln { color: #48484c; }
.prettyprint {
padding: 8px;
background-color: #f7f7f9;
border: 1px solid #e1e1e8;
}
.prettyprint.linenums {
-webkit-box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0;
-moz-box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0;
box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0;
}
/* Specify class=linenums on a pre to get line numbering */
ol.linenums {
margin: 0 0 0 33px; /* IE indents via margin-left */
}
ol.linenums li {
padding-left: 12px;
color: #bebec5;
line-height: 20px;
text-shadow: 0 1px 0 #fff;
}
|
069ka-ambition-cms
|
trunk/bkp/ambition_before_session/assets/js/google-code-prettify/prettify.css
|
CSS
|
mit
| 817
|
/* Add additional stylesheets below
-------------------------------------------------- */
/*
Bootstrap's documentation styles
Special styles for presenting Bootstrap's documentation and examples
*/
/* Body and structure
-------------------------------------------------- */
body {
position: relative;
padding-top: 40px;
}
/* Code in headings */
h3 code {
font-size: 14px;
font-weight: normal;
}
/* Tweak navbar brand link to be super sleek
-------------------------------------------------- */
body > .navbar {
font-size: 13px;
}
/* Change the docs' brand */
body > .navbar .brand {
padding-right: 0;
padding-left: 0;
margin-left: 20px;
float: right;
font-weight: bold;
color: #000;
text-shadow: 0 1px 0 rgba(255,255,255,.1), 0 0 30px rgba(255,255,255,.125);
-webkit-transition: all .2s linear;
-moz-transition: all .2s linear;
transition: all .2s linear;
}
body > .navbar .brand:hover {
text-decoration: none;
text-shadow: 0 1px 0 rgba(255,255,255,.1), 0 0 30px rgba(255,255,255,.4);
}
/* Sections
-------------------------------------------------- */
/* padding for in-page bookmarks and fixed navbar */
section {
padding-top: 30px;
}
section > .page-header,
section > .lead {
color: #5a5a5a;
}
section > ul li {
margin-bottom: 5px;
}
/* Separators (hr) */
.bs-docs-separator {
margin: 40px 0 39px;
}
/* Faded out hr */
hr.soften {
height: 1px;
margin: 70px 0;
background-image: -webkit-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,.1), rgba(0,0,0,0));
background-image: -moz-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,.1), rgba(0,0,0,0));
background-image: -ms-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,.1), rgba(0,0,0,0));
background-image: -o-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,.1), rgba(0,0,0,0));
border: 0;
}
/* Jumbotrons
-------------------------------------------------- */
/* Base class
------------------------- */
.jumbotron {
position: relative;
padding: 40px 0;
color: #fff;
text-align: center;
text-shadow: 0 1px 3px rgba(0,0,0,.4), 0 0 30px rgba(0,0,0,.075);
background: #020031; /* Old browsers */
background: -moz-linear-gradient(45deg, #020031 0%, #6d3353 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left bottom, right top, color-stop(0%,#020031), color-stop(100%,#6d3353)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(45deg, #020031 0%,#6d3353 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(45deg, #020031 0%,#6d3353 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(45deg, #020031 0%,#6d3353 100%); /* IE10+ */
background: linear-gradient(45deg, #020031 0%,#6d3353 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#020031', endColorstr='#6d3353',GradientType=1 ); /* IE6-9 fallback on horizontal gradient */
-webkit-box-shadow: inset 0 3px 7px rgba(0,0,0,.2), inset 0 -3px 7px rgba(0,0,0,.2);
-moz-box-shadow: inset 0 3px 7px rgba(0,0,0,.2), inset 0 -3px 7px rgba(0,0,0,.2);
box-shadow: inset 0 3px 7px rgba(0,0,0,.2), inset 0 -3px 7px rgba(0,0,0,.2);
}
.jumbotron h1 {
font-size: 80px;
font-weight: bold;
letter-spacing: -1px;
line-height: 1;
}
.jumbotron p {
font-size: 24px;
font-weight: 300;
line-height: 1.25;
margin-bottom: 30px;
}
/* Link styles (used on .masthead-links as well) */
.jumbotron a {
color: #fff;
color: rgba(255,255,255,.5);
-webkit-transition: all .2s ease-in-out;
-moz-transition: all .2s ease-in-out;
transition: all .2s ease-in-out;
}
.jumbotron a:hover {
color: #fff;
text-shadow: 0 0 10px rgba(255,255,255,.25);
}
/* Download button */
.masthead .btn {
padding: 19px 24px;
font-size: 24px;
font-weight: 200;
color: #fff; /* redeclare to override the `.jumbotron a` */
border: 0;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
-webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 5px rgba(0,0,0,.25);
-moz-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 5px rgba(0,0,0,.25);
box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 5px rgba(0,0,0,.25);
-webkit-transition: none;
-moz-transition: none;
transition: none;
}
.masthead .btn:hover {
-webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 5px rgba(0,0,0,.25);
-moz-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 5px rgba(0,0,0,.25);
box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 5px rgba(0,0,0,.25);
}
.masthead .btn:active {
-webkit-box-shadow: inset 0 2px 4px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.1);
-moz-box-shadow: inset 0 2px 4px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.1);
box-shadow: inset 0 2px 4px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.1);
}
/* Pattern overlay
------------------------- */
.jumbotron .container {
position: relative;
z-index: 2;
}
.jumbotron:after {
content: '';
display: block;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: url(../img/bs-docs-masthead-pattern.png) repeat center center;
opacity: .4;
}
@media
only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and ( min--moz-device-pixel-ratio: 2),
only screen and ( -o-min-device-pixel-ratio: 2/1) {
.jumbotron:after {
background-size: 150px 150px;
}
}
/* Masthead (docs home)
------------------------- */
.masthead {
padding: 70px 0 80px;
margin-bottom: 0;
color: #fff;
}
.masthead h1 {
font-size: 120px;
line-height: 1;
letter-spacing: -2px;
}
.masthead p {
font-size: 40px;
font-weight: 200;
line-height: 1.25;
}
/* Textual links in masthead */
.masthead-links {
margin: 0;
list-style: none;
}
.masthead-links li {
display: inline;
padding: 0 10px;
color: rgba(255,255,255,.25);
}
/* Social proof buttons from GitHub & Twitter */
.bs-docs-social {
padding: 15px 0;
text-align: center;
background-color: #f5f5f5;
border-top: 1px solid #fff;
border-bottom: 1px solid #ddd;
}
/* Quick links on Home */
.bs-docs-social-buttons {
margin-left: 0;
margin-bottom: 0;
padding-left: 0;
list-style: none;
}
.bs-docs-social-buttons li {
display: inline-block;
padding: 5px 8px;
line-height: 1;
*display: inline;
*zoom: 1;
}
/* Subhead (other pages)
------------------------- */
.subhead {
text-align: left;
border-bottom: 1px solid #ddd;
}
.subhead h1 {
font-size: 60px;
}
.subhead p {
margin-bottom: 20px;
}
.subhead .navbar {
display: none;
}
/* Marketing section of Overview
-------------------------------------------------- */
.marketing {
text-align: center;
color: #5a5a5a;
}
.marketing h1 {
margin: 60px 0 10px;
font-size: 60px;
font-weight: 200;
line-height: 1;
letter-spacing: -1px;
}
.marketing h2 {
font-weight: 200;
margin-bottom: 5px;
}
.marketing p {
font-size: 16px;
line-height: 1.5;
}
.marketing .marketing-byline {
margin-bottom: 40px;
font-size: 20px;
font-weight: 300;
line-height: 1.25;
color: #999;
}
.marketing-img {
display: block;
margin: 0 auto 30px;
max-height: 145px;
}
/* Footer
-------------------------------------------------- */
.footer {
text-align: center;
padding: 30px 0;
margin-top: 70px;
border-top: 1px solid #e5e5e5;
background-color: #f5f5f5;
}
.footer p {
margin-bottom: 0;
color: #777;
}
.footer-links {
margin: 10px 0;
}
.footer-links li {
display: inline;
padding: 0 2px;
}
.footer-links li:first-child {
padding-left: 0;
}
/* Special grid styles
-------------------------------------------------- */
.show-grid {
margin-top: 10px;
margin-bottom: 20px;
}
.show-grid [class*="span"] {
background-color: #eee;
text-align: center;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
min-height: 40px;
line-height: 40px;
}
.show-grid:hover [class*="span"] {
background: #ddd;
}
.show-grid .show-grid {
margin-top: 0;
margin-bottom: 0;
}
.show-grid .show-grid [class*="span"] {
margin-top: 5px;
}
.show-grid [class*="span"] [class*="span"] {
background-color: #ccc;
}
.show-grid [class*="span"] [class*="span"] [class*="span"] {
background-color: #999;
}
/* Mini layout previews
-------------------------------------------------- */
.mini-layout {
border: 1px solid #ddd;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.075);
-moz-box-shadow: 0 1px 2px rgba(0,0,0,.075);
box-shadow: 0 1px 2px rgba(0,0,0,.075);
}
.mini-layout,
.mini-layout .mini-layout-body,
.mini-layout.fluid .mini-layout-sidebar {
height: 300px;
}
.mini-layout {
margin-bottom: 20px;
padding: 9px;
}
.mini-layout div {
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
.mini-layout .mini-layout-body {
background-color: #dceaf4;
margin: 0 auto;
width: 70%;
}
.mini-layout.fluid .mini-layout-sidebar,
.mini-layout.fluid .mini-layout-header,
.mini-layout.fluid .mini-layout-body {
float: left;
}
.mini-layout.fluid .mini-layout-sidebar {
background-color: #bbd8e9;
width: 20%;
}
.mini-layout.fluid .mini-layout-body {
width: 77.5%;
margin-left: 2.5%;
}
/* Download page
-------------------------------------------------- */
.download .page-header {
margin-top: 36px;
}
.page-header .toggle-all {
margin-top: 5px;
}
/* Space out h3s when following a section */
.download h3 {
margin-bottom: 5px;
}
.download-builder input + h3,
.download-builder .checkbox + h3 {
margin-top: 9px;
}
/* Fields for variables */
.download-builder input[type=text] {
margin-bottom: 9px;
font-family: Menlo, Monaco, "Courier New", monospace;
font-size: 12px;
color: #d14;
}
.download-builder input[type=text]:focus {
background-color: #fff;
}
/* Custom, larger checkbox labels */
.download .checkbox {
padding: 6px 10px 6px 25px;
font-size: 13px;
line-height: 18px;
color: #555;
background-color: #f9f9f9;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
cursor: pointer;
}
.download .checkbox:hover {
color: #333;
background-color: #f5f5f5;
}
.download .checkbox small {
font-size: 12px;
color: #777;
}
/* Variables section */
#variables label {
margin-bottom: 0;
}
/* Giant download button */
.download-btn {
margin: 36px 0 108px;
}
#download p,
#download h4 {
max-width: 50%;
margin: 0 auto;
color: #999;
text-align: center;
}
#download h4 {
margin-bottom: 0;
}
#download p {
margin-bottom: 18px;
}
.download-btn .btn {
display: block;
width: auto;
padding: 19px 24px;
margin-bottom: 27px;
font-size: 30px;
line-height: 1;
text-align: center;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
}
/* Misc
-------------------------------------------------- */
/* Make tables spaced out a bit more */
h2 + table,
h3 + table,
h4 + table,
h2 + .row {
margin-top: 5px;
}
/* Example sites showcase */
.example-sites {
xmargin-left: 20px;
}
.example-sites img {
max-width: 100%;
margin: 0 auto;
}
.scrollspy-example {
height: 200px;
overflow: auto;
position: relative;
}
/* Fake the :focus state to demo it */
.focused {
border-color: rgba(82,168,236,.8);
-webkit-box-shadow: inset 0 1px 3px rgba(0,0,0,.1), 0 0 8px rgba(82,168,236,.6);
-moz-box-shadow: inset 0 1px 3px rgba(0,0,0,.1), 0 0 8px rgba(82,168,236,.6);
box-shadow: inset 0 1px 3px rgba(0,0,0,.1), 0 0 8px rgba(82,168,236,.6);
outline: 0;
}
/* For input sizes, make them display block */
.docs-input-sizes select,
.docs-input-sizes input[type=text] {
display: block;
margin-bottom: 9px;
}
/* Icons
------------------------- */
.the-icons {
margin-left: 0;
list-style: none;
}
.the-icons li {
float: left;
width: 25%;
line-height: 25px;
}
.the-icons i:hover {
background-color: rgba(255,0,0,.25);
}
/* Example page
------------------------- */
.bootstrap-examples p {
font-size: 13px;
line-height: 18px;
}
.bootstrap-examples .thumbnail {
margin-bottom: 9px;
background-color: #fff;
}
/* Bootstrap code examples
-------------------------------------------------- */
/* Base class */
.bs-docs-example {
position: relative;
margin: 15px 0;
padding: 39px 19px 14px;
*padding-top: 19px;
background-color: #fff;
border: 1px solid #ddd;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
/* Echo out a label for the example */
.bs-docs-example:after {
content: "Example";
position: absolute;
top: -1px;
left: -1px;
padding: 3px 7px;
font-size: 12px;
font-weight: bold;
background-color: #f5f5f5;
border: 1px solid #ddd;
color: #9da0a4;
-webkit-border-radius: 4px 0 4px 0;
-moz-border-radius: 4px 0 4px 0;
border-radius: 4px 0 4px 0;
}
/* Remove spacing between an example and it's code */
.bs-docs-example + .prettyprint {
margin-top: -20px;
padding-top: 15px;
}
/* Tweak examples
------------------------- */
.bs-docs-example > p:last-child {
margin-bottom: 0;
}
.bs-docs-example .table,
.bs-docs-example .progress,
.bs-docs-example .well,
.bs-docs-example .alert,
.bs-docs-example .hero-unit,
.bs-docs-example .pagination,
.bs-docs-example .navbar,
.bs-docs-example > .nav,
.bs-docs-example blockquote {
margin-bottom: 5px;
}
.bs-docs-example .pagination {
margin-top: 0;
}
.bs-navbar-top-example,
.bs-navbar-bottom-example {
z-index: 1;
padding: 0;
height: 90px;
overflow: hidden; /* cut the drop shadows off */
}
.bs-navbar-top-example .navbar-fixed-top,
.bs-navbar-bottom-example .navbar-fixed-bottom {
margin-left: 0;
margin-right: 0;
}
.bs-navbar-top-example {
-webkit-border-radius: 0 0 4px 4px;
-moz-border-radius: 0 0 4px 4px;
border-radius: 0 0 4px 4px;
}
.bs-navbar-top-example:after {
top: auto;
bottom: -1px;
-webkit-border-radius: 0 4px 0 4px;
-moz-border-radius: 0 4px 0 4px;
border-radius: 0 4px 0 4px;
}
.bs-navbar-bottom-example {
-webkit-border-radius: 4px 4px 0 0;
-moz-border-radius: 4px 4px 0 0;
border-radius: 4px 4px 0 0;
}
.bs-navbar-bottom-example .navbar {
margin-bottom: 0;
}
form.bs-docs-example {
padding-bottom: 19px;
}
/* Images */
.bs-docs-example-images img {
margin: 10px;
display: inline-block;
}
/* Tooltips */
.bs-docs-tooltip-examples {
text-align: center;
margin: 0 0 10px;
list-style: none;
}
.bs-docs-tooltip-examples li {
display: inline;
padding: 0 10px;
}
/* Popovers */
.bs-docs-example-popover {
padding-bottom: 24px;
background-color: #f9f9f9;
}
.bs-docs-example-popover .popover {
position: relative;
display: block;
float: left;
width: 260px;
margin: 20px;
}
/* Dropdowns */
.bs-docs-example-submenus {
min-height: 180px;
}
.bs-docs-example-submenus > .pull-left + .pull-left {
margin-left: 20px;
}
.bs-docs-example-submenus .dropup > .dropdown-menu,
.bs-docs-example-submenus .dropdown > .dropdown-menu {
display: block;
position: static;
margin-bottom: 5px;
*width: 180px;
}
/* Responsive docs
-------------------------------------------------- */
/* Utility classes table
------------------------- */
.responsive-utilities th small {
display: block;
font-weight: normal;
color: #999;
}
.responsive-utilities tbody th {
font-weight: normal;
}
.responsive-utilities td {
text-align: center;
}
.responsive-utilities td.is-visible {
color: #468847;
background-color: #dff0d8 !important;
}
.responsive-utilities td.is-hidden {
color: #ccc;
background-color: #f9f9f9 !important;
}
/* Responsive tests
------------------------- */
.responsive-utilities-test {
margin-top: 5px;
margin-left: 0;
list-style: none;
overflow: hidden; /* clear floats */
}
.responsive-utilities-test li {
position: relative;
float: left;
width: 25%;
height: 43px;
font-size: 14px;
font-weight: bold;
line-height: 43px;
color: #999;
text-align: center;
border: 1px solid #ddd;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.responsive-utilities-test li + li {
margin-left: 10px;
}
.responsive-utilities-test span {
position: absolute;
top: -1px;
left: -1px;
right: -1px;
bottom: -1px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.responsive-utilities-test span {
color: #468847;
background-color: #dff0d8;
border: 1px solid #d6e9c6;
}
/* Sidenav for Docs
-------------------------------------------------- */
.bs-docs-sidenav {
width: 228px;
margin: 30px 0 0;
padding: 0;
background-color: #fff;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
-webkit-box-shadow: 0 1px 4px rgba(0,0,0,.065);
-moz-box-shadow: 0 1px 4px rgba(0,0,0,.065);
box-shadow: 0 1px 4px rgba(0,0,0,.065);
}
.bs-docs-sidenav > li > a {
display: block;
width: 190px \9;
margin: 0 0 -1px;
padding: 8px 14px;
border: 1px solid #e5e5e5;
}
.bs-docs-sidenav > li:first-child > a {
-webkit-border-radius: 6px 6px 0 0;
-moz-border-radius: 6px 6px 0 0;
border-radius: 6px 6px 0 0;
}
.bs-docs-sidenav > li:last-child > a {
-webkit-border-radius: 0 0 6px 6px;
-moz-border-radius: 0 0 6px 6px;
border-radius: 0 0 6px 6px;
}
.bs-docs-sidenav > .active > a {
position: relative;
z-index: 2;
padding: 9px 15px;
border: 0;
text-shadow: 0 1px 0 rgba(0,0,0,.15);
-webkit-box-shadow: inset 1px 0 0 rgba(0,0,0,.1), inset -1px 0 0 rgba(0,0,0,.1);
-moz-box-shadow: inset 1px 0 0 rgba(0,0,0,.1), inset -1px 0 0 rgba(0,0,0,.1);
box-shadow: inset 1px 0 0 rgba(0,0,0,.1), inset -1px 0 0 rgba(0,0,0,.1);
}
/* Chevrons */
.bs-docs-sidenav .icon-chevron-right {
float: right;
margin-top: 2px;
margin-right: -6px;
opacity: .25;
}
.bs-docs-sidenav > li > a:hover {
background-color: #f5f5f5;
}
.bs-docs-sidenav a:hover .icon-chevron-right {
opacity: .5;
}
.bs-docs-sidenav .active .icon-chevron-right,
.bs-docs-sidenav .active a:hover .icon-chevron-right {
background-image: url(../img/glyphicons-halflings-white.png);
opacity: 1;
}
.bs-docs-sidenav.affix {
top: 40px;
}
.bs-docs-sidenav.affix-bottom {
position: absolute;
top: auto;
bottom: 270px;
}
/* Responsive
-------------------------------------------------- */
/* Desktop large
------------------------- */
@media (min-width: 1200px) {
.bs-docs-container {
max-width: 970px;
}
.bs-docs-sidenav {
width: 258px;
}
.bs-docs-sidenav > li > a {
width: 230px \9; /* Override the previous IE8-9 hack */
}
}
/* Desktop
------------------------- */
@media (max-width: 980px) {
/* Unfloat brand */
body > .navbar-fixed-top .brand {
float: left;
margin-left: 0;
padding-left: 10px;
padding-right: 10px;
}
/* Inline-block quick links for more spacing */
.quick-links li {
display: inline-block;
margin: 5px;
}
/* When affixed, space properly */
.bs-docs-sidenav {
top: 0;
width: 218px;
margin-top: 30px;
margin-right: 0;
}
}
/* Tablet to desktop
------------------------- */
@media (min-width: 768px) and (max-width: 979px) {
/* Remove any padding from the body */
body {
padding-top: 0;
}
/* Widen masthead and social buttons to fill body padding */
.jumbotron {
margin-top: -20px; /* Offset bottom margin on .navbar */
}
/* Adjust sidenav width */
.bs-docs-sidenav {
width: 166px;
margin-top: 20px;
}
.bs-docs-sidenav.affix {
top: 0;
}
}
/* Tablet
------------------------- */
@media (max-width: 767px) {
/* Remove any padding from the body */
body {
padding-top: 0;
}
/* Widen masthead and social buttons to fill body padding */
.jumbotron {
padding: 40px 20px;
margin-top: -20px; /* Offset bottom margin on .navbar */
margin-right: -20px;
margin-left: -20px;
}
.masthead h1 {
font-size: 90px;
}
.masthead p,
.masthead .btn {
font-size: 24px;
}
.marketing .span4 {
margin-bottom: 40px;
}
.bs-docs-social {
margin: 0 -20px;
}
/* Space out the show-grid examples */
.show-grid [class*="span"] {
margin-bottom: 5px;
}
/* Sidenav */
.bs-docs-sidenav {
width: auto;
margin-bottom: 20px;
}
.bs-docs-sidenav.affix {
position: static;
width: auto;
top: 0;
}
/* Unfloat the back to top link in footer */
.footer {
margin-left: -20px;
margin-right: -20px;
padding-left: 20px;
padding-right: 20px;
}
.footer p {
margin-bottom: 9px;
}
}
/* Landscape phones
------------------------- */
@media (max-width: 480px) {
/* Remove padding above jumbotron */
body {
padding-top: 0;
}
/* Change up some type stuff */
h2 small {
display: block;
}
/* Downsize the jumbotrons */
.jumbotron h1 {
font-size: 45px;
}
.jumbotron p,
.jumbotron .btn {
font-size: 18px;
}
.jumbotron .btn {
display: block;
margin: 0 auto;
}
/* center align subhead text like the masthead */
.subhead h1,
.subhead p {
text-align: center;
}
/* Marketing on home */
.marketing h1 {
font-size: 30px;
}
.marketing-byline {
font-size: 18px;
}
/* center example sites */
.example-sites {
margin-left: 0;
}
.example-sites > li {
float: none;
display: block;
max-width: 280px;
margin: 0 auto 18px;
text-align: center;
}
.example-sites .thumbnail > img {
max-width: 270px;
}
/* Do our best to make tables work in narrow viewports */
table code {
white-space: normal;
word-wrap: break-word;
word-break: break-all;
}
/* Examples: dropdowns */
.bs-docs-example-submenus > .pull-left {
float: none;
clear: both;
}
.bs-docs-example-submenus > .pull-left,
.bs-docs-example-submenus > .pull-left + .pull-left {
margin-left: 0;
}
.bs-docs-example-submenus p {
margin-bottom: 0;
}
.bs-docs-example-submenus .dropup > .dropdown-menu,
.bs-docs-example-submenus .dropdown > .dropdown-menu {
margin-bottom: 10px;
float: none;
max-width: 180px;
}
/* Examples: modal */
.modal-example .modal {
position: relative;
top: auto;
right: auto;
bottom: auto;
left: auto;
}
/* Tighten up footer */
.footer {
padding-top: 20px;
padding-bottom: 20px;
}
}
|
069ka-ambition-cms
|
trunk/bkp/ambition_before_session/assets/css/docs.css
|
CSS
|
mit
| 22,431
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bootstrap, from Twitter</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">PV Gallery</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">USers</a></li>
<li><a href="#contact">Photos</a></li>
<li><a href="#contact">Videos</a></li>
<li><a href="#contact">Feedback</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>Welcome to PV Gallery</h1>
<p>Use this document as a way to quick start any new project.<br> All you get is this message and a barebones HTML document.</p>
<h3>Add New User</h3>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/bkp/user_add.php
|
Hack
|
mit
| 3,406
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Fresh Pick</title>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
<meta name="author" content="Erwin Aligam - styleshout.com" />
<meta name="description" content="Site Description Here" />
<meta name="keywords" content="keywords, here" />
<meta name="robots" content="index, follow, noarchive" />
<meta name="googlebot" content="noarchive" />
<link rel="stylesheet" type="text/css" media="screen" href="css/screen.css" />
</head>
<body>
<!-- wrap starts here -->
<div id="wrap">
<!--header -->
<div id="header">
<h1 id="logo-text"><a href="index.html" title="">Freshpick</a></h1>
<p id="slogan">Just Another Styleshout CSS Template... </p>
<div id="nav">
<ul>
<li class="first" id="current"><a href="index.html">Home</a></li>
<li><a href="style.html">Style Demo</a></li>
<li><a href="blog.html">Blog</a></li>
<li><a href="archives.html">Archives</a></li>
<li><a href="index.html">Support</a></li>
<li><a href="index.html">About</a></li>
</ul>
</div>
<div id="header-image"></div>
<!--header ends-->
</div>
<!-- featured starts -->
<div id="featured" class="clear">
<a name="TemplateInfo"></a>
<div class="image-block">
<img src="images/img-featured.jpg" alt="featured"/>
</div>
<div class="text-block">
<h2><a href="index.html">Read me first</a></h2>
<p class="post-info">Posted by <a href="index.html">erwin</a> | Filed under <a href="index.html">templates</a>, <a href="index.html">internet</a></p>
<p><strong>FreshPick</strong> is a free, W3C-compliant, CSS-based website template
by <a href="http://www.styleshout.com/">styleshout.com</a>. This work is
distributed under the <a rel="license" href="http://creativecommons.org/licenses/by/2.5/">
Creative Commons Attribution 2.5 License</a>, which means that you are free to
use and modify it for any purpose. All I ask is that you give me credit by including a <strong>link back</strong> to
<a href="http://www.styleshout.com/">my website</a>.
</p>
<p>
You can find more of my free template designs at <a href="http://www.styleshout.com/">my website</a>.
For premium commercial designs, you can check out
<a href="http://www.dreamtemplate.com" title="Website Templates">DreamTemplate.com</a>.
</p>
<p><a href="index.html" class="more-link">Read More</a></p>
</div>
<!-- featured ends -->
</div>
<!-- content -->
<div id="content-outer" class="clear"><div id="content-wrap">
<div id="content">
<div id="left">
<div class="entry">
<h3><a href="index.html">Aliquam Risus Justo</a></h3>
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam. Cras fringilla magna. Phasellus suscipit, leo a pharetra
condimentum, lorem tellus eleifend magna, eget fringilla velit magna id neque. Curabitur vel urna.
In tristique orci porttitor ipsum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo.
</p>
<p><a class="more-link" href="index.html">continue reading</a></p>
</div>
<div class="entry">
<h3>Lorem Ipsum Dolor Sit Amet</h3>
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam. Cras fringilla magna. Phasellus suscipit, leo a pharetra
condimentum, lorem tellus eleifend magna, eget fringilla velit magna id neque. Curabitur vel urna.
In tristique orci porttitor ipsum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo.
</p>
<p><a class="more-link" href="index.html">continue reading</a></p>
</div>
<div class="entry">
<h3>Lorem Ipsum</h3>
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam. Cras fringilla magna. Phasellus suscipit, leo a pharetra
condimentum, lorem tellus eleifend magna, eget fringilla velit magna id neque. Curabitur vel urna.
In tristique orci porttitor ipsum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo.
</p>
<p><a class="more-link" href="index.html">continue reading</a></p>
</div>
</div>
<div id="right">
<div class="sidemenu">
<h3>Sidebar Menu</h3>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="index.html#TemplateInfo">TemplateInfo</a></li>
<li><a href="style.html">Style Demo</a></li>
<li><a href="blog.html">Blog</a></li>
<li><a href="archives.html">Archives</a></li>
<li><a href="http://www.dreamtemplate.com" title="Web Templates">Web Templates</a></li>
</ul>
</div>
<div class="sidemenu">
<h3>Sponsors</h3>
<ul>
<li><a href="http://www.dreamtemplate.com" title="Website Templates">DreamTemplate <br />
<span>Over 6,000+ Premium Web Templates</span></a>
</li>
<li><a href="http://www.themelayouts.com" title="WordPress Themes">ThemeLayouts <br />
<span>Premium WordPress & Joomla Themes</span></a>
</li>
<li><a href="http://www.imhosted.com" title="Website Hosting">ImHosted.com <br />
<span>Affordable Web Hosting Provider</span></a>
</li>
<li><a href="http://www.dreamstock.com" title="Stock Photos">DreamStock <br />
<span>Download Amazing Stock Photos</span></a>
</li>
<li><a href="http://www.evrsoft.com" title="Website Builder">Evrsoft <br />
<span>Website Builder Software & Tools</span></a>
</li>
<li><a href="http://www.webhostingwp.com" title="Web Hosting">Web Hosting <br />
<span>Top 10 Hosting Reviews</span></a>
</li>
</ul>
</div>
<h3>Search</h3>
<form id="quick-search" action="index.html" method="get" >
<p>
<label for="qsearch">Search:</label>
<input class="tbox" id="qsearch" type="text" name="qsearch" value="type and hit enter..." title="Start typing and hit ENTER" />
<input class="btn" alt="Search" type="image" name="searchsubmit" title="Search" src="images/search.gif" />
</p>
</form>
</div>
</div>
<!-- content end -->
</div></div>
<!-- footer starts here -->
<div id="footer-outer" class="clear"><div id="footer-wrap">
<div class="col-a">
<h3>Image Gallery </h3>
<p class="thumbs">
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
</p>
<h3>Lorem ipsum dolor</h3>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam. Cras fringilla magna.
</p>
</div>
<div class="col-a">
<h3>Lorem Ipsum</h3>
<p>
<strong>Lorem ipsum dolor</strong> <br />
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam.</p>
<div class="footer-list">
<ul>
<li><a href="index.html">consequat molestie</a></li>
<li><a href="index.html">sem justo</a></li>
<li><a href="index.html">semper</a></li>
<li><a href="index.html">magna sed purus</a></li>
<li><a href="index.html">tincidunt</a></li>
<li><a href="index.html">consequat molestie</a></li>
<li><a href="index.html">magna sed purus</a></li>
</ul>
</div>
</div>
<div class="col-b">
<h3>About</h3>
<p>
<a href="index.html"><img src="images/gravatar.jpg" width="40" height="40" alt="firefox" class="float-left" /></a>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam.</p>
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. <a href="index.html">Learn more...</a></p>
</div>
<!-- footer ends -->
</div></div>
<!-- footer-bottom starts -->
<div id="footer-bottom">
<div class="bottom-left">
<p>
© 2010 <strong>Your Copyright Info Here</strong>
<a href="http://www.bluewebtemplates.com/" title="Website Templates">website templates</a> by <a href="http://www.styleshout.com/">styleshout</a>
</p>
</div>
<div class="bottom-right">
<p>
<a href="http://jigsaw.w3.org/css-validator/check/referer">CSS</a> |
<a href="http://validator.w3.org/check/referer">XHTML</a> |
<a href="index.html">Home</a> |
<a href="index.html">Sitemap</a> |
<a href="index.html">RSS Feed</a>
</p>
</div>
<!-- footer-bottom ends -->
</div>
<!-- wrap ends here -->
</div>
</body>
</html>
|
069ka-ambition-cms
|
trunk/bkp/Freshpick10/index.html
|
HTML
|
mit
| 12,133
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Fresh Pick</title>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
<meta name="author" content="Erwin Aligam - styleshout.com" />
<meta name="description" content="Site Description Here" />
<meta name="keywords" content="keywords, here" />
<meta name="robots" content="index, follow, noarchive" />
<meta name="googlebot" content="noarchive" />
<link rel="stylesheet" type="text/css" media="screen" href="css/screen.css" />
</head>
<body>
<!-- wrap starts here -->
<div id="wrap">
<!--header -->
<div id="header">
<h1 id="logo-text"><a href="index.html" title="">Freshpick</a></h1>
<p id="slogan">Just Another Styleshout CSS Template... </p>
<div id="nav">
<ul>
<li class="first"><a href="index.html">Home</a></li>
<li><a href="style.html">Style Demo</a></li>
<li id="current"><a href="blog.html">Blog</a></li>
<li><a href="archives.html">Archives</a></li>
<li><a href="index.html">Support</a></li>
<li><a href="index.html">About</a></li>
</ul>
</div>
<div id="header-image"></div>
<!--header ends-->
</div>
<!-- content -->
<div id="content-outer" class="clear"><div id="content-wrap">
<div id="content">
<div id="left">
<div class="post no-bg">
<h2><a href="index.html">A Blog Entry</a></h2>
<p class="post-info">Posted by <a href="index.html">erwin</a> | Filed under <a href="index.html">templates</a>, <a href="index.html">internet</a> </p>
<div class="image-section">
<img src="images/img-post.jpg" alt="image post"/>
</div>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac <a href="index.html">convallis aliquam</a>, lectus turpis varius lorem, eu
posuere nunc justo tempus leo.</p>
<p>Donec mattis, purus nec placerat bibendum, <a href="index.html">dui pede condimentum</a>
odio, ac blandit ante orci ut diam. Cras fringilla magna. Phasellus suscipit, leo a pharetra
condimentum, lorem tellus eleifend magna, <a href="index.html">eget fringilla velit</a> magna id neque. Curabitur vel urna.
In tristique orci porttitor ipsum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo.</p>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam. Cras fringilla magna. Phasellus suscipit, leo a pharetra
condimentum, lorem tellus eleifend magna, eget fringilla velit magna id neque. Curabitur vel urna.
In tristique orci porttitor ipsum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo.
</p>
<p class="tags">
<strong>Tagged : </strong>
<a href="#">orci</a>, <a href="#">lectus</a>, <a href="#">varius</a>, <a href="#">turpis</a>
</p>
<p class="postmeta">
<a href="index.html" class="comments">Comments (3)</a> |
<span class="date">April 20, 2009</span> |
<a href="index.html" class="edit">Edit</a>
</p>
<h3 id="comments">3 Responses</h3>
<ol class="commentlist">
<li class="alt" id="comment-63">
<cite>
<img alt="" src="images/gravatar.jpg" class="avatar" height="40" width="40" />
<a href="index.html">Erwin</a> Says: <br />
<span class="comment-data"><a href="#comment-63" title="">April 20th, 2009 at 8:08 am</a> </span>
</cite>
<div class="comment-text">
<p>Comments are great!</p>
</div>
</li>
<li id="comment-67">
<cite>
<img alt="" src="images/gravatar.jpg" class="avatar" height="40" width="40" />
admin Says: <br />
<span class="comment-data"><a href="#comment-67" title="">April 20th, 2009 at 2:17 pm</a> </span>
</cite>
<div class="comment-text">
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero.
Suspendisse bibendum.</p>
</div>
</li>
<li class="alt" id="comment-71">
<cite>
<img alt="" src="images/gravatar.jpg" class="avatar" height="40" width="40" />
<a href="index.html">Erwin</a> Says: <br />
<span class="comment-data"><a href="#comment-71" title="">April 20th, 2009 at 3:17 pm</a> </span>
</cite>
<div class="comment-text">
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo.</p>
</div>
</li>
</ol>
<h3 id="respond">Leave a Reply</h3>
<form action="index.html" method="post" id="commentform">
<p>
<label for="name">Name (required)</label><br />
<input id="name" name="name" value="Your Name" type="text" tabindex="1" />
</p>
<p>
<label for="email">Email Address (required)</label><br />
<input id="email" name="email" value="Your Email" type="text" tabindex="2" />
</p>
<p>
<label for="website">Website</label><br />
<input id="website" name="website" value="Your Website" type="text" tabindex="3" />
</p>
<p>
<label for="message">Your Message</label><br />
<textarea id="message" name="message" rows="10" cols="20" tabindex="4"></textarea>
</p>
<p class="no-border">
<input class="button" type="submit" value="Submit" tabindex="5" />
</p>
</form>
</div>
</div>
<div id="right">
<div class="sidemenu">
<h3>Sidebar Menu</h3>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="index.html#TemplateInfo">TemplateInfo</a></li>
<li><a href="style.html">Style Demo</a></li>
<li><a href="blog.html">Blog</a></li>
<li><a href="archives.html">Archives</a></li>
<li><a href="http://www.dreamtemplate.com" title="Web Templates">Web Templates</a></li>
</ul>
</div>
<div class="sidemenu">
<h3>Sponsors</h3>
<ul>
<li><a href="http://www.dreamtemplate.com" title="Website Templates">DreamTemplate <br />
<span>Over 6,000+ Premium Web Templates</span></a>
</li>
<li><a href="http://www.themelayouts.com" title="WordPress Themes">ThemeLayouts <br />
<span>Premium WordPress & Joomla Themes</span></a>
</li>
<li><a href="http://www.imhosted.com" title="Website Hosting">ImHosted.com <br />
<span>Affordable Web Hosting Provider</span></a>
</li>
<li><a href="http://www.dreamstock.com" title="Stock Photos">DreamStock <br />
<span>Download Amazing Stock Photos</span></a>
</li>
<li><a href="http://www.evrsoft.com" title="Website Builder">Evrsoft <br />
<span>Website Builder Software & Tools</span></a>
</li>
<li><a href="http://www.webhostingwp.com" title="Web Hosting">Web Hosting <br />
<span>Top 10 Hosting Reviews</span></a>
</li>
</ul>
</div>
<h3>Search</h3>
<form id="quick-search" action="index.html" method="get" >
<p>
<label for="qsearch">Search:</label>
<input class="tbox" id="qsearch" type="text" name="qsearch" value="type and hit enter..." title="Start typing and hit ENTER" />
<input class="btn" alt="Search" type="image" name="searchsubmit" title="Search" src="images/search.gif" />
</p>
</form>
</div>
</div>
<!-- content end -->
</div></div>
<!-- footer starts here -->
<div id="footer-outer" class="clear"><div id="footer-wrap">
<div class="col-a">
<h3>Image Gallery </h3>
<p class="thumbs">
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
</p>
<h3>Lorem ipsum dolor</h3>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam. Cras fringilla magna.
</p>
</div>
<div class="col-a">
<h3>Lorem Ipsum</h3>
<p>
<strong>Lorem ipsum dolor</strong> <br />
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam.</p>
<div class="footer-list">
<ul>
<li><a href="index.html">consequat molestie</a></li>
<li><a href="index.html">sem justo</a></li>
<li><a href="index.html">semper</a></li>
<li><a href="index.html">magna sed purus</a></li>
<li><a href="index.html">tincidunt</a></li>
<li><a href="index.html">consequat molestie</a></li>
<li><a href="index.html">magna sed purus</a></li>
</ul>
</div>
</div>
<div class="col-b">
<h3>About</h3>
<p>
<a href="index.html"><img src="images/gravatar.jpg" width="40" height="40" alt="firefox" class="float-left" /></a>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam.</p>
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. <a href="index.html">Learn more...</a></p>
</div>
<!-- footer ends -->
</div></div>
<!-- footer-bottom starts -->
<div id="footer-bottom">
<div class="bottom-left">
<p>
© 2010 <strong>Your Copyright Info Here</strong>
<a href="http://www.bluewebtemplates.com/" title="Website Templates">website templates</a> by <a href="http://www.styleshout.com/">styleshout</a>
</p>
</div>
<div class="bottom-right">
<p>
<a href="http://jigsaw.w3.org/css-validator/check/referer">CSS</a> |
<a href="http://validator.w3.org/check/referer">XHTML</a> |
<a href="index.html">Home</a> |
<a href="index.html">Sitemap</a> |
<a href="index.html">RSS Feed</a>
</p>
</div>
<!-- footer-bottom ends -->
</div>
<!-- wrap ends here -->
</div>
</body>
</html>
|
069ka-ambition-cms
|
trunk/bkp/Freshpick10/blog.html
|
HTML
|
mit
| 12,853
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Fresh Pick</title>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
<meta name="author" content="Erwin Aligam - styleshout.com" />
<meta name="description" content="Site Description Here" />
<meta name="keywords" content="keywords, here" />
<meta name="robots" content="index, follow, noarchive" />
<meta name="googlebot" content="noarchive" />
<link rel="stylesheet" type="text/css" media="screen" href="css/screen.css" />
</head>
<body>
<!-- wrap starts here -->
<div id="wrap">
<!--header -->
<div id="header">
<h1 id="logo-text"><a href="index.html" title="">Freshpick</a></h1>
<p id="slogan">Just Another Styleshout CSS Template... </p>
<div id="nav">
<ul>
<li class="first"><a href="index.html">Home</a></li>
<li><a href="style.html">Style Demo</a></li>
<li><a href="blog.html">Blog</a></li>
<li id="current"><a href="archives.html">Archives</a></li>
<li><a href="index.html">Support</a></li>
<li><a href="index.html">About</a></li>
</ul>
</div>
<div id="header-image"></div>
<!--header ends-->
</div>
<!-- content -->
<div id="content-outer" class="clear"><div id="content-wrap">
<div id="content">
<div id="left">
<h2><a href="index.html">Archives for 2009</a></h2>
<div class="page-navigation clear">
<div class="float-left"><a href="#">« Older Entries</a></div>
<div class="float-right"><a href="#">Newer Entries » </a></div>
</div>
<ul class="archive">
<li>
<div class="post-title"><strong><a href="index.html">Suspendisse bibendum.</a></strong></div>
<div class="post-details">Posted on <a href="index.html">May 01, 2009</a> | Filed under <a href="index.html">templates</a>, <a href="index.html">internet</a></div>
</li>
<li>
<div class="post-title"><strong><a href="index.html">Lorem ipsum dolor sit amet.</a></strong></div>
<div class="post-details">Posted on <a href="index.html">May 01, 2009</a> | Filed under <a href="index.html">templates</a></div>
</li>
<li>
<div class="post-title"><strong><a href="index.html">In tristique orci porttitor ipsum.</a></strong></div>
<div class="post-details">Posted on <a href="index.html">April 30, 2009</a> | Filed under <a href="index.html">templates</a>, <a href="index.html">design</a></div>
</li>
<li>
<div class="post-title"><strong><a href="index.html">Donec libero. Suspendisse bibendum.</a></strong></div>
<div class="post-details">Posted on <a href="index.html">April 30, 2009</a> | Filed under <a href="index.html">templates</a>, <a href="index.html">design</a></div>
</li>
<li>
<div class="post-title"><strong><a href="index.html">Suspendisse bibendum.</a></strong></div>
<div class="post-details">Posted on <a href="index.html">April 28, 2009</a> | Filed under <a href="index.html">templates</a>, <a href="index.html">internet</a></div>
</li>
<li>
<div class="post-title"><strong><a href="index.html">Lorem ipsum dolor sit amet.</a></strong></div>
<div class="post-details">Posted on <a href="index.html">April 27, 2009</a> | Filed under <a href="index.html">templates</a></div>
</li>
<li>
<div class="post-title"><strong><a href="index.html">In tristique orci porttitor ipsum.</a></strong></div>
<div class="post-details">Posted on <a href="index.html">April 25, 2009</a> | Filed under <a href="index.html">templates</a>, <a href="index.html">design</a></div>
</li>
<li>
<div class="post-title"><strong><a href="index.html">Donec mattis, purus nec placerat bibendum.</a></strong></div>
<div class="post-details">Posted on <a href="index.html">April 25, 2009</a> | Filed under <a href="index.html">templates</a>, <a href="index.html">design</a></div>
</li>
</ul>
<div class="page-navigation clear">
<div class="float-left"><a href="#">« Older Entries</a></div>
<div class="float-right"><a href="#">Newer Entries » </a></div>
</div>
</div>
<div id="right">
<div class="sidemenu">
<h3>Sidebar Menu</h3>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="index.html#TemplateInfo">TemplateInfo</a></li>
<li><a href="style.html">Style Demo</a></li>
<li><a href="blog.html">Blog</a></li>
<li><a href="archives.html">Archives</a></li>
<li><a href="http://www.dreamtemplate.com" title="Web Templates">Web Templates</a></li>
</ul>
</div>
<div class="sidemenu">
<h3>Sponsors</h3>
<ul>
<li><a href="http://www.dreamtemplate.com" title="Website Templates">DreamTemplate <br />
<span>Over 6,000+ Premium Web Templates</span></a>
</li>
<li><a href="http://www.themelayouts.com" title="WordPress Themes">ThemeLayouts <br />
<span>Premium WordPress & Joomla Themes</span></a>
</li>
<li><a href="http://www.imhosted.com" title="Website Hosting">ImHosted.com <br />
<span>Affordable Web Hosting Provider</span></a>
</li>
<li><a href="http://www.dreamstock.com" title="Stock Photos">DreamStock <br />
<span>Download Amazing Stock Photos</span></a>
</li>
<li><a href="http://www.evrsoft.com" title="Website Builder">Evrsoft <br />
<span>Website Builder Software & Tools</span></a>
</li>
<li><a href="http://www.webhostingwp.com" title="Web Hosting">Web Hosting <br />
<span>Top 10 Hosting Reviews</span></a>
</li>
</ul>
</div>
<h3>Search</h3>
<form id="quick-search" action="index.html" method="get" >
<p>
<label for="qsearch">Search:</label>
<input class="tbox" id="qsearch" type="text" name="qsearch" value="type and hit enter..." title="Start typing and hit ENTER" />
<input class="btn" alt="Search" type="image" name="searchsubmit" title="Search" src="images/search.gif" />
</p>
</form>
</div>
</div>
<!-- content end -->
</div></div>
<!-- footer starts here -->
<div id="footer-outer" class="clear"><div id="footer-wrap">
<div class="col-a">
<h3>Image Gallery </h3>
<p class="thumbs">
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
</p>
<h3>Lorem ipsum dolor</h3>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam. Cras fringilla magna.
</p>
</div>
<div class="col-a">
<h3>Lorem Ipsum</h3>
<p>
<strong>Lorem ipsum dolor</strong> <br />
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam.</p>
<div class="footer-list">
<ul>
<li><a href="index.html">consequat molestie</a></li>
<li><a href="index.html">sem justo</a></li>
<li><a href="index.html">semper</a></li>
<li><a href="index.html">magna sed purus</a></li>
<li><a href="index.html">tincidunt</a></li>
<li><a href="index.html">consequat molestie</a></li>
<li><a href="index.html">magna sed purus</a></li>
</ul>
</div>
</div>
<div class="col-b">
<h3>About</h3>
<p>
<a href="index.html"><img src="images/gravatar.jpg" width="40" height="40" alt="firefox" class="float-left" /></a>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam.</p>
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. <a href="index.html">Learn more...</a></p>
</div>
<!-- footer ends -->
</div></div>
<!-- footer-bottom starts -->
<div id="footer-bottom">
<div class="bottom-left">
<p>
© 2010 <strong>Your Copyright Info Here</strong>
<a href="http://www.bluewebtemplates.com/" title="Website Templates">website templates</a> by <a href="http://www.styleshout.com/">styleshout</a>
</p>
</div>
<div class="bottom-right">
<p>
<a href="http://jigsaw.w3.org/css-validator/check/referer">CSS</a> |
<a href="http://validator.w3.org/check/referer">XHTML</a> |
<a href="index.html">Home</a> |
<a href="index.html">Sitemap</a> |
<a href="index.html">RSS Feed</a>
</p>
</div>
<!-- footer-bottom ends -->
</div>
<!-- wrap ends here -->
</div>
</body>
</html>
|
069ka-ambition-cms
|
trunk/bkp/Freshpick10/archives.html
|
HTML
|
mit
| 10,677
|
/* ----------------------------------------------
Template Name : FreshPick
Template Code : S-0029
Version : 1.0
Author : Erwin Aligam
Author URI : http://www.styleshout.com/
Last Date Modified : April 24, 2009
------------------------------------------------ */
/* ----------------------------------------------
HTML ELEMENTS
------------------------------------------------- */
body {
font: 12px/170% 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, Sans-Serif;
color: #666666;
margin: 0;
padding: 0;
background: #FFF url(../images/bg.gif) repeat-x;
text-align: center;
}
/* Links */
a:link, a:visited {
text-decoration: none;
color: #0788C3;
}
a:hover {
border-bottom: 1px dotted #0788C3;
}
a:link.more-link, a:visited.more-link {
padding-bottom: 2px;
font-weight: bold;
color: #0788C3;
border-bottom: 1px dotted #0788C3;
}
a:hover.more-link {
text-decoration: none;
}
/* Headers */
h1, h2, h3, h4 {
font: bold 1em/1.5em Georgia, 'Times New Roman', Times, serif;
color: #555;
margin: 10px 20px 7px 20px;
}
h1 { font-size: 3.7em; font-weight: normal; letter-spacing: -2px; }
h2 { font-size: 2.8em; font-weight: normal; }
h3 { font-size: 2.2em; font-weight: normal; letter-spacing: -0.5px; padding-top: 15px; }
h4 { font-size: 1.4em; }
/* Lists */
ul, ol {
margin: 10px 20px;
padding: 0 20px;
}
ul { list-style: disc; }
ol { list-style: decimal; }
dt {
font-weight: bold;
color: #1980AF;
}
dd {
padding-left: 20px;
}
p, dl { margin: 10px 20px; }
/* Images */
img {
background: #FAFAFA;
border: 1px solid #E4E4E4;
padding: 8px;
}
img.float-right {
margin: 5px 0px 10px 10px;
}
img.float-left {
margin: 5px 10px 10px 0px;
}
code {
margin: 3px 0;
padding: 15px;
text-align: left;
display: block;
overflow: auto;
font: 500 1em/1.5em 'Lucida Console', 'Courier New', Monospace;
/* white-space: pre; */
border: 1px solid #F0F0F0;
background: #F8F8F8;
}
acronym {
cursor: help;
border-bottom: 1px dotted #555;
}
blockquote {
margin: 10px 20px;
padding: 10px 10px 10px 32px;
border: 1px solid #F0F0F0;
background: #f8f8f8 url(../images/quote.gif) no-repeat 12px 12px;
font-weight: normal;
font-size: 17px;
line-height: 1.5em;
font-style: italic;
font-family: Georgia, 'Times New Roman', Times, Serif;
color: #555;
}
strong {
font-weight: bold;
}
/* start - table */
table {
border-collapse: collapse;
margin: 10px 20px;
}
tr { background: #FFF; }
tr.altrow { background: #F9F9F9; }
th, td {
text-align: left;
border-width: 1px;
border-style: solid;
}
th {
color: #555;
background: #F0FBFF;
padding: .8em 1em;
border-color: #D8EBF5 #D8EBF5 #B9DBEE #D8EBF5;
}
td {
border-color: #EFEFEF;
padding: .7em 1em;
}
/* end - table */
/* form elements */
form {
margin: 10px 20px;
padding: 15px 25px 25px 25px;
border: 1px solid #F0F0F0;
background: #F8F8F8;
}
form p {
border-bottom: 1px solid #E6E6E6;
padding: 12px 0 5px 0; margin: 0;
color: #666666;
}
label {
font-weight: bold;
color: #666666;
}
input, select, textarea {
margin: 5px 0;
padding: 5px;
color: #6A6969;
border-width: 1px;
border-style: solid;
border-color: #D4D4D4 #EBEBEB #EBEBEB #D4D4D4;
font: 11px 'Lucida Grande', Verdana, Helvetica, sans-serif;
}
input:focus, select:focus, textarea:focus {
color: #7BA857;
background: #EFFAE6;
}
#name, #email, #message, #website {
width: 380px;
}
input.button {
font: bold 12px Arial, Sans-serif;
height: 30px;
margin: 0;
padding: 2px 3px;
color: #FFF;
background:#B4DB6F;
border-width: 1px;
border-style: solid;
border-color: #B6DE8F #91BD37 #91BD37 #B6DE8F;
}
/* ------------------------------------------
LAYOUT
------------------------------------------- */
#wrap {
width: 920px;
margin: 0 auto;
text-align: left;
}
/* Header */
#header {
position: relative;
margin: 0 auto;
height: 245px;
}
#header h1#logo-text { margin: 0; padding: 0; }
#header h1#logo-text a {
position: absolute;
margin: 0; padding: 0 5px 0 0;
font: bold 62px 'Trebuchet MS', 'Helvetica Neue', Arial, Sans-Serif;
letter-spacing: -5px;
color: #1980AF;
text-decoration: none;
/* change the values of top and left to adjust the position of the logo*/
top: 30px; left: 30px;
}
#header h1#logo-text a:hover { border: none; }
#header p#slogan {
position: absolute;
margin: 0; padding: 0 5px 0 0;
font-family: Georgia, 'Times New Roman', Times, serif;;
font-weight: bold;
font-size: 13px;
line-height: 1.8em;
font-style: italic;
letter-spacing: -.3px;
color: #999;
/* change the values of top and left to adjust the position */
top: 102px; left: 32px;
}
#header #header-image {
position: absolute;
top: 12px; right: 30px;
width: 292px;
height: 234px;
background: url(../images/header-bg.png) no-repeat;
}
/* navigation */
#header #nav {
position: absolute;
left: 0px; bottom: 20px;
margin: 0; padding: 0 0 0 20px;
width: 900px;
border-bottom: 1px solid #F2F2F2;
/* z-index: 99999; */
}
#header #nav ul {
float: left;
list-style: none;
margin: 0;
padding: 0;
}
#header #nav ul li {
float: left;
margin: 0; padding: 0;
}
#header #nav ul li a:link,
#header #nav ul li a:visited {
float: left;
margin: 0;
padding: 5px 15px 10px 15px;
color: #666666;
font: bold 14px 'Trebuchet MS', Arial, Sans-Serif;
text-transform: uppercase;
border-right: 1px solid #EEE;
}
#header #nav ul li a:hover,
#header #nav ul li a:active {
border: none;
color: #000;
border-right: 1px solid #EEE;
}
#header #nav ul li#current a {
background: transparent url(../images/current.gif) repeat-x left bottom;
color: #222;
}
#header #nav ul li.first a:link,
#header #nav ul li.first a:visited {
border-left: 1px solid #F1F1F1;
}
/* Featured Block */
#featured {
clear: both;
background: #F8FAFD;
border: 1px solid #DCF1FB;
margin: 3px 0 15px 10px;
padding-bottom: 20px;
width: 900px;
}
#featured h2 {
font: normal 3.8em Georgia, 'Times New Roman', Times, Serif;
color: #295177;
letter-spacing: -2.0px;
margin-bottom: 0;
padding-bottom: 3px;
border-bottom: 1px solid #EBEBEB;
}
#featured h2 a {
color: #295177;
border: none;
}
#featured .image-block {
float: left;
width: 330px;
margin: 20px 0 0 25px;
padding: 10px 0 0 0;
display: inline;
border-right: 1px solid #DCF1FB;
}
#featured .image-block img {
background: #FFF;
border: 1px solid #DFEAF0;
padding: 12px;
}
#featured .text-block {
float: right;
width: 510px;
margin: 15px 25px 0 0;
display: inline;
}
#featured a.more-link {
background: #B4DB6F;
padding: 5px 10px 5px 10px;
margin-top: 15px;
color: #FFF;
text-decoration: none;
border: 1px solid #BADE7D;
text-transform: uppercase;
font-size: 10px;
font-weight: bold;
line-height: 20px;
display: block;
float: left;
}
#featured a.more-link:hover {
background: #008EFD;
border-color: #007DE2;
}
/* Content */
#content-outer {
clear: both;
float: left;
width: 920px;
margin: 0; padding: 0;
background: transparent url(../images/hor-line.gif) repeat-y center 0;
}
#content-wrap {
float: left;
width: 920px;
background: transparent url(../images/dotted-lines.gif) repeat-x;
}
#content {
float: left;
width: 900px;
margin-left: 10px;
display: inline;
padding-bottom: 40px;
}
/* columns */
#left {
width: 580px;
float: left;
padding-top: 15px;
}
#right {
width: 285px;
float: right;
padding-top: 5px;
}
#right h3 {
margin-left: 10px;
}
#left h2 {
font: normal 3.6em Georgia, 'Times New Roman', Times, Serif;
color: #444;
letter-spacing: -2.2px;
margin-bottom: 0px;
padding-bottom: 3px;
padding-left: 3px;
border-bottom: 1px solid #EBEBEB;
}
#left h2 a {
color: #444;
border: none;
}
#left .entry {
background: url(../images/dotted-lines.gif) repeat-x left bottom;
padding-bottom: 15px;
}
#left .entry h3 a {
color: #444;
border: none;
}
/* sidebar quick search */
#right form#quick-search {
padding: 0; margin: 10px 0 0 10px;
width: 270px; height: 33px;
background: #fff url(../images/header-search.gif) no-repeat;
border: none;
}
#right form#quick-search p {
margin: 0; padding: 0;
border: none;
}
#right form#quick-search input {
border: none;
background: transparent;
color: #BABABA;
margin: 0; padding: 5px;
font-size: .9em;
float: left;
}
#right form#quick-search .tbox {
margin: 6px 0 0 5px;
width: 220px;
display: inline;
}
#right form#quick-search .btn{
width: 24px; height: 24px;
margin: 5px 0 0 0; padding: 0;
}
#right form#quick-search label {
display: none;
}
/* sidemenus */
.sidemenu ul {
text-align: left;
margin: 10px 8px 8px 8px; padding: 0;
border-top: 1px solid #EBEBEB;
}
.sidemenu ul li {
list-style: none;
background: url(../images/dotted-lines.gif) repeat-x left bottom;
padding: 7px 5px;
margin: 0;
}
* html body .sidemenu ul li {
height: 1%;
}
.sidemenu ul li a,
.sidemenu ul li a:visited {
color: #5D95CA;
padding-left: 0;
font-weight: bold;
}
.sidemenu ul li a span {
color: #9F9F9F;
font-family: Georgia, 'Times New Roman', Times, Serif;
font-style: normal;
font-weight: normal;
font-size: .9em;
}
.sidemenu ul li a:hover { color: #000; border: none; }
.sidemenu ul ul { margin: 0 0 0 5px; padding: 0; }
.sidemenu ul ul li { background: none; }
/* footer */
#footer-outer {
clear: both;
float: left;
width: 920px;
background: url(../images/dotted-lines.gif) repeat-x;
font-size: .9em;
color: #777;
}
#footer-wrap {
float: left;
width: 900px;
margin-left: 10px;
display: inline;
}
#footer-wrap h3 {
font-size: 2.4em;
}
#footer-wrap .col-a {
width: 300px;
float: left;
}
#footer-wrap .col-b {
width: 295px;
float: right;
}
/* footer-list */
#footer-outer .footer-list ul {
border-top: 1px solid #E6E6E6;
list-style: none;
padding: 0;
margin-left: 20px;
}
#footer-outer .footer-list ul li {
background: url(../images/dotted-lines.gif) repeat-x left bottom;
}
#footer-outer .footer-list ul li a {
display: block;
width: 98%;
line-height: 2em;
padding: 5px 0;
margin-left: 0;
color: #77A6D3;
border: none;
}
#footer-outer .footer-list ul li a span {
font-style: italic;
font-weight: normal;
font-family: Georgia, 'Times New Roman', Times, Serif;
font-size: .95em;
}
#footer-outer .footer-list ul li a:hover,
#footer-outer .footer-list ul li a:hover span {
color: #333;
}
/* footer-bottom */
#footer-bottom {
float: left;
clear: both;
background: url(../images/dotted-lines.gif) repeat-x;
width: 920px;
margin: 30px auto 0 auto;
font-family: 'Trebuchet MS', 'Helvetica Neue', Arial, sans-serif;
font-size: .9em;
color: #777;
border-bottom: 50px solid #FFF;
}
#footer-bottom a:hover { border: none; }
#footer-bottom .bottom-left {
float: left;
padding-left: 5px;
}
#footer-bottom .bottom-right {
text-align: right;
padding-right: 0;
}
/* post */
.post {
margin-bottom: 15px;
background: url(../images/dotted-lines.gif) repeat-x left bottom;
padding-bottom: 15px;
}
.post .image-section {
clear: both;
display: block;
margin: 25px 0 10px 20px;
padding: 0;
}
.post .image-section img {
background: #FAFAFA;
border: 1px solid #ECECEC;
padding: 12px;
}
.post .postmeta {
padding: 5px 15px; margin: 20px 20px 15px 20px;
background: #f9fbfd;
border: 1px solid #eaf1f5;
}
.post .postmeta a { background: transparent; }
.post .postmeta a:hover { border: none; }
.post .postmeta a.comments { margin: 0 10px 0 5px; }
.post .postmeta a.readmore { margin: 0 10px 0 5px; }
.post .postmeta .date { margin: 0 10px 0 5px; }
.post .post-info,
#featured .post-info { font-size: .95em; margin-top: 0; color: #B0B0B0; }
.post .post-info a, .post .post-info a:visited,
#featured .post-info a, #featured .post-info a:visited { color: #8BB92E; border: none; }
.post .tags {
padding: 5px 15px; margin: 20px 20px 15px 20px;
border-top: 1px solid #eaf1f5;
border-bottom: 1px solid #eaf1f5;
}
/* comments list */
ol.commentlist {
margin: 12px 20px;
padding: 0;
border-style: solid;
border-color: #F0F0F0;
border-width: 1px 1px 0 1px;
}
.commentlist li {
margin: 0;
padding: 10px;
list-style: none;
border-bottom: 1px solid #F0F0F0;
}
.commentlist li cite {
display: block;
font-style: normal;
font-weight: bold;
padding: 7px;
}
.commentlist li cite img {
float: left;
margin-right: 10px;
}
.commentlist li cite .comment-data {
font-size: .8em;
font-weight: normal;
}
.commentlist li .comment-text {
clear: both;
margin: 0; padding: 5px 0 0 0;
}
.commentlist li.alt {
background: #F8F8F8;
}
/* archives */
ul.archive {
background: url(../images/dotted-lines.gif) repeat-x left top;
margin: 15px 20px 20px 20px;
padding: 0;
}
ul.archive li {
list-style: none;
background: url(../images/dotted-lines.gif) repeat-x left bottom;
margin: 0;
padding: 10px 5px;
}
ul.archive li .post-title {
margin: 0;
padding: 0;
font-size: 1.2em;
}
ul.archive li .post-title a {
color: #555;
}
ul.archive li .post-title a:hover {
border: none;
color: #222;
}
ul.archive li .post-details {
font-size: .9em;
margin-left: 0;
margin-top: 0;
}
ul.archive li .post-details a {
border: none;
}
/* pagenavigation */
.page-navigation {
margin: 10px 20px 10px 20px;
padding: 5px 15px;
background: #F9F9F9;
border: 1px solid #F0F0F0;
width: 510px;
}
.page-navigation a:hover {
border: none;
color: #333;
}
/* thumbnails */
p.thumbs {
padding: 10px 0 0 0px;
margin: 0 0 0 15px;
}
.thumbs img {
position: relative;
padding: 8px;
margin: 4px;
background: #FAFAFA;
border: 1px solid #EDEDED;
}
.thumbs img:hover {
border: 1px solid #D2D2D2;
}
.thumbs a:hover { background-color: transparent; border: none }
/* alignment classes & additional classes*/
.float-left { float: left; }
.float-right { float: right; }
.align-left { text-align: left; }
.align-right { text-align: right; }
.no-border { border: none; }
.no-bg { background: none; }
/* clearing */
.clearer { clear: both; }
.clear { display:inline-block; }
.clear:after {
display:block;
visibility:hidden;
clear:both;
height:0;
content: ".";
}
|
069ka-ambition-cms
|
trunk/bkp/Freshpick10/css/FreshPick.css
|
CSS
|
mit
| 14,759
|
/* http://meyerweb.com/eric/thoughts/2007/05/01/reset-reloaded/ */
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,dl, dt, dd, ol, ul, li, fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-weight: inherit;
font-style: inherit;
font-size: 100%;
font-family: inherit;
vertical-align: baseline;
}
/* remember to define focus styles! */
:focus {
outline: 0;
}
body {
line-height: 1;
color: black;
background: white;
}
ol, ul {
list-style: none;
}
/* tables still need 'cellspacing="0"' in the markup */
table {
border-collapse: separate;
border-spacing: 0;
}
caption, th, td {
text-align: left;
font-weight: normal;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: "";
}
blockquote, q {
quotes: "" "";
}
|
069ka-ambition-cms
|
trunk/bkp/Freshpick10/css/reset.css
|
CSS
|
mit
| 996
|
/* theme screen stylesheets */
/* import stylesheets and hide from ie/mac \*/
@import url("reset.css");
@import url("FreshPick.css");
/* end import/hide */
|
069ka-ambition-cms
|
trunk/bkp/Freshpick10/css/screen.css
|
CSS
|
mit
| 161
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Fresh Pick</title>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
<meta name="author" content="Erwin Aligam - styleshout.com" />
<meta name="description" content="Site Description Here" />
<meta name="keywords" content="keywords, here" />
<meta name="robots" content="index, follow, noarchive" />
<meta name="googlebot" content="noarchive" />
<link rel="stylesheet" type="text/css" media="screen" href="css/screen.css" />
</head>
<body>
<!-- wrap starts here -->
<div id="wrap">
<!--header -->
<div id="header">
<h1 id="logo-text"><a href="index.html" title="">Freshpick</a></h1>
<p id="slogan">Just Another Styleshout CSS Template... </p>
<div id="nav">
<ul>
<li class="first"><a href="index.html">Home</a></li>
<li id="current"><a href="style.html">Style Demo</a></li>
<li><a href="blog.html">Blog</a></li>
<li><a href="archives.html">Archives</a></li>
<li><a href="index.html">Support</a></li>
<li><a href="index.html">About</a></li>
</ul>
</div>
<div id="header-image"></div>
<!--header ends-->
</div>
<!-- content -->
<div id="content-outer" class="clear"><div id="content-wrap">
<div id="content">
<div id="left">
<div class="post">
<h2><a href="index.html">A Blog Post</a></h2>
<p class="post-info">Posted by <a href="index.html">erwin</a> | Filed under <a href="index.html">templates</a>, <a href="index.html">internet</a> </p>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac <a href="index.html">convallis aliquam</a>, lectus turpis varius lorem, eu
posuere nunc justo tempus leo.</p>
<p>
Donec mattis, purus nec placerat bibendum, <a href="index.html">dui pede condimentum</a>
odio, ac blandit ante orci ut diam. Cras fringilla magna. Phasellus suscipit, leo a pharetra
condimentum, lorem tellus eleifend magna, <a href="index.html">eget fringilla velit</a> magna id neque. Curabitur vel urna.
In tristique orci porttitor ipsum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo.</p>
<p class="postmeta">
<a href="index.html" class="readmore">Read more</a> |
<a href="index.html" class="comments">Comments (3)</a> |
<span class="date">April 20, 2009</span>
</p>
</div>
<h2><a href="index.html">Common XHTML Elements</a></h2>
<h3>Text and Image</h3>
<p><a href="http://getfirefox.com/"><img src="images/firefox-gray.jpg" width="100" height="120" alt="firefox" class="float-left" /></a>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam. Cras fringilla magna. Phasellus suscipit, leo a pharetra
condimentum, lorem tellus eleifend magna, eget fringilla velit magna id neque. Curabitur vel urna.
In tristique orci porttitor ipsum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo.
</p>
<p>
A <a href="style.html">link</a>,
<acronym title="this really isn't a very good description">acronym</acronym>,
<strong>strong text</strong> and
<del>deleted text</del>.
</p>
<h3>Code</h3>
<p><code>
code-sample { <br />
font-weight: bold;<br />
font-style: italic;<br />
}
</code></p>
<h3>Example Lists</h3>
<ol>
<li>Here is an example</li>
<li>of an ordered list</li>
</ol>
<ul>
<li>Here is an example</li>
<li>of an unordered list</li>
</ul>
<dl>
<dt>Definition title</dt>
<dd>Definition description</dd>
<dt>Definition title</dt>
<dd>Definition description</dd>
</dl>
<h3>Blockquote</h3>
<blockquote>
<p>You can have anything in the world you want if you'll just help
enough other people get what they want.</p>
<p class="align-right"> - Zig Ziglar</p>
</blockquote>
<h3>Headers</h3>
<h1>H1 Heading</h1>
<h2>H2 Heading</h2>
<h3>H3 Heading</h3>
<h4>H4 Heading</h4>
<h3>Tabular Data</h3>
<table>
<tr>
<th><strong>post date</strong></th>
<th>title</th>
<th>description</th>
</tr>
<tr>
<td>04.18.2009</td>
<td>Augue non nibh</td>
<td>Commodo <a href="index.html">metus</a> vestibulum hdhdh djdjdj djdjdj</td>
</tr>
<tr class="altrow">
<td>04.18.2009</td>
<td>Fusce ut diam</td>
<td>Purus in eget odio in sapien</td>
</tr>
<tr>
<td>04.18.2009</td>
<td>Augue non nibh</td>
<td>Adipiscing blandit </td>
</tr>
<tr class="altrow">
<td>04.18.2009</td>
<td>Sed vestibulum</td>
<td>Cras <a href="index.html">lobortis</a> commodo </td>
</tr>
</table>
<h3>Contact Form</h3>
<form action="index.html" method="get" id="contactform">
<p>Send me a message</p>
<p>
<label for="subject">Subject</label><br />
<select id="subject" name="subject" tabindex="1">
<option value="1">Option One</option>
<option value="2">Option Two</option>
<option value="3">Option Three</option>
</select>
</p>
<p>
<label for="name">Your Name</label><br />
<input id="name" name="name" value="Your Name" type="text" tabindex="2" />
</p>
<p>
<label for="email">Your Email Address</label><br />
<input id="email" name="email" value="Your Email" type="text" tabindex="3" />
</p>
<p>
<label for="message">Your Message</label><br />
<textarea id="message" name="message" rows="10" cols="20" tabindex="4"></textarea>
</p>
<p class="no-border">
<input class="button" type="submit" value="Submit" tabindex="5" />
<input class="button" type="reset" value="Reset" tabindex="6" />
</p>
</form>
</div>
<div id="right">
<div class="sidemenu">
<h3>Sidebar Menu</h3>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="index.html#TemplateInfo">TemplateInfo</a></li>
<li><a href="style.html">Style Demo</a></li>
<li><a href="blog.html">Blog</a></li>
<li><a href="archives.html">Archives</a></li>
<li><a href="http://www.dreamtemplate.com" title="Web Templates">Web Templates</a></li>
</ul>
</div>
<div class="sidemenu">
<h3>Sponsors</h3>
<ul>
<li><a href="http://www.dreamtemplate.com" title="Website Templates">DreamTemplate <br />
<span>Over 6,000+ Premium Web Templates</span></a>
</li>
<li><a href="http://www.themelayouts.com" title="WordPress Themes">ThemeLayouts <br />
<span>Premium WordPress & Joomla Themes</span></a>
</li>
<li><a href="http://www.imhosted.com" title="Website Hosting">ImHosted.com <br />
<span>Affordable Web Hosting Provider</span></a>
</li>
<li><a href="http://www.dreamstock.com" title="Stock Photos">DreamStock <br />
<span>Download Amazing Stock Photos</span></a>
</li>
<li><a href="http://www.evrsoft.com" title="Website Builder">Evrsoft <br />
<span>Website Builder Software & Tools</span></a>
</li>
<li><a href="http://www.webhostingwp.com" title="Web Hosting">Web Hosting <br />
<span>Top 10 Hosting Reviews</span></a>
</li>
</ul>
</div>
<h3>Search</h3>
<form id="quick-search" action="index.html" method="get" >
<p>
<label for="qsearch">Search:</label>
<input class="tbox" id="qsearch" type="text" name="qsearch" value="type and hit enter..." title="Start typing and hit ENTER" />
<input class="btn" alt="Search" type="image" name="searchsubmit" title="Search" src="images/search.gif" />
</p>
</form>
</div>
</div>
<!-- content end -->
</div></div>
<!-- footer starts here -->
<div id="footer-outer" class="clear"><div id="footer-wrap">
<div class="col-a">
<h3>Image Gallery </h3>
<p class="thumbs">
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
</p>
<h3>Lorem ipsum dolor</h3>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam. Cras fringilla magna.
</p>
</div>
<div class="col-a">
<h3>Lorem Ipsum</h3>
<p>
<strong>Lorem ipsum dolor</strong> <br />
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam.</p>
<div class="footer-list">
<ul>
<li><a href="index.html">consequat molestie</a></li>
<li><a href="index.html">sem justo</a></li>
<li><a href="index.html">semper</a></li>
<li><a href="index.html">magna sed purus</a></li>
<li><a href="index.html">tincidunt</a></li>
<li><a href="index.html">consequat molestie</a></li>
<li><a href="index.html">magna sed purus</a></li>
</ul>
</div>
</div>
<div class="col-b">
<h3>About</h3>
<p>
<a href="index.html"><img src="images/gravatar.jpg" width="40" height="40" alt="firefox" class="float-left" /></a>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam.</p>
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. <a href="index.html">Learn more...</a></p>
</div>
<!-- footer ends -->
</div></div>
<!-- footer-bottom starts -->
<div id="footer-bottom">
<div class="bottom-left">
<p>
© 2010 <strong>Your Copyright Info Here</strong>
<a href="http://www.bluewebtemplates.com/" title="Website Templates">website templates</a> by <a href="http://www.styleshout.com/">styleshout</a>
</p>
</div>
<div class="bottom-right">
<p>
<a href="http://jigsaw.w3.org/css-validator/check/referer">CSS</a> |
<a href="http://validator.w3.org/check/referer">XHTML</a> |
<a href="index.html">Home</a> |
<a href="index.html">Sitemap</a> |
<a href="index.html">RSS Feed</a>
</p>
</div>
<!-- footer-bottom ends -->
</div>
<!-- wrap ends here -->
</div>
</body>
</html>
|
069ka-ambition-cms
|
trunk/bkp/Freshpick10/style.html
|
HTML
|
mit
| 13,204
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Welcome to PV Gallery</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">PV Gallery</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">Users</a></li>
<li><a href="#contact">Photos</a></li>
<li><a href="#contact">Videos</a></li>
<li><a href="#contact">Feedback</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>Welcome to PV Gallery</h1>
<p>Use this document as a way to quick start any new project.<br> All you get is this message and a barebones HTML document.</p>
<h3>Latest Users</h3>
<a href="user_add.html">+ Add New User</a>
<br/><br/>
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
<td><a href="">View</a> | <a href="">Edit</a> | <a href="">Delete</a></td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
<td><a href="">View</a> | <a href="">Edit</a> | <a href="">Delete</a></td>
</tr>
<tr>
<td>3</td>
<td>Larry the Bird</td>
<td>@twitter</td>
<td>@twitter</td>
<td><a href="">View</a> | <a href="">Edit</a> | <a href="">Delete</a></td>
</tr>
</tbody>
</table>
<h3>Add New Users</h3>
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="first_name">First Name</label>
<div class="controls">
<input type="text" id="first_name" name="first_name" placeholder="first name">
</div>
</div>
<div class="control-group">
<label class="control-label" for="last_name">Last Name</label>
<div class="controls">
<input type="text" id="last_name" name="last_name" placeholder="last name">
</div>
</div>
<div class="control-group">
<label class="control-label" for="username">Username</label>
<div class="controls">
<input type="text" id="username" name="username" placeholder="username">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn">Add User</button>
</div>
</div>
</form>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/bkp/users.php
|
Hack
|
mit
| 5,535
|
<script>window.location.href='http://google.com'</script>
|
069ka-ambition-cms
|
trunk/simple.html
|
HTML
|
mit
| 59
|
/* ----------------------------------------------
Template Name : FreshPick
Template Code : S-0029
Version : 1.0
Author : Erwin Aligam
Author URI : http://www.styleshout.com/
Last Date Modified : April 24, 2009
------------------------------------------------ */
/* ----------------------------------------------
HTML ELEMENTS
------------------------------------------------- */
body {
font: 12px/170% 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, Sans-Serif;
color: #666666;
margin: 0;
padding: 0;
background: #FFF url(../images/bg.gif) repeat-x;
text-align: center;
}
/* Links */
a:link, a:visited {
text-decoration: none;
color: #0788C3;
}
a:hover {
border-bottom: 1px dotted #0788C3;
}
a:link.more-link, a:visited.more-link {
padding-bottom: 2px;
font-weight: bold;
color: #0788C3;
border-bottom: 1px dotted #0788C3;
}
a:hover.more-link {
text-decoration: none;
}
/* Headers */
h1, h2, h3, h4 {
font: bold 1em/1.5em Georgia, 'Times New Roman', Times, serif;
color: #555;
margin: 10px 20px 7px 20px;
}
h1 { font-size: 3.7em; font-weight: normal; letter-spacing: -2px; }
h2 { font-size: 2.8em; font-weight: normal; }
h3 { font-size: 2.2em; font-weight: normal; letter-spacing: -0.5px; padding-top: 15px; }
h4 { font-size: 1.4em; }
/* Lists */
ul, ol {
margin: 10px 20px;
padding: 0 20px;
}
ul { list-style: disc; }
ol { list-style: decimal; }
dt {
font-weight: bold;
color: #1980AF;
}
dd {
padding-left: 20px;
}
p, dl { margin: 10px 20px; }
/* Images */
img {
background: #FAFAFA;
border: 1px solid #E4E4E4;
padding: 8px;
}
img.float-right {
margin: 5px 0px 10px 10px;
}
img.float-left {
margin: 5px 10px 10px 0px;
}
code {
margin: 3px 0;
padding: 15px;
text-align: left;
display: block;
overflow: auto;
font: 500 1em/1.5em 'Lucida Console', 'Courier New', Monospace;
/* white-space: pre; */
border: 1px solid #F0F0F0;
background: #F8F8F8;
}
acronym {
cursor: help;
border-bottom: 1px dotted #555;
}
blockquote {
margin: 10px 20px;
padding: 10px 10px 10px 32px;
border: 1px solid #F0F0F0;
background: #f8f8f8 url(../images/quote.gif) no-repeat 12px 12px;
font-weight: normal;
font-size: 17px;
line-height: 1.5em;
font-style: italic;
font-family: Georgia, 'Times New Roman', Times, Serif;
color: #555;
}
strong {
font-weight: bold;
}
/* start - table */
table {
border-collapse: collapse;
margin: 10px 20px;
}
tr { background: #FFF; }
tr.altrow { background: #F9F9F9; }
th, td {
text-align: left;
border-width: 1px;
border-style: solid;
}
th {
color: #555;
background: #F0FBFF;
padding: .8em 1em;
border-color: #D8EBF5 #D8EBF5 #B9DBEE #D8EBF5;
}
td {
border-color: #EFEFEF;
padding: .7em 1em;
}
/* end - table */
/* form elements */
form {
margin: 10px 20px;
padding: 15px 25px 25px 25px;
border: 1px solid #F0F0F0;
background: #F8F8F8;
}
form p {
border-bottom: 1px solid #E6E6E6;
padding: 12px 0 5px 0; margin: 0;
color: #666666;
}
label {
font-weight: bold;
color: #666666;
}
input, select, textarea {
margin: 5px 0;
padding: 5px;
color: #6A6969;
border-width: 1px;
border-style: solid;
border-color: #D4D4D4 #EBEBEB #EBEBEB #D4D4D4;
font: 11px 'Lucida Grande', Verdana, Helvetica, sans-serif;
}
input:focus, select:focus, textarea:focus {
color: #7BA857;
background: #EFFAE6;
}
#name, #email, #message, #website {
width: 380px;
}
input.button {
font: bold 12px Arial, Sans-serif;
height: 30px;
margin: 0;
padding: 2px 3px;
color: #FFF;
background:#B4DB6F;
border-width: 1px;
border-style: solid;
border-color: #B6DE8F #91BD37 #91BD37 #B6DE8F;
}
/* ------------------------------------------
LAYOUT
------------------------------------------- */
#wrap {
width: 920px;
margin: 0 auto;
text-align: left;
}
/* Header */
#header {
position: relative;
margin: 0 auto;
height: 245px;
}
#header h1#logo-text { margin: 0; padding: 0; }
#header h1#logo-text a {
position: absolute;
margin: 0; padding: 0 5px 0 0;
font: bold 62px 'Trebuchet MS', 'Helvetica Neue', Arial, Sans-Serif;
letter-spacing: -5px;
color: #1980AF;
text-decoration: none;
/* change the values of top and left to adjust the position of the logo*/
top: 30px; left: 30px;
}
#header h1#logo-text a:hover { border: none; }
#header p#slogan {
position: absolute;
margin: 0; padding: 0 5px 0 0;
font-family: Georgia, 'Times New Roman', Times, serif;;
font-weight: bold;
font-size: 13px;
line-height: 1.8em;
font-style: italic;
letter-spacing: -.3px;
color: #999;
/* change the values of top and left to adjust the position */
top: 102px; left: 32px;
}
#header #header-image {
position: absolute;
top: 12px; right: 30px;
width: 292px;
height: 234px;
/*background: url(../images/header-bg.png) no-repeat; */
}
/* navigation */
#header #nav {
position: absolute;
left: 0px; bottom: 20px;
margin: 0; padding: 0 0 0 20px;
width: 900px;
border-bottom: 1px solid #F2F2F2;
/* z-index: 99999; */
}
#header #nav ul {
float: left;
list-style: none;
margin: 0;
padding: 0;
}
#header #nav ul li {
float: left;
margin: 0; padding: 0;
}
#header #nav ul li a:link,
#header #nav ul li a:visited {
float: left;
margin: 0;
padding: 5px 15px 10px 15px;
color: #666666;
font: bold 14px 'Trebuchet MS', Arial, Sans-Serif;
text-transform: uppercase;
border-right: 1px solid #EEE;
}
#header #nav ul li a:hover,
#header #nav ul li a:active {
border: none;
color: #000;
border-right: 1px solid #EEE;
}
#header #nav ul li#current a {
background: transparent url(../images/current.gif) repeat-x left bottom;
color: #222;
}
#header #nav ul li.first a:link,
#header #nav ul li.first a:visited {
border-left: 1px solid #F1F1F1;
}
/* Featured Block */
#featured {
clear: both;
background: #F8FAFD;
border: 1px solid #DCF1FB;
margin: 3px 0 15px 10px;
padding-bottom: 20px;
width: 900px;
}
#featured h2 {
font: normal 3.8em Georgia, 'Times New Roman', Times, Serif;
color: #295177;
letter-spacing: -2.0px;
margin-bottom: 0;
padding-bottom: 3px;
border-bottom: 1px solid #EBEBEB;
}
#featured h2 a {
color: #295177;
border: none;
}
#featured .image-block {
float: left;
width: 330px;
margin: 20px 0 0 25px;
padding: 10px 0 0 0;
display: inline;
border-right: 1px solid #DCF1FB;
}
#featured .image-block img {
background: #FFF;
border: 1px solid #DFEAF0;
padding: 12px;
}
#featured .text-block {
float: right;
width: 510px;
margin: 15px 25px 0 0;
display: inline;
}
#featured a.more-link {
background: #B4DB6F;
padding: 5px 10px 5px 10px;
margin-top: 15px;
color: #FFF;
text-decoration: none;
border: 1px solid #BADE7D;
text-transform: uppercase;
font-size: 10px;
font-weight: bold;
line-height: 20px;
display: block;
float: left;
}
#featured a.more-link:hover {
background: #008EFD;
border-color: #007DE2;
}
/* Content */
#content-outer {
clear: both;
float: left;
width: 920px;
margin: 0; padding: 0;
background: transparent url(../images/hor-line.gif) repeat-y center 0;
}
#content-wrap {
float: left;
width: 920px;
background: transparent url(../images/dotted-lines.gif) repeat-x;
}
#content {
float: left;
width: 900px;
margin-left: 10px;
display: inline;
padding-bottom: 40px;
}
/* columns */
#left {
width: 580px;
float: left;
padding-top: 15px;
}
#right {
width: 285px;
float: right;
padding-top: 5px;
}
#right h3 {
margin-left: 10px;
}
#left h2 {
font: normal 3.6em Georgia, 'Times New Roman', Times, Serif;
color: #444;
letter-spacing: -2.2px;
margin-bottom: 0px;
padding-bottom: 3px;
padding-left: 3px;
border-bottom: 1px solid #EBEBEB;
}
#left h2 a {
color: #444;
border: none;
}
#left .entry {
background: url(../images/dotted-lines.gif) repeat-x left bottom;
padding-bottom: 15px;
}
#left .entry h3 a {
color: #444;
border: none;
}
/* sidebar quick search */
#right form#quick-search {
padding: 0; margin: 10px 0 0 10px;
width: 270px; height: 33px;
background: #fff url(../images/header-search.gif) no-repeat;
border: none;
}
#right form#quick-search p {
margin: 0; padding: 0;
border: none;
}
#right form#quick-search input {
border: none;
background: transparent;
color: #BABABA;
margin: 0; padding: 5px;
font-size: .9em;
float: left;
}
#right form#quick-search .tbox {
margin: 6px 0 0 5px;
width: 220px;
display: inline;
}
#right form#quick-search .btn{
width: 24px; height: 24px;
margin: 5px 0 0 0; padding: 0;
}
#right form#quick-search label {
display: none;
}
/* sidemenus */
.sidemenu ul {
text-align: left;
margin: 10px 8px 8px 8px; padding: 0;
border-top: 1px solid #EBEBEB;
}
.sidemenu ul li {
list-style: none;
background: url(../images/dotted-lines.gif) repeat-x left bottom;
padding: 7px 5px;
margin: 0;
}
* html body .sidemenu ul li {
height: 1%;
}
.sidemenu ul li a,
.sidemenu ul li a:visited {
color: #5D95CA;
padding-left: 0;
font-weight: bold;
}
.sidemenu ul li a span {
color: #9F9F9F;
font-family: Georgia, 'Times New Roman', Times, Serif;
font-style: normal;
font-weight: normal;
font-size: .9em;
}
.sidemenu ul li a:hover { color: #000; border: none; }
.sidemenu ul ul { margin: 0 0 0 5px; padding: 0; }
.sidemenu ul ul li { background: none; }
/* footer */
#footer-outer {
clear: both;
float: left;
width: 920px;
background: url(../images/dotted-lines.gif) repeat-x;
font-size: .9em;
color: #777;
}
#footer-wrap {
float: left;
width: 900px;
margin-left: 10px;
display: inline;
}
#footer-wrap h3 {
font-size: 2.4em;
}
#footer-wrap .col-a {
width: 300px;
float: left;
}
#footer-wrap .col-b {
width: 295px;
float: right;
}
/* footer-list */
#footer-outer .footer-list ul {
border-top: 1px solid #E6E6E6;
list-style: none;
padding: 0;
margin-left: 20px;
}
#footer-outer .footer-list ul li {
background: url(../images/dotted-lines.gif) repeat-x left bottom;
}
#footer-outer .footer-list ul li a {
display: block;
width: 98%;
line-height: 2em;
padding: 5px 0;
margin-left: 0;
color: #77A6D3;
border: none;
}
#footer-outer .footer-list ul li a span {
font-style: italic;
font-weight: normal;
font-family: Georgia, 'Times New Roman', Times, Serif;
font-size: .95em;
}
#footer-outer .footer-list ul li a:hover,
#footer-outer .footer-list ul li a:hover span {
color: #333;
}
/* footer-bottom */
#footer-bottom {
float: left;
clear: both;
background: url(../images/dotted-lines.gif) repeat-x;
width: 920px;
margin: 30px auto 0 auto;
font-family: 'Trebuchet MS', 'Helvetica Neue', Arial, sans-serif;
font-size: .9em;
color: #777;
border-bottom: 50px solid #FFF;
}
#footer-bottom a:hover { border: none; }
#footer-bottom .bottom-left {
float: left;
padding-left: 5px;
}
#footer-bottom .bottom-right {
text-align: right;
padding-right: 0;
}
/* post */
.post {
margin-bottom: 15px;
background: url(../images/dotted-lines.gif) repeat-x left bottom;
padding-bottom: 15px;
}
.post .image-section {
clear: both;
display: block;
margin: 25px 0 10px 20px;
padding: 0;
}
.post .image-section img {
background: #FAFAFA;
border: 1px solid #ECECEC;
padding: 12px;
}
.post .postmeta {
padding: 5px 15px; margin: 20px 20px 15px 20px;
background: #f9fbfd;
border: 1px solid #eaf1f5;
}
.post .postmeta a { background: transparent; }
.post .postmeta a:hover { border: none; }
.post .postmeta a.comments { margin: 0 10px 0 5px; }
.post .postmeta a.readmore { margin: 0 10px 0 5px; }
.post .postmeta .date { margin: 0 10px 0 5px; }
.post .post-info,
#featured .post-info { font-size: .95em; margin-top: 0; color: #B0B0B0; }
.post .post-info a, .post .post-info a:visited,
#featured .post-info a, #featured .post-info a:visited { color: #8BB92E; border: none; }
.post .tags {
padding: 5px 15px; margin: 20px 20px 15px 20px;
border-top: 1px solid #eaf1f5;
border-bottom: 1px solid #eaf1f5;
}
/* comments list */
ol.commentlist {
margin: 12px 20px;
padding: 0;
border-style: solid;
border-color: #F0F0F0;
border-width: 1px 1px 0 1px;
}
.commentlist li {
margin: 0;
padding: 10px;
list-style: none;
border-bottom: 1px solid #F0F0F0;
}
.commentlist li cite {
display: block;
font-style: normal;
font-weight: bold;
padding: 7px;
}
.commentlist li cite img {
float: left;
margin-right: 10px;
}
.commentlist li cite .comment-data {
font-size: .8em;
font-weight: normal;
}
.commentlist li .comment-text {
clear: both;
margin: 0; padding: 5px 0 0 0;
}
.commentlist li.alt {
background: #F8F8F8;
}
/* archives */
ul.archive {
background: url(../images/dotted-lines.gif) repeat-x left top;
margin: 15px 20px 20px 20px;
padding: 0;
}
ul.archive li {
list-style: none;
background: url(../images/dotted-lines.gif) repeat-x left bottom;
margin: 0;
padding: 10px 5px;
}
ul.archive li .post-title {
margin: 0;
padding: 0;
font-size: 1.2em;
}
ul.archive li .post-title a {
color: #555;
}
ul.archive li .post-title a:hover {
border: none;
color: #222;
}
ul.archive li .post-details {
font-size: .9em;
margin-left: 0;
margin-top: 0;
}
ul.archive li .post-details a {
border: none;
}
/* pagenavigation */
.page-navigation {
margin: 10px 20px 10px 20px;
padding: 5px 15px;
background: #F9F9F9;
border: 1px solid #F0F0F0;
width: 510px;
}
.page-navigation a:hover {
border: none;
color: #333;
}
/* thumbnails */
p.thumbs {
padding: 10px 0 0 0px;
margin: 0 0 0 15px;
}
.thumbs img {
position: relative;
padding: 8px;
margin: 4px;
background: #FAFAFA;
border: 1px solid #EDEDED;
}
.thumbs img:hover {
border: 1px solid #D2D2D2;
}
.thumbs a:hover { background-color: transparent; border: none }
/* alignment classes & additional classes*/
.float-left { float: left; }
.float-right { float: right; }
.align-left { text-align: left; }
.align-right { text-align: right; }
.no-border { border: none; }
.no-bg { background: none; }
/* clearing */
.clearer { clear: both; }
.clear { display:inline-block; }
.clear:after {
display:block;
visibility:hidden;
clear:both;
height:0;
content: ".";
}
|
069ka-ambition-cms
|
trunk/css/FreshPick.css
|
CSS
|
mit
| 14,763
|
/* http://meyerweb.com/eric/thoughts/2007/05/01/reset-reloaded/ */
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,dl, dt, dd, ol, ul, li, fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-weight: inherit;
font-style: inherit;
font-size: 100%;
font-family: inherit;
vertical-align: baseline;
}
/* remember to define focus styles! */
:focus {
outline: 0;
}
body {
line-height: 1;
color: black;
background: white;
}
ol, ul {
list-style: none;
}
/* tables still need 'cellspacing="0"' in the markup */
table {
border-collapse: separate;
border-spacing: 0;
}
caption, th, td {
text-align: left;
font-weight: normal;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: "";
}
blockquote, q {
quotes: "" "";
}
|
069ka-ambition-cms
|
trunk/css/reset.css
|
CSS
|
mit
| 996
|
/* theme screen stylesheets */
/* import stylesheets and hide from ie/mac \*/
@import url("reset.css");
@import url("FreshPick.css");
/* end import/hide */
|
069ka-ambition-cms
|
trunk/css/screen.css
|
CSS
|
mit
| 161
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Fresh Pick Template</title>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
<meta name="author" content="Erwin Aligam - styleshout.com" />
<meta name="description" content="Site Description Here" />
<meta name="keywords" content="keywords, here" />
<meta name="robots" content="index, follow, noarchive" />
<meta name="googlebot" content="noarchive" />
<link rel="stylesheet" type="text/css" media="screen" href="css/screen.css" />
</head>
<body>
<!-- wrap starts here -->
<div id="wrap">
<!--header -->
<div id="header">
<h1 id="logo-text"><a href="index.html" title="">Freshpick</a></h1>
<p id="slogan">Just Another Styleshout CSS Template... </p>
<div id="nav">
<ul>
<li class="first"><a href="index.html">Home</a></li>
<li id="current"><a href="style.html">Style Demo</a></li>
<li><a href="blog.html">Blog</a></li>
<li><a href="archives.html">Archives</a></li>
<li><a href="index.html">Support</a></li>
<li><a href="index.html">About</a></li>
</ul>
</div>
<div id="header-image"></div>
<!--header ends-->
</div>
<!-- content -->
<div id="content-outer" class="clear"><div id="content-wrap">
<div id="content">
<div id="left">
<div class="post">
<h2><a href="index.html">A Blog Post</a></h2>
<p class="post-info">Posted by <a href="index.html">erwin</a> | Filed under <a href="index.html">templates</a>, <a href="index.html">internet</a> </p>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac <a href="index.html">convallis aliquam</a>, lectus turpis varius lorem, eu
posuere nunc justo tempus leo.</p>
<p>
Donec mattis, purus nec placerat bibendum, <a href="index.html">dui pede condimentum</a>
odio, ac blandit ante orci ut diam. Cras fringilla magna. Phasellus suscipit, leo a pharetra
condimentum, lorem tellus eleifend magna, <a href="index.html">eget fringilla velit</a> magna id neque. Curabitur vel urna.
In tristique orci porttitor ipsum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo.</p>
<p class="postmeta">
<a href="index.html" class="readmore">Read more</a> |
<a href="index.html" class="comments">Comments (3)</a> |
<span class="date">April 20, 2009</span>
</p>
</div>
<h2><a href="index.html">Common XHTML Elements</a></h2>
<h3>Text and Image</h3>
<p><a href="http://getfirefox.com/"><img src="images/firefox-gray.jpg" width="100" height="120" alt="firefox" class="float-left" /></a>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam. Cras fringilla magna. Phasellus suscipit, leo a pharetra
condimentum, lorem tellus eleifend magna, eget fringilla velit magna id neque. Curabitur vel urna.
In tristique orci porttitor ipsum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo.
</p>
<p>
A <a href="style.html">link</a>,
<acronym title="this really isn't a very good description">acronym</acronym>,
<strong>strong text</strong> and
<del>deleted text</del>.
</p>
<h3>Code</h3>
<p><code>
code-sample { <br />
font-weight: bold;<br />
font-style: italic;<br />
}
</code></p>
<h3>Example Lists</h3>
<ol>
<li>Here is an example</li>
<li>of an ordered list</li>
</ol>
<ul>
<li>Here is an example</li>
<li>of an unordered list</li>
</ul>
<dl>
<dt>Definition title</dt>
<dd>Definition description</dd>
<dt>Definition title</dt>
<dd>Definition description</dd>
</dl>
<h3>Blockquote</h3>
<blockquote>
<p>You can have anything in the world you want if you'll just help
enough other people get what they want.</p>
<p class="align-right"> - Zig Ziglar</p>
</blockquote>
<h3>Headers</h3>
<h1>H1 Heading</h1>
<h2>H2 Heading</h2>
<h3>H3 Heading</h3>
<h4>H4 Heading</h4>
<h3>Tabular Data</h3>
<table>
<tr>
<th><strong>post date</strong></th>
<th>title</th>
<th>description</th>
</tr>
<tr>
<td>04.18.2009</td>
<td>Augue non nibh</td>
<td>Commodo <a href="index.html">metus</a> vestibulum hdhdh djdjdj djdjdj</td>
</tr>
<tr class="altrow">
<td>04.18.2009</td>
<td>Fusce ut diam</td>
<td>Purus in eget odio in sapien</td>
</tr>
<tr>
<td>04.18.2009</td>
<td>Augue non nibh</td>
<td>Adipiscing blandit </td>
</tr>
<tr class="altrow">
<td>04.18.2009</td>
<td>Sed vestibulum</td>
<td>Cras <a href="index.html">lobortis</a> commodo </td>
</tr>
</table>
<h3>Contact Form</h3>
<form action="index.html" method="get" id="contactform">
<p>Send me a message</p>
<p>
<label for="subject">Subject</label><br />
<select id="subject" name="subject" tabindex="1">
<option value="1">Option One</option>
<option value="2">Option Two</option>
<option value="3">Option Three</option>
</select>
</p>
<p>
<label for="name">Your Name</label><br />
<input id="name" name="name" value="Your Name" type="text" tabindex="2" />
</p>
<p>
<label for="email">Your Email Address</label><br />
<input id="email" name="email" value="Your Email" type="text" tabindex="3" />
</p>
<p>
<label for="message">Your Message</label><br />
<textarea id="message" name="message" rows="10" cols="20" tabindex="4"></textarea>
</p>
<p class="no-border">
<input class="button" type="submit" value="Submit" tabindex="5" />
<input class="button" type="reset" value="Reset" tabindex="6" />
</p>
</form>
</div>
<div id="right">
<div class="sidemenu">
<h3>Sidebar Menu</h3>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="index.html#TemplateInfo">TemplateInfo</a></li>
<li><a href="style.html">Style Demo</a></li>
<li><a href="blog.html">Blog</a></li>
<li><a href="archives.html">Archives</a></li>
<li><a href="http://www.dreamtemplate.com" title="Web Templates">Web Templates</a></li>
</ul>
</div>
<div class="sidemenu">
<h3>Sponsors</h3>
<ul>
<li><a href="http://www.dreamtemplate.com" title="Website Templates">DreamTemplate <br />
<span>Over 6,000+ Premium Web Templates</span></a>
</li>
<li><a href="http://www.themelayouts.com" title="WordPress Themes">ThemeLayouts <br />
<span>Premium WordPress & Joomla Themes</span></a>
</li>
<li><a href="http://www.imhosted.com" title="Website Hosting">ImHosted.com <br />
<span>Affordable Web Hosting Provider</span></a>
</li>
<li><a href="http://www.dreamstock.com" title="Stock Photos">DreamStock <br />
<span>Download Amazing Stock Photos</span></a>
</li>
<li><a href="http://www.evrsoft.com" title="Website Builder">Evrsoft <br />
<span>Website Builder Software & Tools</span></a>
</li>
<li><a href="http://www.webhostingwp.com" title="Web Hosting">Web Hosting <br />
<span>Top 10 Hosting Reviews</span></a>
</li>
</ul>
</div>
<h3>Search</h3>
<form id="quick-search" action="index.html" method="get" >
<p>
<label for="qsearch">Search:</label>
<input class="tbox" id="qsearch" type="text" name="qsearch" value="type and hit enter..." title="Start typing and hit ENTER" />
<input class="btn" alt="Search" type="image" name="searchsubmit" title="Search" src="images/search.gif" />
</p>
</form>
</div>
</div>
<!-- content end -->
</div></div>
<!-- footer starts here -->
<div id="footer-outer" class="clear"><div id="footer-wrap">
<div class="col-a">
<h3>Image Gallery </h3>
<p class="thumbs">
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
</p>
<h3>Lorem ipsum dolor</h3>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam. Cras fringilla magna.
</p>
</div>
<div class="col-a">
<h3>Lorem Ipsum</h3>
<p>
<strong>Lorem ipsum dolor</strong> <br />
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam.</p>
<div class="footer-list">
<ul>
<li><a href="index.html">consequat molestie</a></li>
<li><a href="index.html">sem justo</a></li>
<li><a href="index.html">semper</a></li>
<li><a href="index.html">magna sed purus</a></li>
<li><a href="index.html">tincidunt</a></li>
<li><a href="index.html">consequat molestie</a></li>
<li><a href="index.html">magna sed purus</a></li>
</ul>
</div>
</div>
<div class="col-b">
<h3>About</h3>
<p>
<a href="index.html"><img src="images/gravatar.jpg" width="40" height="40" alt="firefox" class="float-left" /></a>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam.</p>
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. <a href="index.html">Learn more...</a></p>
</div>
<!-- footer ends -->
</div></div>
<!-- footer-bottom starts -->
<div id="footer-bottom">
<div class="bottom-left">
<p>
© 2010 <strong>Your Copyright Info Here</strong>
<a href="http://www.bluewebtemplates.com/" title="Website Templates">website templates</a> by <a href="http://www.styleshout.com/">styleshout</a>
</p>
</div>
<div class="bottom-right">
<p>
<a href="http://jigsaw.w3.org/css-validator/check/referer">CSS</a> |
<a href="http://validator.w3.org/check/referer">XHTML</a> |
<a href="index.html">Home</a> |
<a href="index.html">Sitemap</a> |
<a href="index.html">RSS Feed</a>
</p>
</div>
<!-- footer-bottom ends -->
</div>
<!-- wrap ends here -->
</div>
</body>
</html>
|
069ka-ambition-cms
|
trunk/style.html
|
HTML
|
mit
| 13,213
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using _1191021127.QuanLyGiaoVien.UI.Common;
namespace _1191021127.QuanLyGiaoVien.UI
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Main());
}
}
}
|
1191021127qlgv
|
trunk/1191021127.QuanLyGiaoVien/1191021127.QuanLyGiaoVien.UI/Program.cs
|
C#
|
asf20
| 565
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Data.Linq;
using System.Text;
using System.Windows.Forms;
using _1191021127.QuanLyGiaoVien.Domain;
namespace _1191021127.QuanLyGiaoVien.UI.Common
{
public partial class DangNhap : Form
{
string tenDangNhap = "";
string matkhau = "";
public DangNhap()
{
InitializeComponent();
}
private void DangNhap_Load(object sender, EventArgs e)
{
}
private void btDangNhap_Click(object sender, EventArgs e)
{
if (tbTenDangNhap.Text != null && tbTenDangNhap.Text != "")
{
if (tbMatKhau.Text != null && tbMatKhau.Text != "")
{
DBStoreDataContext db = new DBStoreDataContext();
User user = db.Users.Where(x => x.TenDangNhap == tbTenDangNhap.Text && x.MatKhau == tbMatKhau.Text).FirstOrDefault();
if (user == null)
{
MessageBox.Show("Sai tên hoặc mật khẩu,", "Đăng nhập - Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else {
tenDangNhap = tbTenDangNhap.Text;
matkhau = tbMatKhau.Text;
this.Close();
}
}
else
MessageBox.Show("Sai mật khẩu,", "Đăng nhập - Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
MessageBox.Show("Sai tên đăng nhập,", "Đăng nhập - Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
|
1191021127qlgv
|
trunk/1191021127.QuanLyGiaoVien/1191021127.QuanLyGiaoVien.UI/Form/DangNhap.cs
|
C#
|
asf20
| 1,997
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Data.Linq;
using _1191021127.QuanLyGiaoVien.Domain;
using _1191021127.QuanLyGiaoVien.Domain.Entities;
namespace _1191021127.QuanLyGiaoVien.UI
{
public partial class ChonPhanCongGiaoVien : Form
{
public ChonPhanCongGiaoVien()
{
InitializeComponent();
}
DBStoreDataContext db = new DBStoreDataContext();
private void ChonPhanCongGiaoVien_Load(object sender, EventArgs e)
{
ArrayList arr = new ArrayList { "1", "2" };
cbHocKy.DataSource = arr;
Table<LopHoc> lh = db.GetTable<LopHoc>();
cbLop.DataSource = lh;
Table<MonHoc> monHocs = db.GetTable<MonHoc>();
cbMonHoc.DataSource = monHocs;
Table<PhongBan> phongbans = db.GetTable<PhongBan>();
cbPhongBan.DataSource = phongbans;
}
private void button6_Click(object sender, EventArgs e)
{
Close();
}
private void groupBox2_Enter(object sender, EventArgs e)
{
}
private void txtMaGiaoVien_TextChanged(object sender, EventArgs e)
{
if (txtMaGiaoVien.Text != null && txtMaGiaoVien.Text != "")
{
GiaoVien gv = db.GiaoViens.Where(x => x.MaGiaoVien == int.Parse(txtMaGiaoVien.Text)).FirstOrDefault();
if (gv != null)
{
tbHoTen.Text = gv.HoTen;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
PhanCongGiaoVien pc = new PhanCongGiaoVien();
if (txtMaGiaoVien.Text == null || txtMaGiaoVien.Text == "")
{
MessageBox.Show("Chưa điền mã giáo viên!", "Phân công - Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
pc.MaGiaoVien = int.Parse(txtMaGiaoVien.Text);
pc.MaLopHoc = ((LopHoc)cbLop.SelectedItem).MaLopHoc;
pc.MaMonHoc = ((MonHoc)cbMonHoc.SelectedItem).MaMonHoc;
pc.MaPhongBan = ((PhongBan)cbPhongBan.SelectedItem).MaPhongBan;
pc.HocKy = cbHocKy.SelectedValue.ToString();
pc.NamHoc = DateTime.Now.Year;
if (tbSOtiet.Text == null || tbSOtiet.Text == "")
{
MessageBox.Show("Chưa điền số tiêt!", "Phân công - Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
pc.SoTietDay = int.Parse(tbSOtiet.Text);
db.PhanCongGiaoViens.InsertOnSubmit(pc);
db.SubmitChanges();
MessageBox.Show("Quá trình phân công thành công!", "Phân công - Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show("Quá trình phân công thất bai,! " + ex.ToString(), "Phân công - Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void button3_Click(object sender, EventArgs e)
{
}
//cap nhat
private void button5_Click(object sender, EventArgs e)
{
try
{
if (txtMaGiaoVien.Text == null || txtMaGiaoVien.Text == "")
{
MessageBox.Show("Chưa điền mã giáo viên!", "Phân công - Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
PhanCongGiaoVien pc = db.PhanCongGiaoViens.Where(x => x.MaPhanCong == int.Parse(Text)).FirstOrDefault();
if (txtMaGiaoVien.Text == null || txtMaGiaoVien.Text == "")
{
MessageBox.Show("Chưa điền mã giáo viên!", "Phân công - Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
//PhanCongGiaoVien pc = db.PhanCongGiaoViens.Where(x
pc.MaGiaoVien = int.Parse(txtMaGiaoVien.Text);
pc.MaLopHoc = ((LopHoc)cbLop.SelectedItem).MaLopHoc;
pc.MaMonHoc = ((MonHoc)cbMonHoc.SelectedItem).MaMonHoc;
pc.MaPhongBan = ((PhongBan)cbPhongBan.SelectedItem).MaPhongBan;
pc.HocKy = cbHocKy.SelectedValue.ToString();
pc.NamHoc = DateTime.Now.Year;
if (tbSOtiet.Text == null || tbSOtiet.Text == "")
{
MessageBox.Show("Chưa điền số tiêt!", "Phân công - Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
pc.SoTietDay = int.Parse(tbSOtiet.Text);
db.PhanCongGiaoViens.InsertOnSubmit(pc);
db.SubmitChanges();
MessageBox.Show("Quá trình phân công thành công!", "Phân công - Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show("Quá trình phân công thất bai,! " + ex.ToString(), "Phân công - Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
|
1191021127qlgv
|
trunk/1191021127.QuanLyGiaoVien/1191021127.QuanLyGiaoVien.UI/Form/ChonPhanCongGiaoVien.cs
|
C#
|
asf20
| 5,760
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using _1191021127.QuanLyGiaoVien.Domain;
using _1191021127.QuanLyGiaoVien.Domain.Entities;
using System.Data.Linq;
namespace _1191021127.QuanLyGiaoVien.UI
{
public partial class ThongKeTheoBoMon : Form
{
public ThongKeTheoBoMon()
{
InitializeComponent();
}
DBStoreDataContext db = new DBStoreDataContext();
private void ThongKeTheoBoMon_Load(object sender, EventArgs e)
{
Table<BoMon> boMons = db.GetTable<BoMon>();
cbBoMon.DataSource = boMons;
TimKiemGiaoVienTheoBoMon();
}
private void cbBoMon_SelectedIndexChanged(object sender, EventArgs e)
{
TimKiemGiaoVienTheoBoMon();
}
private void TimKiemGiaoVienTheoBoMon()
{
List<GiaoVien> gv = null;
if (cbBoMon.SelectedValue != null)
{
if (gv == null)
gv = db.GiaoViens.ToList<GiaoVien>();
BoMon m = (BoMon)cbBoMon.SelectedValue;
gv.Clear();
gv = db.GiaoViens.ToList<GiaoVien>().Where(x => x.MaBoMon == m.MaBoMon).ToList<GiaoVien>(); ;
}
List<GiaoVienView> lGVView = new List<GiaoVienView>();
if (gv == null)
{
dgBoMon.DataSource = null;
return;
}
for (int i = 0; i < gv.Count; i++)
{
GiaoVienView gvview = new GiaoVienView();
gvview.Id = gv[i].MaGiaoVien;
gvview.HoTen = gv[i].HoTen;
gvview.GioiTinh = gv[i].GioiTinh;
gvview.NgaySinh = (gv[i].NgaySinh != null ? gv[i].NgaySinh.ToString() : "Chưa cập nhật ngày sinh");
gvview.Email = gv[i].Email;
gvview.SoDienThoai = (long)gv[i].SoDienThoai;
gvview.LuongCoBan = (float)gv[i].LuongCoBan;
gvview.BoMon = gv[i].BoMon;
lGVView.Add(gvview);
}
dgBoMon.DataSource = lGVView;
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
|
1191021127qlgv
|
trunk/1191021127.QuanLyGiaoVien/1191021127.QuanLyGiaoVien.UI/Form/ThongKeTheoBoMon.cs
|
C#
|
asf20
| 2,444
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using _1191021127.QuanLyGiaoVien.Domain;
using _1191021127.QuanLyGiaoVien.Domain.Entities;
using System.Data.Linq;
namespace _1191021127.QuanLyGiaoVien.UI
{
public partial class TimKiemLichGiangDay : Form
{
public TimKiemLichGiangDay()
{
InitializeComponent();
}
DBStoreDataContext db = new DBStoreDataContext();
private void button2_Click(object sender, EventArgs e)
{
Close();
}
private void TimKiemLichGiangDay_Load(object sender, EventArgs e)
{
//Load danh sách mã giáo viên cần thống kê
Table<GiaoVien> giaoViens = db.GetTable<GiaoVien>();
cbGV.DataSource = giaoViens;
// TimKiemLichDayGiaoVien();
}
private void cbMaGiaoVien_SelectedIndexChanged(object sender, EventArgs e)
{
TimKiemLichDayGiaoVien();
}
private void TimKiemLichDayGiaoVien()
{
//if (cbMaGiaoVien.SelectedValue != null)
//{
// List<PhanCongGiaoVien> lstgv = null;
// GiaoVien gvx = (GiaoVien)cbMaGiaoVien.SelectedValue;
// txtHoTen.Text = gvx.HoTen;
// lstgv = db.PhanCongGiaoViens.ToList<PhanCongGiaoVien>().Where(x => x.MaGiaoVien == gvx.MaGiaoVien).ToList<PhanCongGiaoVien>(); ;
// dgPhanCong.DataSource = lstgv;
//}
}
private void cbGV_SelectedIndexChanged(object sender, EventArgs e)
{
GiaoVien gvx = (GiaoVien)cbGV.SelectedValue;
List<PhanCongGiaoVien> lstgv = db.PhanCongGiaoViens.ToList<PhanCongGiaoVien>().Where(x => x.MaGiaoVien == gvx.MaGiaoVien).ToList<PhanCongGiaoVien>();
dgPhanCong.DataSource = lstgv;
}
}
}
|
1191021127qlgv
|
trunk/1191021127.QuanLyGiaoVien/1191021127.QuanLyGiaoVien.UI/Form/TimKiemLichGiangDay.cs
|
C#
|
asf20
| 2,054
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Data.Linq;
using System.Text;
using System.Windows.Forms;
using _1191021127.QuanLyGiaoVien.Domain;
using _1191021127.QuanLyGiaoVien.Domain.Entities;
namespace _1191021127.QuanLyGiaoVien.UI
{
public partial class TimKiemGiaoVien : Form
{
DBStoreDataContext db = new DBStoreDataContext();
public TimKiemGiaoVien()
{
InitializeComponent();
}
private void groupBox2_Enter(object sender, EventArgs e)
{
}
private void btTim_Click(object sender, EventArgs e)
{
string tenGV = tbTenGV.Text;
List<GiaoVien> gv = null;
if (tenGV != null && tenGV != "")
{
gv = db.GiaoViens.Where(x => x.HoTen.Contains(tenGV) && x.TrangThai == true).ToList<GiaoVien>();
}
string maGV = tbMaGV.Text;
ChucDanh hocVi = (ChucDanh)cbHocVi.SelectedValue;
ChucDanh hocHam = (ChucDanh)cbHocHam.SelectedValue;
if (checkBoxHocVi.Checked && cbHocVi.SelectedValue != null)
{
if (gv == null) gv = db.GiaoViens.ToList<GiaoVien>();
ChucDanh m = (ChucDanh)cbHocVi.SelectedValue;
List<ChucDanh_GiaoVien> lcd = db.ChucDanh_GiaoViens.Where(x => x.MaChucDanh == m.MaChucDanh).ToList<ChucDanh_GiaoVien>();
List<GiaoVien> gvs = new List<GiaoVien>();
gv.Clear();
for (int i = 0; i < lcd.Count; i++)
{
gv.Add(lcd[i].GiaoVien);
}
}
if (checkBoxHocHam.Checked && cbHocHam.SelectedValue != null)
{
if (gv == null) gv = db.GiaoViens.ToList<GiaoVien>();
ChucDanh m = (ChucDanh)cbHocHam.SelectedValue;
List<ChucDanh_GiaoVien> lcd = db.ChucDanh_GiaoViens.Where(x => x.MaChucDanh == m.MaChucDanh).ToList<ChucDanh_GiaoVien>();
List<GiaoVien> gvs = new List<GiaoVien>();
gv.Clear();
for (int i = 0; i < lcd.Count; i++)
{
gv.Add(lcd[i].GiaoVien);
}
}
if (checkBoxBoMon.Checked && cbBoMon.SelectedValue != null)
{
if (gv == null) gv = db.GiaoViens.ToList<GiaoVien>();
BoMon bm = (BoMon)cbBoMon.SelectedValue;
gv = gv.Where(x => x.MaGiaoVien == bm.MaBoMon).ToList<GiaoVien>();
}
if (checkboxMaGV.Checked && tbMaGV.Text != null && maGV != null || maGV != "")
{
if (gv == null) gv = db.GiaoViens.ToList<GiaoVien>();
int ma = int.Parse(maGV);
gv = gv.Where(x => x.MaGiaoVien == ma).ToList<GiaoVien>();
}
List<GiaoVienView> lGVView = new List<GiaoVienView>();
if (gv == null)
{
dataGridViewGV.DataSource = null;
return;
}
for (int i = 0; i < gv.Count; i++)
{
GiaoVienView gvview = new GiaoVienView();
gvview.Id = gv[i].MaGiaoVien;
gvview.HoTen = gv[i].HoTen;
gvview.GioiTinh = gv[i].GioiTinh;
gvview.NgaySinh = ( gv[i].NgaySinh != null ? gv[i].NgaySinh.ToString() : "Chưa cập nhật ngày sinh");
gvview.Email = gv[i].Email;
gvview.SoDienThoai = (long)gv[i].SoDienThoai;
gvview.LuongCoBan = (float)gv[i].LuongCoBan;
gvview.BoMon = gv[i].BoMon;
List<ChiTietChucVuGV> cv = db.ChiTietChucVuGVs.Where(x => x.MaGV == gv[i].MaGiaoVien).ToList<ChiTietChucVuGV>();
if (cv.Count > 0)
{
gvview.MChucVu = cv[0].ChucVu;
}
else
{
gvview.MChucVu = new ChucVu();
gvview.MChucVu.TenChucVu = "Chưa có chức vụ";
}
List<ChucDanh_GiaoVien> cd = db.ChucDanh_GiaoViens.Where(x => x.MaGiaoVien == gv[i].MaGiaoVien).ToList<ChucDanh_GiaoVien>();
if (cd.Count > 0)
{
gvview.ChucDanh = cd[0].ChucDanh;
}
else
{
gvview.ChucDanh = new ChucDanh();
gvview.ChucDanh.TenChucDanh = "Chưa có chức danh";
}
lGVView.Add(gvview);
}
dataGridViewGV.DataSource = lGVView;
}
private void TimKiemGiaoVien_Load(object sender, EventArgs e)
{
Table<BoMon> tbBoMon = db.GetTable<BoMon>();
List<ChucDanh> LHocVi = db.ChucDanhs.Where(x => x.LoaiChucDanh == "Hoc Vị").ToList<ChucDanh>();
List<ChucDanh> LHocHam = db.ChucDanhs.Where(x => x.LoaiChucDanh == "Học Hàm").ToList<ChucDanh>();
cbBoMon.DataSource = tbBoMon;
cbHocHam.DataSource = LHocHam;
cbHocVi.DataSource = LHocVi;
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
|
1191021127qlgv
|
trunk/1191021127.QuanLyGiaoVien/1191021127.QuanLyGiaoVien.UI/Form/TimKiemGiaoVien.cs
|
C#
|
asf20
| 5,522
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Linq;
using _1191021127.QuanLyGiaoVien.Domain;
using _1191021127.QuanLyGiaoVien.Domain.Entities;
namespace _1191021127.QuanLyGiaoVien.UI
{
public partial class ThongKeChucDanh : Form
{
public ThongKeChucDanh()
{
InitializeComponent();
}
DBStoreDataContext db = new DBStoreDataContext();
private void ThongKeChucDanh_Load(object sender, EventArgs e)
{
Table<ChucDanh> chucDanhs = db.GetTable<ChucDanh>();
cbChucDanh.DataSource = chucDanhs;
TimKiemGiaoVienTheoChucDanh();
}
private void cbChucDanh_SelectedIndexChanged(object sender, EventArgs e)
{
TimKiemGiaoVienTheoChucDanh();
}
private void TimKiemGiaoVienTheoChucDanh()
{
List<GiaoVien> gv = null;
if (cbChucDanh.SelectedValue != null)
{
if (gv == null)
gv = db.GiaoViens.ToList<GiaoVien>();
ChucDanh m = (ChucDanh)cbChucDanh.SelectedValue;
List<ChucDanh_GiaoVien> lcd = db.ChucDanh_GiaoViens.Where(x => x.MaChucDanh == m.MaChucDanh).ToList<ChucDanh_GiaoVien>();
List<GiaoVien> gvs = new List<GiaoVien>();
gv.Clear();
for (int i = 0; i < lcd.Count; i++)
{
gv.Add(lcd[i].GiaoVien);
}
}
List<GiaoVienView> lGVView = new List<GiaoVienView>();
if (gv == null)
{
dgChucDanh.DataSource = null;
return;
}
for (int i = 0; i < gv.Count; i++)
{
GiaoVienView gvview = new GiaoVienView();
gvview.Id = gv[i].MaGiaoVien;
gvview.HoTen = gv[i].HoTen;
gvview.GioiTinh = gv[i].GioiTinh;
gvview.NgaySinh = (gv[i].NgaySinh != null ? gv[i].NgaySinh.ToString() : "Chưa cập nhật ngày sinh");
gvview.Email = gv[i].Email;
gvview.SoDienThoai = (long)gv[i].SoDienThoai;
gvview.LuongCoBan = (float)gv[i].LuongCoBan;
gvview.BoMon = gv[i].BoMon;
List<ChucDanh_GiaoVien> cd = db.ChucDanh_GiaoViens.Where(x => x.MaGiaoVien == gv[i].MaGiaoVien).ToList<ChucDanh_GiaoVien>();
if (cd.Count > 0)
{
gvview.ChucDanh = cd[0].ChucDanh;
}
else
{
gvview.ChucDanh = new ChucDanh();
gvview.ChucDanh.TenChucDanh = "Chưa có chức danh";
}
lGVView.Add(gvview);
}
dgChucDanh.DataSource = lGVView;
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
|
1191021127qlgv
|
trunk/1191021127.QuanLyGiaoVien/1191021127.QuanLyGiaoVien.UI/Form/ThongKeChucDanh.cs
|
C#
|
asf20
| 3,169
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Data.Linq;
using System.Text;
using System.Windows.Forms;
using _1191021127.QuanLyGiaoVien.Domain;
namespace _1191021127.QuanLyGiaoVien.UI
{
public partial class XoaGiaoVien : Form
{
public XoaGiaoVien()
{
InitializeComponent();
}
DBStoreDataContext db = new DBStoreDataContext();
private void btXoa_Click(object sender, EventArgs e)
{
try
{
if (tbMaGV.Text != null && tbMaGV.Text != "")
{
int magv = int.Parse(tbMaGV.Text);
// lay thong tin giao vien co ma giao vien la magv
GiaoVien gv = db.GiaoViens.Where(x => x.MaGiaoVien == magv).FirstOrDefault();
if (gv != null)
{
gv.TrangThai = false;
db.SubmitChanges();
MessageBox.Show("Xóa thành công,", "Xóa Giáo viên - Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
cbMaGV.DataSource = db.GiaoViens.Where(x => x.TrangThai == true).ToList<GiaoVien>();
}
else
{
MessageBox.Show("không tìm thấy giáo viên có mã : " + magv, "Xóa Giáo viên - Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
MessageBox.Show("Chưa nhập mã giáo viên cần xóa,", "Xóa Giáo viên - Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex) {
MessageBox.Show("Xóa thất bại ! \n Lỗi :" + ex.ToString(), "Xóa Giáo viên - Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void XoaGiaoVien_Load(object sender, EventArgs e)
{
// loat tat ca cac ma giao vien len combobox
cbMaGV.DataSource = db.GiaoViens.Where(x=> x.TrangThai == true).ToList<GiaoVien>();
}
private void cbMaGV_SelectedIndexChanged(object sender, EventArgs e)
{
GiaoVien gv = (GiaoVien)cbMaGV.SelectedItem;
tbMaGV.Text = "";
tbBoMon.Text = "";
tbKhoa.Text = "";
// cap nhat lai thong tin tren form
if (gv != null)
{
tbMaGV.Text = gv.MaGiaoVien.ToString();
tbBoMon.Text = gv.BoMon.ToString();
BoMon b = db.BoMons.Where(x => x.MaBoMon == gv.MaBoMon).FirstOrDefault();
if (b != null) {
tbKhoa.Text = b.Khoa.ToString();
}
}
}
private void btDong_Click(object sender, EventArgs e)
{
this.Close();
}
private void tbMaGV_TextChanged(object sender, EventArgs e)
{
// if (tbMaGV.Text == null || tbMaGV.Text == "")
// { return; }
// int magv = int.Parse(tbMaGV.Text);
// List<GiaoVien> lgv = db.GiaoViens.Where(x => x.TrangThai == true).ToList<GiaoVien>();
// if (lgv == null || lgv.Count <= 0) return;
// GiaoVien gv = (GiaoVien)lgv[0];
// tbBoMon.Text = "";
// tbKhoa.Text = "";
// cbMaGV.SelectedItem = gv;
// // cap nhat lai thong tin tren form
// if (gv != null)
// {
// tbBoMon.Text = gv.BoMon.ToString();
// BoMon b = db.BoMons.Where(x => x.MaBoMon == gv.MaBoMon).FirstOrDefault();
// if (b != null)
// {
// tbKhoa.Text = b.Khoa.ToString();
// }
// }
}
}
}
|
1191021127qlgv
|
trunk/1191021127.QuanLyGiaoVien/1191021127.QuanLyGiaoVien.UI/Form/XoaGiaoVien.cs
|
C#
|
asf20
| 4,098
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace _1191021127.QuanLyGiaoVien.UI.Common
{
public partial class IN : Form
{
public IN()
{
InitializeComponent();
}
}
}
|
1191021127qlgv
|
trunk/1191021127.QuanLyGiaoVien/1191021127.QuanLyGiaoVien.UI/Form/IN.cs
|
C#
|
asf20
| 380
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Data.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using _1191021127.QuanLyGiaoVien.Domain;
namespace _1191021127.QuanLyGiaoVien.UI.Common
{
public partial class ThemGiaoVien : Form
{
DBStoreDataContext db = new DBStoreDataContext();
public ThemGiaoVien()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
//try
//{
GiaoVien giaoVien = new GiaoVien();
giaoVien.HoTen = txtHoTen.Text;
if (txtHoTen.Text == null || txtHoTen.Text == "")
{
MessageBox.Show("chưa điền tên," , "Giáo viên - Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
giaoVien.GioiTinh = cbGioiTinh.SelectedValue.ToString();
giaoVien.NgaySinh = DateTime.Now;
giaoVien.Email = txtEmail.Text;
if(giaoVien.Email == null || giaoVien.Email == "")
{
MessageBox.Show("chưa điền email" , "Giáo viên - Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
if(txtSoDienThoai.Text == null || txtSoDienThoai.Text == "")
{
MessageBox.Show("chưa điền so dien thoai" , "Giáo viên - Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
giaoVien.SoDienThoai = int.Parse(txtSoDienThoai.Text);
if(txtLuongCoBan.Text == null || txtLuongCoBan.Text == "")
{
MessageBox.Show("Chưa điền lương cơ bản!," , "Giáo viên - Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
giaoVien.LuongCoBan = int.Parse(txtLuongCoBan.Text);
BoMon bm = (BoMon)cbBoMon.SelectedValue;
if(bm != null){
giaoVien.MaBoMon = bm.MaBoMon;
}
giaoVien.TrangThai = true;
db.GiaoViens.InsertOnSubmit(giaoVien);
db.SubmitChanges();
ChiTietChucVuGV chiTiet = new ChiTietChucVuGV();
ChucVu cv = (ChucVu)cbChucVu.SelectedValue;
if (cv != null)
{
chiTiet.MaChucVu = cv.MaChucVu;
}
chiTiet.MaGV = giaoVien.MaGiaoVien; ;
db.ChiTietChucVuGVs.InsertOnSubmit(chiTiet);
db.SubmitChanges();
ChucDanh_GiaoVien chiTiet2 = new ChucDanh_GiaoVien();
ChucDanh cd = (ChucDanh)cbChucDanh.SelectedValue;
if (cd != null)
{
chiTiet2.MaChucDanh = cd.MaChucDanh;
}
chiTiet2.MaGiaoVien = giaoVien.MaGiaoVien; ;
db.ChucDanh_GiaoViens.InsertOnSubmit(chiTiet2);
db.SubmitChanges();
MessageBox.Show("Qúa trình thêm thành công!", "Giáo viên - Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.DialogResult = DialogResult.OK;
//}
//catch (FormatException ex)
//{
// MessageBox.Show("Qúa trình thêm thất bại!," + ex.ToString(), "Giáo viên - Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
// this.DialogResult = DialogResult.OK;
//}
}
private void ThemGiaoVien_Load(object sender, EventArgs e)
{
ArrayList array = new ArrayList { "Nam", "Nữ" };
cbGioiTinh.DataSource = array;
Table<ChucDanh> chucDanhs = db.GetTable<ChucDanh>();
cbChucDanh.DataSource = chucDanhs;
Table<ChucVu> chucVus = db.GetTable<ChucVu>();
cbChucVu.DataSource = chucVus;
Table<BoMon> boMons = db.GetTable<BoMon>();
cbBoMon.DataSource = boMons;
}
}
}
|
1191021127qlgv
|
trunk/1191021127.QuanLyGiaoVien/1191021127.QuanLyGiaoVien.UI/Form/ThemGiaoVien.cs
|
C#
|
asf20
| 4,603
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using _1191021127.QuanLyGiaoVien.Domain;
namespace _1191021127.QuanLyGiaoVien.UI
{
public partial class XuatLuongGV : Form
{
DBStoreDataContext db = new DBStoreDataContext();
public XuatLuongGV()
{
InitializeComponent();
}
private void label4_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text != null && textBox1.Text != "")
{
GiaoVien gv = db.GiaoViens.Where(x => x.MaGiaoVien == int.Parse(textBox1.Text)).FirstOrDefault();
if (gv != null)
{
tbMaGV.Text = gv.MaGiaoVien.ToString();
tbHoTen.Text = gv.HoTen;
ChucDanh_GiaoVien xx = db.ChucDanh_GiaoViens.Where(x => x.MaGiaoVien == gv.MaGiaoVien).FirstOrDefault();
if (xx != null)
{
tbHSL.Text = xx.ChucDanh.HeSoLuong.ToString();
}
tbLuongCoBan.Text = gv.LuongCoBan.ToString();
List<PhanCongGiaoVien> lpc = db.PhanCongGiaoViens.Where(x => x.MaGiaoVien == gv.MaGiaoVien).ToList<PhanCongGiaoVien>();
int soTietDay = 0;
for (int i = 0; i < lpc.Count; i++)
{
soTietDay += (int)lpc[i].SoTietDay;
}
tbSoTiet.Text = soTietDay.ToString();
float tongLuong =(float)(gv.LuongCoBan + xx.ChucDanh.HeSoLuong * soTietDay);
tbTongLuong.Text = tongLuong.ToString();
}
}
}
private void XuatLuongGV_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
|
1191021127qlgv
|
trunk/1191021127.QuanLyGiaoVien/1191021127.QuanLyGiaoVien.UI/Form/XuatLuongGV.cs
|
C#
|
asf20
| 2,229
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using _1191021127.QuanLyGiaoVien.UI.Common;
namespace _1191021127.QuanLyGiaoVien.UI
{
public partial class Main : Form
{
public Main()
{
InitializeComponent();
}
private void quảnLýHồSơGiáoVienToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void thêmHồSơGiáoViênToolStripMenuItem_Click(object sender, EventArgs e)
{
Form f = new ThemGiaoVien();
f.MdiParent = this;
f.Show();
}
private void xóaHồSơGiáoViênToolStripMenuItem_Click(object sender, EventArgs e)
{
Form f = new XoaGiaoVien();
f.MdiParent = this;
f.Show();
}
private void cậpNhậtHồSơGiáoViênToolStripMenuItem_Click(object sender, EventArgs e)
{
Form f = new CapNhatGiaoVien();
f.MdiParent = this;
f.Show();
}
private void phânCôngToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void thôngTinGiáoViênToolStripMenuItem_Click(object sender, EventArgs e)
{
Form f = new ChonPhanCongGiaoVien();
f.MdiParent = this;
f.Show();
}
private void chứcDanhToolStripMenuItem_Click(object sender, EventArgs e)
{
Form f = new ThongKeChucDanh();
f.MdiParent = this;
f.Show();
}
private void TimKiemGVToolStripMenuItem_Click(object sender, EventArgs e)
{
Form f = new TimKiemGiaoVien();
f.MdiParent = this;
f.Show();
}
private void TimKiemLichGiangDayToolStripMenuItem_Click(object sender, EventArgs e)
{
Form f = new TimKiemLichGiangDay();
f.MdiParent = this;
f.Show();
}
private void ThongKeTheoHocViToolStripMenuItem_Click(object sender, EventArgs e)
{
Form f = new ThongKeChucDanh();
f.MdiParent = this;
f.Show();
}
private void ThongKeTheoBoMonToolStripMenuItem_Click(object sender, EventArgs e)
{
Form f = new ThongKeTheoBoMon();
f.MdiParent = this;
f.Show();
}
private void ThoatToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void XuatLuongGVToolStripMenuItem_Click(object sender, EventArgs e)
{
Form f = new XuatLuongGV();
f.MdiParent = this;
f.Show();
}
private void Main_Load(object sender, EventArgs e)
{
//Form dangNhap = new DangNhap();
//dangNhap.MdiParent = this;
//dangNhap.Show();
}
}
}
|
1191021127qlgv
|
trunk/1191021127.QuanLyGiaoVien/1191021127.QuanLyGiaoVien.UI/Form/Main.cs
|
C#
|
asf20
| 3,180
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using _1191021127.QuanLyGiaoVien.Domain;
using System.Data.Linq;
using System.Collections;
namespace _1191021127.QuanLyGiaoVien.UI
{
public partial class CapNhatGiaoVien : Form
{
GiaoVien giaovienHienTai = null;
public CapNhatGiaoVien()
{
InitializeComponent();
}
DBStoreDataContext db = new DBStoreDataContext();
private void CapNhatGiaoVien_Load(object sender, EventArgs e)
{
ArrayList array = new ArrayList { "Nam", "Nữ" };
cbGioiTinh.DataSource = array;
Table<ChucDanh> chucDanhs = db.GetTable<ChucDanh>();
cbChucDanh.DataSource = chucDanhs;
Table<ChucVu> chucVus = db.GetTable<ChucVu>();
cbChucVu.DataSource = chucVus;
Table<BoMon> boMons = db.GetTable<BoMon>();
cbBoMon.DataSource = boMons;
cbHoTen.DataSource = db.GiaoViens.Where(x=> x.TrangThai == true).ToList<GiaoVien>();
giaovienHienTai = (GiaoVien)cbHoTen.SelectedItem;
dtNgaySinh.Text = giaovienHienTai.NgaySinh.ToString();
cbGioiTinh.Text = giaovienHienTai.GioiTinh;
txtEmail.Text = giaovienHienTai.Email;
txtSoDienThoai.Text = giaovienHienTai.SoDienThoai.ToString();
txtLuongCoBan.Text = giaovienHienTai.LuongCoBan.ToString();
ChucDanh_GiaoVien ct = db.ChucDanh_GiaoViens.Where(x => x.MaGiaoVien == giaovienHienTai.MaGiaoVien).FirstOrDefault();
if(ct != null)
cbChucDanh.SelectedItem = ct.ChucDanh;
ChiTietChucVuGV chiTietChucVu = db.ChiTietChucVuGVs.Where(x => x.MaGV == giaovienHienTai.MaGiaoVien).FirstOrDefault();
if (chiTietChucVu != null)
cbChucVu.SelectedItem = chiTietChucVu.ChucVu ;
cbBoMon.SelectedItem = giaovienHienTai.BoMon;
}
private void cbChucDanh_SelectedIndexChanged(object sender, EventArgs e)
{
if(giaovienHienTai != null)
{
ChucDanh_GiaoVien ct = db.ChucDanh_GiaoViens.Where(x => x.MaGiaoVien == giaovienHienTai.MaGiaoVien).FirstOrDefault();
if (ct == null) return;
db.ChucDanh_GiaoViens.InsertOnSubmit(ct);
ct.MaChucDanh = ((ChucDanh)cbChucDanh.SelectedItem).MaChucDanh;
ct.MaGiaoVien = giaovienHienTai.MaGiaoVien;
db.ChucDanh_GiaoViens.InsertOnSubmit(ct);
}
// db.SubmitChanges();
}
private void cbChucVu_SelectedIndexChanged(object sender, EventArgs e)
{
if (giaovienHienTai != null)
{
ChiTietChucVuGV ct = db.ChiTietChucVuGVs.Where(x => x.MaGV == giaovienHienTai.MaGiaoVien).FirstOrDefault();
db.ChiTietChucVuGVs.DeleteOnSubmit(ct);
ct.MaChucVu = ((ChucVu)cbChucVu.SelectedItem).MaChucVu;
ct.MaGV = giaovienHienTai.MaGiaoVien;
db.ChiTietChucVuGVs.InsertOnSubmit(ct);
}
// db.SubmitChanges();
}
private void cbBoMon_SelectedIndexChanged(object sender, EventArgs e)
{
if (giaovienHienTai != null)
giaovienHienTai.MaBoMon = ((BoMon)cbBoMon.SelectedItem).MaBoMon;
// db.SubmitChanges();
}
private void cbHoTen_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
GiaoVien gv = (GiaoVien)cbHoTen.SelectedItem;
dtNgaySinh.Text = gv.NgaySinh.ToString();
cbGioiTinh.Text = gv.GioiTinh;
txtEmail.Text = gv.Email;
txtSoDienThoai.Text = gv.SoDienThoai.ToString();
txtLuongCoBan.Text = gv.LuongCoBan.ToString();
ChiTietChucVuGV cv = db.ChiTietChucVuGVs.Where(x => x.MaGV == gv.MaGiaoVien).FirstOrDefault();
if (cv != null)
cbChucVu.SelectedItem = cv.ChucVu;
ChucDanh_GiaoVien cd = gv.ChucDanh_GiaoViens.Where(x => x.MaGiaoVien == gv.MaGiaoVien).FirstOrDefault();
if (cd != null)
cbChucDanh.SelectedItem = cd.ChucDanh;
BoMon bm = gv.BoMon;
cbBoMon.SelectedItem = bm;
}
catch (Exception ex) { }
}
private void button2_Click(object sender, EventArgs e)
{
try
{
if( txtEmail.Text != null && txtEmail.Text != "")
giaovienHienTai.Email = txtEmail.Text;
if(txtSoDienThoai.Text != null && txtSoDienThoai.Text != "")
giaovienHienTai.SoDienThoai = Int32.Parse(txtSoDienThoai.Text);
if (txtLuongCoBan.Text != null && txtLuongCoBan.Text != "")
giaovienHienTai.LuongCoBan = Int32.Parse(txtLuongCoBan.Text);
db.SubmitChanges();
MessageBox.Show("Quá trình cập nhật thành công!", "Giáo viên - Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.DialogResult = DialogResult.OK;
}
catch (Exception ex )
{
MessageBox.Show("Qúa trình cập nhật thất bại! \n Lỗi : " + ex.ToString(), "Giáo viên - Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.DialogResult = DialogResult.OK;
}
}
private void cbGioiTinh_SelectedIndexChanged(object sender, EventArgs e)
{
if (giaovienHienTai != null && cbGioiTinh.SelectedItem != null)
giaovienHienTai.GioiTinh = (string)cbGioiTinh.SelectedItem;
}
private void dtNgaySinh_ValueChanged(object sender, EventArgs e)
{
if (giaovienHienTai != null)
giaovienHienTai.NgaySinh = dtNgaySinh.Value;
}
}
}
|
1191021127qlgv
|
trunk/1191021127.QuanLyGiaoVien/1191021127.QuanLyGiaoVien.UI/Form/CapNhatGiaoVien.cs
|
C#
|
asf20
| 6,260
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("1191021127.QuanLyGiaoVien.UI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("1191021127.QuanLyGiaoVien.UI")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4b25cdc9-648c-403c-a6c9-2a21657a0047")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
1191021127qlgv
|
trunk/1191021127.QuanLyGiaoVien/1191021127.QuanLyGiaoVien.UI/Properties/AssemblyInfo.cs
|
C#
|
asf20
| 1,468
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _1191021127.QuanLyGiaoVien.Domain.Entities
{
public class GiaoVienView
{
private long mId;
public long Id
{
get { return mId; }
set { mId = value; }
}
private string mHoTen;
public string HoTen
{
get { return mHoTen; }
set { mHoTen = value; }
}
private string mGioiTinh;
public string GioiTinh
{
get { return mGioiTinh; }
set { mGioiTinh = value; }
}
private string mNgaySinh;
public string NgaySinh
{
get { return mNgaySinh; }
set { mNgaySinh = value; }
}
private string mEmail;
public string Email
{
get { return mEmail; }
set { mEmail = value; }
}
private long mSoDT;
public long SoDienThoai
{
get { return mSoDT; }
set { mSoDT = value; }
}
private float mLuongCoBan;
public float LuongCoBan
{
get { return mLuongCoBan; }
set { mLuongCoBan = value; }
}
private BoMon mBoMon;
public BoMon BoMon
{
get { return mBoMon; }
set { mBoMon = value; }
}
private ChucDanh mChucDanh;
public ChucDanh ChucDanh
{
get { return mChucDanh; }
set { mChucDanh = value; }
}
private ChucVu mChucVu;
public ChucVu MChucVu
{
get { return mChucVu; }
set { mChucVu = value; }
}
}
}
|
1191021127qlgv
|
trunk/1191021127.QuanLyGiaoVien/1191021127.QuanLyGiaoVien.Domain/EntitiesView/GiaoVienView.cs
|
C#
|
asf20
| 1,828
|
namespace _1191021127.QuanLyGiaoVien.Domain
{
partial class Khoa
{
public override string ToString()
{
return this.TenKhoa;
}
}
partial class MonHoc
{
public override string ToString()
{
return this.TenMonHoc;
}
}
partial class PhongBan
{
public override string ToString()
{
return this.TenPhongBan;
}
}
partial class LopHoc
{
public override string ToString()
{
return this.TenLopHoc;
}
}
partial class BoMon
{
public override string ToString()
{
return this.TenBoMon;
}
}
partial class ChucVu
{
public override string ToString()
{
return this.TenChucVu;
}
}
partial class GiaoVien
{
public override string ToString()
{
return this.HoTen;
}
}
partial class ChucDanh
{
public override string ToString()
{
return this.TenChucDanh;
}
}
}
|
1191021127qlgv
|
trunk/1191021127.QuanLyGiaoVien/1191021127.QuanLyGiaoVien.Domain/DBStore.cs
|
C#
|
asf20
| 1,191
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("1191021127.QuanLyGiaoVien.Domain")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("1191021127.QuanLyGiaoVien.Domain")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("49d7d08c-00c0-49de-9ce1-f1a0e00829b8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
1191021127qlgv
|
trunk/1191021127.QuanLyGiaoVien/1191021127.QuanLyGiaoVien.Domain/Properties/AssemblyInfo.cs
|
C#
|
asf20
| 1,476
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.activities;
import java.util.ArrayList;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.DeleteInstancesListener;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import org.odk.collect.android.tasks.DeleteInstancesTask;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
/**
* Responsible for displaying and deleting all the valid forms in the forms
* directory.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class DataManagerList extends ListActivity implements
DeleteInstancesListener {
private static final String t = "DataManagerList";
private AlertDialog mAlertDialog;
private Button mDeleteButton;
private Button mToggleButton;
private SimpleCursorAdapter mInstances;
private ArrayList<Long> mSelected = new ArrayList<Long>();
DeleteInstancesTask mDeleteInstancesTask = null;
private static final String SELECTED = "selected";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data_manage_list);
mDeleteButton = (Button) findViewById(R.id.delete_button);
mDeleteButton.setText(getString(R.string.delete_file));
mDeleteButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logAction(this, "deleteButton", Integer.toString(mSelected.size()));
if (mSelected.size() > 0) {
createDeleteInstancesDialog();
} else {
Toast.makeText(getApplicationContext(),
R.string.noselect_error, Toast.LENGTH_SHORT).show();
}
}
});
mToggleButton = (Button) findViewById(R.id.toggle_button);
mToggleButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
boolean checkAll = false;
// if everything is checked, uncheck
if (mSelected.size() == mInstances.getCount()) {
checkAll = false;
mSelected.clear();
mDeleteButton.setEnabled(false);
} else {
// otherwise check everything
checkAll = true;
for (int pos = 0; pos < DataManagerList.this.getListView().getCount(); pos++) {
Long id = getListAdapter().getItemId(pos);
if (!mSelected.contains(id)) {
mSelected.add(id);
}
}
mDeleteButton.setEnabled(true);
}
for (int pos = 0; pos < DataManagerList.this.getListView().getCount(); pos++) {
DataManagerList.this.getListView().setItemChecked(pos, checkAll);
}
}
});
Cursor c = managedQuery(InstanceColumns.CONTENT_URI, null, null, null,
InstanceColumns.DISPLAY_NAME + " ASC");
String[] data = new String[] { InstanceColumns.DISPLAY_NAME,
InstanceColumns.DISPLAY_SUBTEXT };
int[] view = new int[] { R.id.text1, R.id.text2 };
mInstances = new SimpleCursorAdapter(this,
R.layout.two_item_multiple_choice, c, data, view);
setListAdapter(mInstances);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
getListView().setItemsCanFocus(false);
mDeleteButton.setEnabled(false);
mDeleteInstancesTask = (DeleteInstancesTask) getLastNonConfigurationInstance();
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
@Override
public Object onRetainNonConfigurationInstance() {
// pass the tasks on orientation-change restart
return mDeleteInstancesTask;
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
long[] selectedArray = savedInstanceState.getLongArray(SELECTED);
for (int i = 0; i < selectedArray.length; i++) {
mSelected.add(selectedArray[i]);
}
mDeleteButton.setEnabled(selectedArray.length > 0);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
long[] selectedArray = new long[mSelected.size()];
for (int i = 0; i < mSelected.size(); i++) {
selectedArray[i] = mSelected.get(i);
}
outState.putLongArray(SELECTED, selectedArray);
}
@Override
protected void onResume() {
// hook up to receive completion events
if (mDeleteInstancesTask != null) {
mDeleteInstancesTask.setDeleteListener(this);
}
super.onResume();
// async task may have completed while we were reorienting...
if (mDeleteInstancesTask != null
&& mDeleteInstancesTask.getStatus() == AsyncTask.Status.FINISHED) {
deleteComplete(mDeleteInstancesTask.getDeleteCount());
}
}
@Override
protected void onPause() {
if (mDeleteInstancesTask != null ) {
mDeleteInstancesTask.setDeleteListener(null);
}
if (mAlertDialog != null && mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
super.onPause();
}
/**
* Create the instance delete dialog
*/
private void createDeleteInstancesDialog() {
Collect.getInstance().getActivityLogger().logAction(this, "createDeleteInstancesDialog", "show");
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setTitle(getString(R.string.delete_file));
mAlertDialog.setMessage(getString(R.string.delete_confirm,
mSelected.size()));
DialogInterface.OnClickListener dialogYesNoListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON_POSITIVE: // delete
Collect.getInstance().getActivityLogger().logAction(this, "createDeleteInstancesDialog", "delete");
deleteSelectedInstances();
break;
case DialogInterface. BUTTON_NEGATIVE: // do nothing
Collect.getInstance().getActivityLogger().logAction(this, "createDeleteInstancesDialog", "cancel");
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.delete_yes),
dialogYesNoListener);
mAlertDialog.setButton2(getString(R.string.delete_no),
dialogYesNoListener);
mAlertDialog.show();
}
/**
* Deletes the selected files. Content provider handles removing the files
* from the filesystem.
*/
private void deleteSelectedInstances() {
if (mDeleteInstancesTask == null) {
mDeleteInstancesTask = new DeleteInstancesTask();
mDeleteInstancesTask.setContentResolver(getContentResolver());
mDeleteInstancesTask.setDeleteListener(this);
mDeleteInstancesTask.execute(mSelected.toArray(new Long[mSelected
.size()]));
} else {
Toast.makeText(this, getString(R.string.file_delete_in_progress),
Toast.LENGTH_LONG).show();
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// get row id from db
Cursor c = (Cursor) getListAdapter().getItem(position);
long k = c.getLong(c.getColumnIndex(InstanceColumns._ID));
// add/remove from selected list
if (mSelected.contains(k))
mSelected.remove(k);
else
mSelected.add(k);
Collect.getInstance().getActivityLogger().logAction(this, "onListItemClick", Long.toString(k));
mDeleteButton.setEnabled(!(mSelected.size() == 0));
}
@Override
public void deleteComplete(int deletedInstances) {
Log.i(t, "Delete instances complete");
Collect.getInstance().getActivityLogger().logAction(this, "deleteComplete", Integer.toString(deletedInstances));
if (deletedInstances == mSelected.size()) {
// all deletes were successful
Toast.makeText(this,
getString(R.string.file_deleted_ok, deletedInstances),
Toast.LENGTH_SHORT).show();
} else {
// had some failures
Log.e(t, "Failed to delete "
+ (mSelected.size() - deletedInstances) + " instances");
Toast.makeText(
this,
getString(R.string.file_deleted_error, mSelected.size()
- deletedInstances, mSelected.size()),
Toast.LENGTH_LONG).show();
}
mDeleteInstancesTask = null;
mSelected.clear();
getListView().clearChoices(); // doesn't unset the checkboxes
for ( int i = 0 ; i < getListView().getCount() ; ++i ) {
getListView().setItemChecked(i, false);
}
mDeleteButton.setEnabled(false);
}
}
|
0nima0-f
|
src/org/odk/collect/android/activities/DataManagerList.java
|
Java
|
asf20
| 9,602
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.activities;
import java.util.ArrayList;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.DeleteFormsListener;
import org.odk.collect.android.listeners.DiskSyncListener;
import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns;
import org.odk.collect.android.tasks.DeleteFormsTask;
import org.odk.collect.android.tasks.DiskSyncTask;
import org.odk.collect.android.utilities.VersionHidingCursorAdapter;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
/**
* Responsible for displaying and deleting all the valid forms in the forms
* directory.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class FormManagerList extends ListActivity implements DiskSyncListener,
DeleteFormsListener {
private static String t = "FormManagerList";
private static final String SELECTED = "selected";
private static final String syncMsgKey = "syncmsgkey";
private AlertDialog mAlertDialog;
private Button mDeleteButton;
private Button mToggleButton;
private SimpleCursorAdapter mInstances;
private ArrayList<Long> mSelected = new ArrayList<Long>();
static class BackgroundTasks {
DiskSyncTask mDiskSyncTask = null;
DeleteFormsTask mDeleteFormsTask = null;
BackgroundTasks() {
};
}
BackgroundTasks mBackgroundTasks; // handed across orientation changes
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.form_manage_list);
mDeleteButton = (Button) findViewById(R.id.delete_button);
mDeleteButton.setText(getString(R.string.delete_file));
mDeleteButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logAction(this, "deleteButton", Integer.toString(mSelected.size()));
if (mSelected.size() > 0) {
createDeleteFormsDialog();
} else {
Toast.makeText(getApplicationContext(),
R.string.noselect_error, Toast.LENGTH_SHORT).show();
}
}
});
mToggleButton = (Button) findViewById(R.id.toggle_button);
mToggleButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
boolean checkAll = false;
// if everything is checked, uncheck
if (mSelected.size() == mInstances.getCount()) {
checkAll = false;
mSelected.clear();
mDeleteButton.setEnabled(false);
} else {
// otherwise check everything
checkAll = true;
for (int pos = 0; pos < FormManagerList.this.getListView().getCount(); pos++) {
Long id = getListAdapter().getItemId(pos);
if (!mSelected.contains(id)) {
mSelected.add(id);
}
}
mDeleteButton.setEnabled(true);
}
for (int pos = 0; pos < FormManagerList.this.getListView().getCount(); pos++) {
FormManagerList.this.getListView().setItemChecked(pos, checkAll);
}
}
});
String sortOrder = FormsColumns.DISPLAY_NAME + " ASC, " + FormsColumns.JR_VERSION + " DESC";
Cursor c = managedQuery(FormsColumns.CONTENT_URI, null, null, null, sortOrder);
String[] data = new String[] { FormsColumns.DISPLAY_NAME,
FormsColumns.DISPLAY_SUBTEXT, FormsColumns.JR_VERSION };
int[] view = new int[] { R.id.text1, R.id.text2, R.id.text3 };
// render total instance view
mInstances = new VersionHidingCursorAdapter(FormsColumns.JR_VERSION, this,
R.layout.two_item_multiple_choice, c, data, view);
setListAdapter(mInstances);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
getListView().setItemsCanFocus(false);
mDeleteButton.setEnabled(!(mSelected.size() == 0));
if (savedInstanceState != null
&& savedInstanceState.containsKey(syncMsgKey)) {
TextView tv = (TextView) findViewById(R.id.status_text);
tv.setText(savedInstanceState.getString(syncMsgKey));
}
mBackgroundTasks = (BackgroundTasks) getLastNonConfigurationInstance();
if (mBackgroundTasks == null) {
mBackgroundTasks = new BackgroundTasks();
mBackgroundTasks.mDiskSyncTask = new DiskSyncTask();
mBackgroundTasks.mDiskSyncTask.setDiskSyncListener(this);
mBackgroundTasks.mDiskSyncTask.execute((Void[]) null);
}
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
@Override
public Object onRetainNonConfigurationInstance() {
// pass the tasks on restart
return mBackgroundTasks;
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
long[] selectedArray = savedInstanceState.getLongArray(SELECTED);
for (int i = 0; i < selectedArray.length; i++) {
mSelected.add(selectedArray[i]);
}
mDeleteButton.setEnabled(selectedArray.length > 0);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
long[] selectedArray = new long[mSelected.size()];
for (int i = 0; i < mSelected.size(); i++) {
selectedArray[i] = mSelected.get(i);
}
outState.putLongArray(SELECTED, selectedArray);
TextView tv = (TextView) findViewById(R.id.status_text);
outState.putString(syncMsgKey, tv.getText().toString());
}
@Override
protected void onResume() {
// hook up to receive completion events
mBackgroundTasks.mDiskSyncTask.setDiskSyncListener(this);
if (mBackgroundTasks.mDeleteFormsTask != null) {
mBackgroundTasks.mDeleteFormsTask.setDeleteListener(this);
}
super.onResume();
// async task may have completed while we were reorienting...
if (mBackgroundTasks.mDiskSyncTask.getStatus() == AsyncTask.Status.FINISHED) {
SyncComplete(mBackgroundTasks.mDiskSyncTask.getStatusMessage());
}
if (mBackgroundTasks.mDeleteFormsTask != null
&& mBackgroundTasks.mDeleteFormsTask.getStatus() == AsyncTask.Status.FINISHED) {
deleteComplete(mBackgroundTasks.mDeleteFormsTask.getDeleteCount());
}
}
@Override
protected void onPause() {
mBackgroundTasks.mDiskSyncTask.setDiskSyncListener(null);
if (mBackgroundTasks.mDeleteFormsTask != null ) {
mBackgroundTasks.mDeleteFormsTask.setDeleteListener(null);
}
if (mAlertDialog != null && mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
super.onPause();
}
/**
* Create the form delete dialog
*/
private void createDeleteFormsDialog() {
Collect.getInstance().getActivityLogger().logAction(this, "createDeleteFormsDialog", "show");
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setTitle(getString(R.string.delete_file));
mAlertDialog.setMessage(getString(R.string.delete_confirm,
mSelected.size()));
DialogInterface.OnClickListener dialogYesNoListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON_POSITIVE: // delete
Collect.getInstance().getActivityLogger().logAction(this, "createDeleteFormsDialog", "delete");
deleteSelectedForms();
break;
case DialogInterface. BUTTON_NEGATIVE: // do nothing
Collect.getInstance().getActivityLogger().logAction(this, "createDeleteFormsDialog", "cancel");
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.delete_yes),
dialogYesNoListener);
mAlertDialog.setButton2(getString(R.string.delete_no),
dialogYesNoListener);
mAlertDialog.show();
}
/**
* Deletes the selected files.First from the database then from the file
* system
*/
private void deleteSelectedForms() {
// only start if no other task is running
if (mBackgroundTasks.mDeleteFormsTask == null) {
mBackgroundTasks.mDeleteFormsTask = new DeleteFormsTask();
mBackgroundTasks.mDeleteFormsTask
.setContentResolver(getContentResolver());
mBackgroundTasks.mDeleteFormsTask.setDeleteListener(this);
mBackgroundTasks.mDeleteFormsTask.execute(mSelected
.toArray(new Long[mSelected.size()]));
} else {
Toast.makeText(this, getString(R.string.file_delete_in_progress),
Toast.LENGTH_LONG).show();
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// get row id from db
Cursor c = (Cursor) getListAdapter().getItem(position);
long k = c.getLong(c.getColumnIndex(FormsColumns._ID));
// add/remove from selected list
if (mSelected.contains(k))
mSelected.remove(k);
else
mSelected.add(k);
Collect.getInstance().getActivityLogger().logAction(this, "onListItemClick", Long.toString(k));
mDeleteButton.setEnabled(!(mSelected.size() == 0));
}
@Override
public void SyncComplete(String result) {
Log.i(t, "Disk scan complete");
TextView tv = (TextView) findViewById(R.id.status_text);
tv.setText(result);
}
@Override
public void deleteComplete(int deletedForms) {
Log.i(t, "Delete forms complete");
Collect.getInstance().getActivityLogger().logAction(this, "deleteComplete", Integer.toString(deletedForms));
if (deletedForms == mSelected.size()) {
// all deletes were successful
Toast.makeText(getApplicationContext(),
getString(R.string.file_deleted_ok, deletedForms),
Toast.LENGTH_SHORT).show();
} else {
// had some failures
Log.e(t, "Failed to delete " + (mSelected.size() - deletedForms)
+ " forms");
Toast.makeText(
getApplicationContext(),
getString(R.string.file_deleted_error, mSelected.size()
- deletedForms, mSelected.size()),
Toast.LENGTH_LONG).show();
}
mBackgroundTasks.mDeleteFormsTask = null;
mSelected.clear();
getListView().clearChoices(); // doesn't unset the checkboxes
for ( int i = 0 ; i < getListView().getCount() ; ++i ) {
getListView().setItemChecked(i, false);
}
mDeleteButton.setEnabled(false);
}
}
|
0nima0-f
|
src/org/odk/collect/android/activities/FormManagerList.java
|
Java
|
asf20
| 11,377
|
/*
* Copyright (C) 2014 Nafundi
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Activity to upload completed forms to gme.
*
* @author Carl Hartung (chartung@nafundi.com)
*/
package org.odk.collect.android.activities;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.InstanceUploaderListener;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import org.odk.collect.android.tasks.GoogleMapsEngineAbstractUploader;
import org.odk.collect.android.tasks.GoogleMapsEngineTask;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GooglePlayServicesAvailabilityException;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.android.gms.common.GooglePlayServicesUtil;
public class GoogleMapsEngineUploaderActivity extends Activity implements
InstanceUploaderListener {
private final static String tag = "GoogleMapsEngineUploaderActivity";
private final static int PROGRESS_DIALOG = 1;
private final static int GOOGLE_USER_DIALOG = 3;
private static final String ALERT_MSG = "alertmsg";
private static final String ALERT_SHOWING = "alertshowing";
private ProgressDialog mProgressDialog;
private AlertDialog mAlertDialog;
private String mAlertMsg;
private boolean mAlertShowing;
private Long[] mInstancesToSend;
private GoogleMapsEngineInstanceUploaderTask mUlTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(tag, "onCreate: "
+ ((savedInstanceState == null) ? "creating"
: "re-initializing"));
// if we start this activity, the following must be true:
// 1) Google Maps Engine is selected in preferences
// 2) A google user is selected
// default initializers
mAlertMsg = getString(R.string.please_wait);
mAlertShowing = false;
setTitle(getString(R.string.app_name) + " > "
+ getString(R.string.send_data)); // get any simple saved
// state...
// resets alert message and showing dialog if the screen is rotated
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(ALERT_MSG)) {
mAlertMsg = savedInstanceState.getString(ALERT_MSG);
}
if (savedInstanceState.containsKey(ALERT_SHOWING)) {
mAlertShowing = savedInstanceState.getBoolean(ALERT_SHOWING,
false);
}
}
long[] selectedInstanceIDs = null;
Intent intent = getIntent();
selectedInstanceIDs = intent
.getLongArrayExtra(FormEntryActivity.KEY_INSTANCES);
mInstancesToSend = new Long[(selectedInstanceIDs == null) ? 0
: selectedInstanceIDs.length];
if (selectedInstanceIDs != null) {
for (int i = 0; i < selectedInstanceIDs.length; ++i) {
mInstancesToSend[i] = selectedInstanceIDs[i];
}
}
// at this point,
// we don't expect this to be empty...
if (mInstancesToSend.length == 0) {
Log.e(tag, "onCreate: No instances to upload!");
// drop through --
// everything will process through OK
} else {
Log.i(tag, "onCreate: Beginning upload of "
+ mInstancesToSend.length + " instances!");
}
runTask();
}
private void runTask() {
mUlTask = (GoogleMapsEngineInstanceUploaderTask) getLastNonConfigurationInstance();
if (mUlTask == null) {
mUlTask = new GoogleMapsEngineInstanceUploaderTask();
// ensure we have a google account selected
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
String googleUsername = prefs.getString(
PreferencesActivity.KEY_SELECTED_GOOGLE_ACCOUNT, null);
if (googleUsername == null || googleUsername.equals("")) {
showDialog(GOOGLE_USER_DIALOG);
return;
}
// setup dialog and upload task
showDialog(PROGRESS_DIALOG);
mUlTask.setUserName(googleUsername);
mUlTask.setUploaderListener(this);
mUlTask.execute(mInstancesToSend);
} else {
// it's not null, so we have a task running
// progress dialog is handled by the system
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GoogleMapsEngineTask.PLAYSTORE_REQUEST_CODE
&& resultCode == RESULT_OK) {
// the user got sent to the playstore
// it returns to this activity, but we'd rather they manually retry
// so we finish
finish();
} else if (requestCode == GoogleMapsEngineTask.USER_RECOVERABLE_REQUEST_CODE
&& resultCode == RESULT_OK) {
// authorization granted, try again
runTask();
} else if (requestCode == GoogleMapsEngineTask.USER_RECOVERABLE_REQUEST_CODE
&& resultCode == RESULT_CANCELED) {
// the user backed out
finish();
} else {
Log.e(tag, "unknown request: " + requestCode + " :: result: "
+ resultCode);
}
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onResume() {
if (mUlTask != null) {
mUlTask.setUploaderListener(this);
}
if (mAlertShowing) {
createAlertDialog(mAlertMsg);
}
super.onResume();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(ALERT_MSG, mAlertMsg);
outState.putBoolean(ALERT_SHOWING, mAlertShowing);
}
@Override
public Object onRetainNonConfigurationInstance() {
return mUlTask;
}
@Override
protected void onPause() {
super.onPause();
if (mAlertDialog != null && mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
@Override
protected void onDestroy() {
if (mUlTask != null) {
mUlTask.setUploaderListener(null);
}
super.onDestroy();
}
@Override
public void uploadingComplete(HashMap<String, String> result) {
try {
dismissDialog(PROGRESS_DIALOG);
} catch (Exception e) {
// tried to close a dialog not open. don't care.
}
if (result == null) {
// probably got an auth request, so ignore
return;
}
Log.i(tag, "uploadingComplete: Processing results (" + result.size()
+ ") from upload of " + mInstancesToSend.length + " instances!");
StringBuilder selection = new StringBuilder();
Set<String> keys = result.keySet();
StringBuilder message = new StringBuilder();
if (keys.size() == 0) {
message.append(getString(R.string.no_forms_uploaded));
} else {
Iterator<String> it = keys.iterator();
String[] selectionArgs = new String[keys.size()];
int i = 0;
while (it.hasNext()) {
String id = it.next();
selection.append(InstanceColumns._ID + "=?");
selectionArgs[i++] = id;
if (i != keys.size()) {
selection.append(" or ");
}
}
Cursor results = null;
try {
results = getContentResolver().query(
InstanceColumns.CONTENT_URI, null,
selection.toString(), selectionArgs, null);
if (results.getCount() > 0) {
results.moveToPosition(-1);
while (results.moveToNext()) {
String name = results.getString(results
.getColumnIndex(InstanceColumns.DISPLAY_NAME));
String id = results.getString(results
.getColumnIndex(InstanceColumns._ID));
message.append(name + " - " + result.get(id) + "\n\n");
}
} else {
message.append(getString(R.string.no_forms_uploaded));
}
} finally {
if (results != null) {
results.close();
}
}
}
createAlertDialog(message.toString().trim());
}
@Override
public void progressUpdate(int progress, int total) {
mAlertMsg = getString(R.string.sending_items, progress, total);
mProgressDialog.setMessage(mAlertMsg);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
Collect.getInstance().getActivityLogger()
.logAction(this, "onCreateDialog.PROGRESS_DIALOG", "show");
mProgressDialog = new ProgressDialog(this);
DialogInterface.OnClickListener loadingButtonListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance()
.getActivityLogger()
.logAction(this, "onCreateDialog.PROGRESS_DIALOG",
"cancel");
dialog.dismiss();
mUlTask.cancel(true);
mUlTask.setUploaderListener(null);
finish();
}
};
mProgressDialog.setTitle(getString(R.string.uploading_data));
mProgressDialog.setMessage(mAlertMsg);
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setCancelable(false);
mProgressDialog.setButton(getString(R.string.cancel),
loadingButtonListener);
return mProgressDialog;
case GOOGLE_USER_DIALOG:
AlertDialog.Builder gudBuilder = new AlertDialog.Builder(this);
gudBuilder.setTitle(getString(R.string.no_google_account));
gudBuilder.setMessage(getString(R.string.gme_set_account));
gudBuilder.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
gudBuilder.setCancelable(false);
return gudBuilder.create();
}
return null;
}
private void createAlertDialog(String message) {
Collect.getInstance().getActivityLogger()
.logAction(this, "createAlertDialog", "show");
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setTitle(getString(R.string.upload_results));
mAlertDialog.setMessage(message);
DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON1: // ok
Collect.getInstance().getActivityLogger()
.logAction(this, "createAlertDialog", "OK");
// always exit this activity since it has no interface
mAlertShowing = false;
finish();
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.ok), quitListener);
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertShowing = true;
mAlertMsg = message;
mAlertDialog.show();
}
public class GoogleMapsEngineInstanceUploaderTask
extends
GoogleMapsEngineAbstractUploader<Long, Integer, HashMap<String, String>> {
@Override
protected HashMap<String, String> doInBackground(Long... values) {
mResults = new HashMap<String, String>();
String selection = InstanceColumns._ID + "=?";
String[] selectionArgs = new String[(values == null) ? 0
: values.length];
if (values != null) {
for (int i = 0; i < values.length; i++) {
if (i != values.length - 1) {
selection += " or " + InstanceColumns._ID + "=?";
}
selectionArgs[i] = values[i].toString();
}
}
String token = null;
try {
token = authenticate(GoogleMapsEngineUploaderActivity.this, mGoogleUserName);
} catch (IOException e) {
// network or server error, the call is expected to succeed if
// you try again later. Don't attempt to call again immediately
// - the request is likely to fail, you'll hit quotas or
// back-off.
e.printStackTrace();
mResults.put("0", oauth_fail + e.getMessage());
return mResults;
} catch (GooglePlayServicesAvailabilityException playEx) {
Dialog alert = GooglePlayServicesUtil.getErrorDialog(
playEx.getConnectionStatusCode(), GoogleMapsEngineUploaderActivity.this,
PLAYSTORE_REQUEST_CODE);
alert.show();
return null;
} catch (UserRecoverableAuthException e) {
GoogleMapsEngineUploaderActivity.this.startActivityForResult(e.getIntent(),
USER_RECOVERABLE_REQUEST_CODE);
e.printStackTrace();
return null;
} catch (GoogleAuthException e) {
// Failure. The call is not expected to ever succeed so it
// should not be retried.
e.printStackTrace();
mResults.put("0", oauth_fail + e.getMessage());
return mResults;
}
if (token == null) {
// if token is null,
return null;
}
uploadInstances(selection, selectionArgs, token);
return mResults;
}
}
@Override
public void authRequest(Uri url, HashMap<String, String> doneSoFar) {
// this shouldn't be in the interface...
}
}
|
0nima0-f
|
src/org/odk/collect/android/activities/GoogleMapsEngineUploaderActivity.java
|
Java
|
asf20
| 13,425
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.activities;
import java.io.File;
import java.io.FileFilter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.instance.TreeElement;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryController;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.exception.JavaRosaException;
import org.odk.collect.android.listeners.AdvanceToNextListener;
import org.odk.collect.android.listeners.FormLoaderListener;
import org.odk.collect.android.listeners.FormSavedListener;
import org.odk.collect.android.listeners.SavePointListener;
import org.odk.collect.android.logic.FormController;
import org.odk.collect.android.logic.FormController.FailedConstraint;
import org.odk.collect.android.preferences.AdminPreferencesActivity;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns;
import org.odk.collect.android.provider.InstanceProviderAPI;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import org.odk.collect.android.tasks.FormLoaderTask;
import org.odk.collect.android.tasks.SavePointTask;
import org.odk.collect.android.tasks.SaveResult;
import org.odk.collect.android.tasks.SaveToDiskTask;
import org.odk.collect.android.utilities.CompatibilityUtils;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.utilities.MediaUtils;
import org.odk.collect.android.views.ODKView;
import org.odk.collect.android.widgets.QuestionWidget;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore.Images;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
* FormEntryActivity is responsible for displaying questions, animating
* transitions between questions, and allowing the user to enter data.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Thomas Smyth, Sassafras Tech Collective (tom@sassafrastech.com; constraint behavior option)
*/
public class FormEntryActivity extends Activity implements AnimationListener,
FormLoaderListener, FormSavedListener, AdvanceToNextListener,
OnGestureListener, SavePointListener {
private static final String t = "FormEntryActivity";
// save with every swipe forward or back. Timings indicate this takes .25
// seconds.
// if it ever becomes an issue, this value can be changed to save every n'th
// screen.
private static final int SAVEPOINT_INTERVAL = 1;
// Defines for FormEntryActivity
private static final boolean EXIT = true;
private static final boolean DO_NOT_EXIT = false;
private static final boolean EVALUATE_CONSTRAINTS = true;
private static final boolean DO_NOT_EVALUATE_CONSTRAINTS = false;
// Request codes for returning data from specified intent.
public static final int IMAGE_CAPTURE = 1;
public static final int BARCODE_CAPTURE = 2;
public static final int AUDIO_CAPTURE = 3;
public static final int VIDEO_CAPTURE = 4;
public static final int LOCATION_CAPTURE = 5;
public static final int HIERARCHY_ACTIVITY = 6;
public static final int IMAGE_CHOOSER = 7;
public static final int AUDIO_CHOOSER = 8;
public static final int VIDEO_CHOOSER = 9;
public static final int EX_STRING_CAPTURE = 10;
public static final int EX_INT_CAPTURE = 11;
public static final int EX_DECIMAL_CAPTURE = 12;
public static final int DRAW_IMAGE = 13;
public static final int SIGNATURE_CAPTURE = 14;
public static final int ANNOTATE_IMAGE = 15;
public static final int ALIGNED_IMAGE = 16;
public static final int BEARING_CAPTURE = 17;
public static final int EX_GROUP_CAPTURE = 18;
// Extra returned from gp activity
public static final String LOCATION_RESULT = "LOCATION_RESULT";
public static final String BEARING_RESULT = "BEARING_RESULT";
public static final String KEY_INSTANCES = "instances";
public static final String KEY_SUCCESS = "success";
public static final String KEY_ERROR = "error";
// Identifies the gp of the form used to launch form entry
public static final String KEY_FORMPATH = "formpath";
// Identifies whether this is a new form, or reloading a form after a screen
// rotation (or similar)
private static final String NEWFORM = "newform";
// these are only processed if we shut down and are restoring after an
// external intent fires
public static final String KEY_INSTANCEPATH = "instancepath";
public static final String KEY_XPATH = "xpath";
public static final String KEY_XPATH_WAITING_FOR_DATA = "xpathwaiting";
// Tracks whether we are autosaving
public static final String KEY_AUTO_SAVED = "autosaved";
private static final int MENU_LANGUAGES = Menu.FIRST;
private static final int MENU_HIERARCHY_VIEW = Menu.FIRST + 1;
private static final int MENU_SAVE = Menu.FIRST + 2;
private static final int MENU_PREFERENCES = Menu.FIRST + 3;
private static final int PROGRESS_DIALOG = 1;
private static final int SAVING_DIALOG = 2;
private boolean mAutoSaved;
// Random ID
private static final int DELETE_REPEAT = 654321;
private String mFormPath;
private GestureDetector mGestureDetector;
private Animation mInAnimation;
private Animation mOutAnimation;
private View mStaleView = null;
private LinearLayout mQuestionHolder;
private View mCurrentView;
private AlertDialog mAlertDialog;
private ProgressDialog mProgressDialog;
private String mErrorMessage;
// used to limit forward/backward swipes to one per question
private boolean mBeenSwiped = false;
private final Object saveDialogLock = new Object();
private int viewCount = 0;
private FormLoaderTask mFormLoaderTask;
private SaveToDiskTask mSaveToDiskTask;
private ImageButton mNextButton;
private ImageButton mBackButton;
private String stepMessage = "";
enum AnimationType {
LEFT, RIGHT, FADE
}
private SharedPreferences mAdminPreferences;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// must be at the beginning of any activity that can be called from an
// external intent
try {
Collect.createODKDirs();
} catch (RuntimeException e) {
createErrorDialog(e.getMessage(), EXIT);
return;
}
setContentView(R.layout.form_entry);
setTitle(getString(R.string.app_name) + " > "
+ getString(R.string.loading_form));
mErrorMessage = null;
mBeenSwiped = false;
mAlertDialog = null;
mCurrentView = null;
mInAnimation = null;
mOutAnimation = null;
mGestureDetector = new GestureDetector(this, this);
mQuestionHolder = (LinearLayout) findViewById(R.id.questionholder);
// get admin preference settings
mAdminPreferences = getSharedPreferences(
AdminPreferencesActivity.ADMIN_PREFERENCES, 0);
mNextButton = (ImageButton) findViewById(R.id.form_forward_button);
mNextButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mBeenSwiped = true;
showNextView();
}
});
mBackButton = (ImageButton) findViewById(R.id.form_back_button);
mBackButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mBeenSwiped = true;
showPreviousView();
}
});
String startingXPath = null;
String waitingXPath = null;
String instancePath = null;
Boolean newForm = true;
mAutoSaved = false;
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(KEY_FORMPATH)) {
mFormPath = savedInstanceState.getString(KEY_FORMPATH);
}
if (savedInstanceState.containsKey(KEY_INSTANCEPATH)) {
instancePath = savedInstanceState.getString(KEY_INSTANCEPATH);
}
if (savedInstanceState.containsKey(KEY_XPATH)) {
startingXPath = savedInstanceState.getString(KEY_XPATH);
Log.i(t, "startingXPath is: " + startingXPath);
}
if (savedInstanceState.containsKey(KEY_XPATH_WAITING_FOR_DATA)) {
waitingXPath = savedInstanceState
.getString(KEY_XPATH_WAITING_FOR_DATA);
Log.i(t, "waitingXPath is: " + waitingXPath);
}
if (savedInstanceState.containsKey(NEWFORM)) {
newForm = savedInstanceState.getBoolean(NEWFORM, true);
}
if (savedInstanceState.containsKey(KEY_ERROR)) {
mErrorMessage = savedInstanceState.getString(KEY_ERROR);
}
if (savedInstanceState.containsKey(KEY_AUTO_SAVED)) {
mAutoSaved = savedInstanceState.getBoolean(KEY_AUTO_SAVED);
}
}
// If a parse error message is showing then nothing else is loaded
// Dialogs mid form just disappear on rotation.
if (mErrorMessage != null) {
createErrorDialog(mErrorMessage, EXIT);
return;
}
// Check to see if this is a screen flip or a new form load.
Object data = getLastNonConfigurationInstance();
if (data instanceof FormLoaderTask) {
mFormLoaderTask = (FormLoaderTask) data;
} else if (data instanceof SaveToDiskTask) {
mSaveToDiskTask = (SaveToDiskTask) data;
} else if (data == null) {
if (!newForm) {
if (Collect.getInstance().getFormController() != null) {
refreshCurrentView();
} else {
Log.w(t, "Reloading form and restoring state.");
// we need to launch the form loader to load the form
// controller...
mFormLoaderTask = new FormLoaderTask(instancePath,
startingXPath, waitingXPath);
Collect.getInstance().getActivityLogger()
.logAction(this, "formReloaded", mFormPath);
// TODO: this doesn' work (dialog does not get removed):
// showDialog(PROGRESS_DIALOG);
// show dialog before we execute...
mFormLoaderTask.execute(mFormPath);
}
return;
}
// Not a restart from a screen orientation change (or other).
Collect.getInstance().setFormController(null);
CompatibilityUtils.invalidateOptionsMenu(this);
Intent intent = getIntent();
if (intent != null) {
Uri uri = intent.getData();
if (getContentResolver().getType(uri).equals(InstanceColumns.CONTENT_ITEM_TYPE)) {
// get the formId and version for this instance...
String jrFormId = null;
String jrVersion = null;
{
Cursor instanceCursor = null;
try {
instanceCursor = getContentResolver().query(uri,
null, null, null, null);
if (instanceCursor.getCount() != 1) {
this.createErrorDialog("Bad URI: " + uri, EXIT);
return;
} else {
instanceCursor.moveToFirst();
instancePath = instanceCursor
.getString(instanceCursor
.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
Collect.getInstance()
.getActivityLogger()
.logAction(this, "instanceLoaded",
instancePath);
jrFormId = instanceCursor
.getString(instanceCursor
.getColumnIndex(InstanceColumns.JR_FORM_ID));
int idxJrVersion = instanceCursor
.getColumnIndex(InstanceColumns.JR_VERSION);
jrVersion = instanceCursor.isNull(idxJrVersion) ? null
: instanceCursor
.getString(idxJrVersion);
}
} finally {
if (instanceCursor != null) {
instanceCursor.close();
}
}
}
String[] selectionArgs;
String selection;
if (jrVersion == null) {
selectionArgs = new String[] { jrFormId };
selection = FormsColumns.JR_FORM_ID + "=? AND "
+ FormsColumns.JR_VERSION + " IS NULL";
} else {
selectionArgs = new String[] { jrFormId, jrVersion };
selection = FormsColumns.JR_FORM_ID + "=? AND "
+ FormsColumns.JR_VERSION + "=?";
}
{
Cursor formCursor = null;
try {
formCursor = getContentResolver().query(
FormsColumns.CONTENT_URI, null, selection,
selectionArgs, null);
if (formCursor.getCount() == 1) {
formCursor.moveToFirst();
mFormPath = formCursor
.getString(formCursor
.getColumnIndex(FormsColumns.FORM_FILE_PATH));
} else if (formCursor.getCount() < 1) {
this.createErrorDialog(
getString(
R.string.parent_form_not_present,
jrFormId)
+ ((jrVersion == null) ? ""
: "\n"
+ getString(R.string.version)
+ " "
+ jrVersion),
EXIT);
return;
} else if (formCursor.getCount() > 1) {
// still take the first entry, but warn that
// there are multiple rows.
// user will need to hand-edit the SQLite
// database to fix it.
formCursor.moveToFirst();
mFormPath = formCursor.getString(formCursor.getColumnIndex(FormsColumns.FORM_FILE_PATH));
this.createErrorDialog(getString(R.string.survey_multiple_forms_error), EXIT);
return;
}
} finally {
if (formCursor != null) {
formCursor.close();
}
}
}
} else if (getContentResolver().getType(uri).equals(FormsColumns.CONTENT_ITEM_TYPE)) {
Cursor c = null;
try {
c = getContentResolver().query(uri, null, null, null,
null);
if (c.getCount() != 1) {
this.createErrorDialog("Bad URI: " + uri, EXIT);
return;
} else {
c.moveToFirst();
mFormPath = c.getString(c.getColumnIndex(FormsColumns.FORM_FILE_PATH));
// This is the fill-blank-form code path.
// See if there is a savepoint for this form that
// has never been
// explicitly saved
// by the user. If there is, open this savepoint
// (resume this filled-in
// form).
// Savepoints for forms that were explicitly saved
// will be recovered
// when that
// explicitly saved instance is edited via
// edit-saved-form.
final String filePrefix = mFormPath.substring(
mFormPath.lastIndexOf('/') + 1,
mFormPath.lastIndexOf('.'))
+ "_";
final String fileSuffix = ".xml.save";
File cacheDir = new File(Collect.CACHE_PATH);
File[] files = cacheDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
String name = pathname.getName();
return name.startsWith(filePrefix)
&& name.endsWith(fileSuffix);
}
});
// see if any of these savepoints are for a
// filled-in form that has never been
// explicitly saved by the user...
for (int i = 0; i < files.length; ++i) {
File candidate = files[i];
String instanceDirName = candidate.getName()
.substring(
0,
candidate.getName().length()
- fileSuffix.length());
File instanceDir = new File(
Collect.INSTANCES_PATH + File.separator
+ instanceDirName);
File instanceFile = new File(instanceDir,
instanceDirName + ".xml");
if (instanceDir.exists()
&& instanceDir.isDirectory()
&& !instanceFile.exists()) {
// yes! -- use this savepoint file
instancePath = instanceFile
.getAbsolutePath();
break;
}
}
}
} finally {
if (c != null) {
c.close();
}
}
} else {
Log.e(t, "unrecognized URI");
this.createErrorDialog("Unrecognized URI: " + uri, EXIT);
return;
}
mFormLoaderTask = new FormLoaderTask(instancePath, null, null);
Collect.getInstance().getActivityLogger()
.logAction(this, "formLoaded", mFormPath);
showDialog(PROGRESS_DIALOG);
// show dialog before we execute...
mFormLoaderTask.execute(mFormPath);
}
}
}
/**
* Create save-points asynchronously in order to not affect swiping performance
* on larger forms.
*/
private void nonblockingCreateSavePointData() {
try {
SavePointTask savePointTask = new SavePointTask(this);
savePointTask.execute();
} catch (Exception e) {
Log.e(t, "Could not schedule SavePointTask. Perhaps a lot of swiping is taking place?");
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_FORMPATH, mFormPath);
FormController formController = Collect.getInstance()
.getFormController();
if (formController != null) {
outState.putString(KEY_INSTANCEPATH, formController
.getInstancePath().getAbsolutePath());
outState.putString(KEY_XPATH,
formController.getXPath(formController.getFormIndex()));
FormIndex waiting = formController.getIndexWaitingForData();
if (waiting != null) {
outState.putString(KEY_XPATH_WAITING_FOR_DATA,
formController.getXPath(waiting));
}
// save the instance to a temp path...
nonblockingCreateSavePointData();
}
outState.putBoolean(NEWFORM, false);
outState.putString(KEY_ERROR, mErrorMessage);
outState.putBoolean(KEY_AUTO_SAVED, mAutoSaved);
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
FormController formController = Collect.getInstance()
.getFormController();
if (formController == null) {
// we must be in the midst of a reload of the FormController.
// try to save this callback data to the FormLoaderTask
if (mFormLoaderTask != null
&& mFormLoaderTask.getStatus() != AsyncTask.Status.FINISHED) {
mFormLoaderTask.setActivityResult(requestCode, resultCode,
intent);
} else {
Log.e(t,
"Got an activityResult without any pending form loader");
}
return;
}
if (resultCode == RESULT_CANCELED) {
// request was canceled...
if (requestCode != HIERARCHY_ACTIVITY) {
((ODKView) mCurrentView).cancelWaitingForBinaryData();
}
return;
}
switch (requestCode) {
case BARCODE_CAPTURE:
String sb = intent.getStringExtra("SCAN_RESULT");
((ODKView) mCurrentView).setBinaryData(sb);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case EX_STRING_CAPTURE:
case EX_INT_CAPTURE:
case EX_DECIMAL_CAPTURE:
String key = "value";
boolean exists = intent.getExtras().containsKey(key);
if (exists) {
Object externalValue = intent.getExtras().get(key);
((ODKView) mCurrentView).setBinaryData(externalValue);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
break;
case EX_GROUP_CAPTURE:
try {
Bundle extras = intent.getExtras();
((ODKView) mCurrentView).setDataForFields(extras);
} catch (JavaRosaException e) {
Log.e(t, e.getMessage(), e);
createErrorDialog(e.getCause().getMessage(), DO_NOT_EXIT);
}
break;
case DRAW_IMAGE:
case ANNOTATE_IMAGE:
case SIGNATURE_CAPTURE:
case IMAGE_CAPTURE:
/*
* We saved the image to the tempfile_path, but we really want it to
* be in: /sdcard/odk/instances/[current instnace]/something.jpg so
* we move it there before inserting it into the content provider.
* Once the android image capture bug gets fixed, (read, we move on
* from Android 1.6) we want to handle images the audio and video
*/
// The intent is empty, but we know we saved the image to the temp
// file
File fi = new File(Collect.TMPFILE_PATH);
String mInstanceFolder = formController.getInstancePath()
.getParent();
String s = mInstanceFolder + File.separator
+ System.currentTimeMillis() + ".jpg";
File nf = new File(s);
if (!fi.renameTo(nf)) {
Log.e(t, "Failed to rename " + fi.getAbsolutePath());
} else {
Log.i(t,
"renamed " + fi.getAbsolutePath() + " to "
+ nf.getAbsolutePath());
}
((ODKView) mCurrentView).setBinaryData(nf);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case ALIGNED_IMAGE:
/*
* We saved the image to the tempfile_path; the app returns the full
* path to the saved file in the EXTRA_OUTPUT extra. Take that file
* and move it into the instance folder.
*/
String path = intent
.getStringExtra(android.provider.MediaStore.EXTRA_OUTPUT);
fi = new File(path);
mInstanceFolder = formController.getInstancePath().getParent();
s = mInstanceFolder + File.separator + System.currentTimeMillis()
+ ".jpg";
nf = new File(s);
if (!fi.renameTo(nf)) {
Log.e(t, "Failed to rename " + fi.getAbsolutePath());
} else {
Log.i(t,
"renamed " + fi.getAbsolutePath() + " to "
+ nf.getAbsolutePath());
}
((ODKView) mCurrentView).setBinaryData(nf);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case IMAGE_CHOOSER:
/*
* We have a saved image somewhere, but we really want it to be in:
* /sdcard/odk/instances/[current instnace]/something.jpg so we move
* it there before inserting it into the content provider. Once the
* android image capture bug gets fixed, (read, we move on from
* Android 1.6) we want to handle images the audio and video
*/
// get gp of chosen file
Uri selectedImage = intent.getData();
String sourceImagePath = MediaUtils.getPathFromUri(this, selectedImage, Images.Media.DATA);
// Copy file to sdcard
String mInstanceFolder1 = formController.getInstancePath()
.getParent();
String destImagePath = mInstanceFolder1 + File.separator
+ System.currentTimeMillis() + ".jpg";
File source = new File(sourceImagePath);
File newImage = new File(destImagePath);
FileUtils.copyFile(source, newImage);
((ODKView) mCurrentView).setBinaryData(newImage);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case AUDIO_CAPTURE:
case VIDEO_CAPTURE:
case AUDIO_CHOOSER:
case VIDEO_CHOOSER:
// For audio/video capture/chooser, we get the URI from the content
// provider
// then the widget copies the file and makes a new entry in the
// content provider.
Uri media = intent.getData();
((ODKView) mCurrentView).setBinaryData(media);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case LOCATION_CAPTURE:
String sl = intent.getStringExtra(LOCATION_RESULT);
((ODKView) mCurrentView).setBinaryData(sl);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case BEARING_CAPTURE:
String bearing = intent.getStringExtra(BEARING_RESULT);
((ODKView) mCurrentView).setBinaryData(bearing);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
case HIERARCHY_ACTIVITY:
// We may have jumped to a new index in hierarchy activity, so
// refresh
break;
}
refreshCurrentView();
}
/**
* Refreshes the current view. the controller and the displayed view can get
* out of sync due to dialogs and restarts caused by screen orientation
* changes, so they're resynchronized here.
*/
public void refreshCurrentView() {
FormController formController = Collect.getInstance()
.getFormController();
int event = formController.getEvent();
// When we refresh, repeat dialog state isn't maintained, so step back
// to the previous
// question.
// Also, if we're within a group labeled 'field list', step back to the
// beginning of that
// group.
// That is, skip backwards over repeat prompts, groups that are not
// field-lists,
// repeat events, and indexes in field-lists that is not the containing
// group.
if (event == FormEntryController.EVENT_PROMPT_NEW_REPEAT) {
createRepeatDialog();
} else {
View current = createView(event, false);
showView(current, AnimationType.FADE);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "onCreateOptionsMenu", "show");
super.onCreateOptionsMenu(menu);
CompatibilityUtils.setShowAsAction(
menu.add(0, MENU_SAVE, 0, R.string.save_all_answers).setIcon(
android.R.drawable.ic_menu_save),
MenuItem.SHOW_AS_ACTION_IF_ROOM);
CompatibilityUtils.setShowAsAction(
menu.add(0, MENU_HIERARCHY_VIEW, 0, R.string.view_hierarchy)
.setIcon(R.drawable.ic_menu_goto),
MenuItem.SHOW_AS_ACTION_IF_ROOM);
CompatibilityUtils.setShowAsAction(
menu.add(0, MENU_LANGUAGES, 0, R.string.change_language)
.setIcon(R.drawable.ic_menu_start_conversation),
MenuItem.SHOW_AS_ACTION_NEVER);
CompatibilityUtils.setShowAsAction(
menu.add(0, MENU_PREFERENCES, 0, R.string.general_preferences)
.setIcon(R.drawable.ic_menu_preferences),
MenuItem.SHOW_AS_ACTION_NEVER);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
FormController formController = Collect.getInstance()
.getFormController();
boolean useability;
useability = mAdminPreferences.getBoolean(
AdminPreferencesActivity.KEY_SAVE_MID, true);
menu.findItem(MENU_SAVE).setVisible(useability).setEnabled(useability);
useability = mAdminPreferences.getBoolean(
AdminPreferencesActivity.KEY_JUMP_TO, true);
menu.findItem(MENU_HIERARCHY_VIEW).setVisible(useability)
.setEnabled(useability);
useability = mAdminPreferences.getBoolean(
AdminPreferencesActivity.KEY_CHANGE_LANGUAGE, true)
&& (formController != null)
&& formController.getLanguages() != null
&& formController.getLanguages().length > 1;
menu.findItem(MENU_LANGUAGES).setVisible(useability)
.setEnabled(useability);
useability = mAdminPreferences.getBoolean(
AdminPreferencesActivity.KEY_ACCESS_SETTINGS, true);
menu.findItem(MENU_PREFERENCES).setVisible(useability)
.setEnabled(useability);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
FormController formController = Collect.getInstance()
.getFormController();
switch (item.getItemId()) {
case MENU_LANGUAGES:
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onOptionsItemSelected",
"MENU_LANGUAGES");
createLanguageDialog();
return true;
case MENU_SAVE:
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onOptionsItemSelected",
"MENU_SAVE");
// don't exit
saveDataToDisk(DO_NOT_EXIT, isInstanceComplete(false), null);
return true;
case MENU_HIERARCHY_VIEW:
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onOptionsItemSelected",
"MENU_HIERARCHY_VIEW");
if (formController.currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
Intent i = new Intent(this, FormHierarchyActivity.class);
startActivityForResult(i, HIERARCHY_ACTIVITY);
return true;
case MENU_PREFERENCES:
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onOptionsItemSelected",
"MENU_PREFERENCES");
Intent pref = new Intent(this, PreferencesActivity.class);
startActivity(pref);
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Attempt to save the answer(s) in the current screen to into the data
* model.
*
* @param evaluateConstraints
* @return false if any error occurs while saving (constraint violated,
* etc...), true otherwise.
*/
private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints) {
FormController formController = Collect.getInstance()
.getFormController();
// only try to save if the current event is a question or a field-list
// group
if (formController.currentPromptIsQuestion()) {
LinkedHashMap<FormIndex, IAnswerData> answers = ((ODKView) mCurrentView)
.getAnswers();
try {
FailedConstraint constraint = formController.saveAllScreenAnswers(answers, evaluateConstraints);
if (constraint != null) {
createConstraintToast(constraint.index, constraint.status);
return false;
}
} catch (JavaRosaException e) {
Log.e(t, e.getMessage(), e);
createErrorDialog(e.getCause().getMessage(), DO_NOT_EXIT);
return false;
}
}
return true;
}
/**
* Clears the answer on the screen.
*/
private void clearAnswer(QuestionWidget qw) {
if (qw.getAnswer() != null) {
qw.clearAnswer();
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "onCreateContextMenu", "show");
FormController formController = Collect.getInstance()
.getFormController();
menu.add(0, v.getId(), 0, getString(R.string.clear_answer));
if (formController.indexContainsRepeatableGroup()) {
menu.add(0, DELETE_REPEAT, 0, getString(R.string.delete_repeat));
}
menu.setHeaderTitle(getString(R.string.edit_prompt));
}
@Override
public boolean onContextItemSelected(MenuItem item) {
/*
* We don't have the right view here, so we store the View's ID as the
* item ID and loop through the possible views to find the one the user
* clicked on.
*/
for (QuestionWidget qw : ((ODKView) mCurrentView).getWidgets()) {
if (item.getItemId() == qw.getId()) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onContextItemSelected",
"createClearDialog", qw.getPrompt().getIndex());
createClearDialog(qw);
}
}
if (item.getItemId() == DELETE_REPEAT) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onContextItemSelected",
"createDeleteRepeatConfirmDialog");
createDeleteRepeatConfirmDialog();
}
return super.onContextItemSelected(item);
}
/**
* If we're loading, then we pass the loading thread to our next instance.
*/
@Override
public Object onRetainNonConfigurationInstance() {
FormController formController = Collect.getInstance()
.getFormController();
// if a form is loading, pass the loader task
if (mFormLoaderTask != null
&& mFormLoaderTask.getStatus() != AsyncTask.Status.FINISHED)
return mFormLoaderTask;
// if a form is writing to disk, pass the save to disk task
if (mSaveToDiskTask != null
&& mSaveToDiskTask.getStatus() != AsyncTask.Status.FINISHED)
return mSaveToDiskTask;
// mFormEntryController is static so we don't need to pass it.
if (formController != null && formController.currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
return null;
}
/**
* Creates a view given the View type and an event
*
* @param event
* @param advancingPage
* -- true if this results from advancing through the form
* @return newly created View
*/
private View createView(int event, boolean advancingPage) {
FormController formController = Collect.getInstance()
.getFormController();
setTitle(getString(R.string.app_name) + " > "
+ formController.getFormTitle());
switch (event) {
case FormEntryController.EVENT_BEGINNING_OF_FORM:
View startView = View
.inflate(this, R.layout.form_entry_start, null);
setTitle(getString(R.string.app_name) + " > "
+ formController.getFormTitle());
Drawable image = null;
File mediaFolder = formController.getMediaFolder();
String mediaDir = mediaFolder.getAbsolutePath();
BitmapDrawable bitImage = null;
// attempt to load the form-specific logo...
// this is arbitrarily silly
bitImage = new BitmapDrawable(getResources(), mediaDir + File.separator
+ "form_logo.png");
if (bitImage != null && bitImage.getBitmap() != null
&& bitImage.getIntrinsicHeight() > 0
&& bitImage.getIntrinsicWidth() > 0) {
image = bitImage;
}
if (image == null) {
// show the opendatakit zig...
// image =
// getResources().getDrawable(R.drawable.opendatakit_zig);
((ImageView) startView.findViewById(R.id.form_start_bling))
.setVisibility(View.GONE);
} else {
ImageView v = ((ImageView) startView
.findViewById(R.id.form_start_bling));
v.setImageDrawable(image);
v.setContentDescription(formController.getFormTitle());
}
// change start screen based on navigation prefs
String navigationChoice = PreferenceManager
.getDefaultSharedPreferences(this).getString(
PreferencesActivity.KEY_NAVIGATION,
PreferencesActivity.KEY_NAVIGATION);
Boolean useSwipe = false;
Boolean useButtons = false;
ImageView ia = ((ImageView) startView
.findViewById(R.id.image_advance));
ImageView ib = ((ImageView) startView
.findViewById(R.id.image_backup));
TextView ta = ((TextView) startView.findViewById(R.id.text_advance));
TextView tb = ((TextView) startView.findViewById(R.id.text_backup));
TextView d = ((TextView) startView.findViewById(R.id.description));
if (navigationChoice != null) {
if (navigationChoice
.contains(PreferencesActivity.NAVIGATION_SWIPE)) {
useSwipe = true;
}
if (navigationChoice
.contains(PreferencesActivity.NAVIGATION_BUTTONS)) {
useButtons = true;
}
}
if (useSwipe && !useButtons) {
d.setText(getString(R.string.swipe_instructions,
formController.getFormTitle()));
} else if (useButtons && !useSwipe) {
ia.setVisibility(View.GONE);
ib.setVisibility(View.GONE);
ta.setVisibility(View.GONE);
tb.setVisibility(View.GONE);
d.setText(getString(R.string.buttons_instructions,
formController.getFormTitle()));
} else {
d.setText(getString(R.string.swipe_buttons_instructions,
formController.getFormTitle()));
}
if (mBackButton.isShown()) {
mBackButton.setEnabled(false);
}
if (mNextButton.isShown()) {
mNextButton.setEnabled(true);
}
return startView;
case FormEntryController.EVENT_END_OF_FORM:
View endView = View.inflate(this, R.layout.form_entry_end, null);
((TextView) endView.findViewById(R.id.description))
.setText(getString(R.string.save_enter_data_description,
formController.getFormTitle()));
// checkbox for if finished or ready to send
final CheckBox instanceComplete = ((CheckBox) endView
.findViewById(R.id.mark_finished));
instanceComplete.setChecked(isInstanceComplete(true));
if (!mAdminPreferences.getBoolean(
AdminPreferencesActivity.KEY_MARK_AS_FINALIZED, true)) {
instanceComplete.setVisibility(View.GONE);
}
// edittext to change the displayed name of the instance
final EditText saveAs = (EditText) endView
.findViewById(R.id.save_name);
// disallow carriage returns in the name
InputFilter returnFilter = new InputFilter() {
public CharSequence filter(CharSequence source, int start,
int end, Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (Character.getType((source.charAt(i))) == Character.CONTROL) {
return "";
}
}
return null;
}
};
saveAs.setFilters(new InputFilter[] { returnFilter });
String saveName = formController.getSubmissionMetadata().instanceName;
if (saveName == null) {
// no meta/instanceName field in the form -- see if we have a
// name for this instance from a previous save attempt...
if (getContentResolver().getType(getIntent().getData()) == InstanceColumns.CONTENT_ITEM_TYPE) {
Uri instanceUri = getIntent().getData();
Cursor instance = null;
try {
instance = getContentResolver().query(instanceUri,
null, null, null, null);
if (instance.getCount() == 1) {
instance.moveToFirst();
saveName = instance
.getString(instance
.getColumnIndex(InstanceColumns.DISPLAY_NAME));
}
} finally {
if (instance != null) {
instance.close();
}
}
}
if (saveName == null) {
// last resort, default to the form title
saveName = formController.getFormTitle();
}
// present the prompt to allow user to name the form
TextView sa = (TextView) endView
.findViewById(R.id.save_form_as);
sa.setVisibility(View.VISIBLE);
saveAs.setText(saveName);
saveAs.setEnabled(true);
saveAs.setVisibility(View.VISIBLE);
} else {
// if instanceName is defined in form, this is the name -- no
// revisions
// display only the name, not the prompt, and disable edits
TextView sa = (TextView) endView
.findViewById(R.id.save_form_as);
sa.setVisibility(View.GONE);
saveAs.setText(saveName);
saveAs.setEnabled(false);
saveAs.setBackgroundColor(Color.WHITE);
saveAs.setVisibility(View.VISIBLE);
}
// override the visibility settings based upon admin preferences
if (!mAdminPreferences.getBoolean(
AdminPreferencesActivity.KEY_SAVE_AS, true)) {
saveAs.setVisibility(View.GONE);
TextView sa = (TextView) endView
.findViewById(R.id.save_form_as);
sa.setVisibility(View.GONE);
}
// Create 'save' button
((Button) endView.findViewById(R.id.save_exit_button))
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(
this,
"createView.saveAndExit",
instanceComplete.isChecked() ? "saveAsComplete"
: "saveIncomplete");
// Form is marked as 'saved' here.
if (saveAs.getText().length() < 1) {
Toast.makeText(FormEntryActivity.this,
R.string.save_as_error,
Toast.LENGTH_SHORT).show();
} else {
saveDataToDisk(EXIT, instanceComplete
.isChecked(), saveAs.getText()
.toString());
}
}
});
if (mBackButton.isShown()) {
mBackButton.setEnabled(true);
}
if (mNextButton.isShown()) {
mNextButton.setEnabled(false);
}
return endView;
case FormEntryController.EVENT_QUESTION:
case FormEntryController.EVENT_GROUP:
case FormEntryController.EVENT_REPEAT:
ODKView odkv = null;
// should only be a group here if the event_group is a field-list
try {
FormEntryPrompt[] prompts = formController.getQuestionPrompts();
FormEntryCaption[] groups = formController
.getGroupsForCurrentIndex();
odkv = new ODKView(this, formController.getQuestionPrompts(),
groups, advancingPage);
Log.i(t,
"created view for group "
+ (groups.length > 0 ? groups[groups.length - 1]
.getLongText() : "[top]")
+ " "
+ (prompts.length > 0 ? prompts[0]
.getQuestionText() : "[no question]"));
} catch (RuntimeException e) {
Log.e(t, e.getMessage(), e);
// this is badness to avoid a crash.
try {
event = formController.stepToNextScreenEvent();
createErrorDialog(e.getMessage(), DO_NOT_EXIT);
} catch (JavaRosaException e1) {
Log.e(t, e1.getMessage(), e1);
createErrorDialog(e.getMessage() + "\n\n" + e1.getCause().getMessage(), DO_NOT_EXIT);
}
return createView(event, advancingPage);
}
// Makes a "clear answer" menu pop up on long-click
for (QuestionWidget qw : odkv.getWidgets()) {
if (!qw.getPrompt().isReadOnly()) {
registerForContextMenu(qw);
}
}
if (mBackButton.isShown() && mNextButton.isShown()) {
mBackButton.setEnabled(true);
mNextButton.setEnabled(true);
}
return odkv;
default:
Log.e(t, "Attempted to create a view that does not exist.");
// this is badness to avoid a crash.
try {
event = formController.stepToNextScreenEvent();
createErrorDialog(getString(R.string.survey_internal_error), EXIT);
} catch (JavaRosaException e) {
Log.e(t, e.getMessage(), e);
createErrorDialog(e.getCause().getMessage(), EXIT);
}
return createView(event, advancingPage);
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent mv) {
boolean handled = mGestureDetector.onTouchEvent(mv);
if (!handled) {
return super.dispatchTouchEvent(mv);
}
return handled; // this is always true
}
/**
* Determines what should be displayed on the screen. Possible options are:
* a question, an ask repeat dialog, or the submit screen. Also saves
* answers to the data model after checking constraints.
*/
private void showNextView() {
try {
FormController formController = Collect.getInstance()
.getFormController();
// get constraint behavior preference value with appropriate default
String constraint_behavior = PreferenceManager.getDefaultSharedPreferences(this)
.getString(PreferencesActivity.KEY_CONSTRAINT_BEHAVIOR,
PreferencesActivity.CONSTRAINT_BEHAVIOR_DEFAULT);
if (formController.currentPromptIsQuestion()) {
// if constraint behavior says we should validate on swipe, do so
if (constraint_behavior.equals(PreferencesActivity.CONSTRAINT_BEHAVIOR_ON_SWIPE)) {
if (!saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS)) {
// A constraint was violated so a dialog should be showing.
mBeenSwiped = false;
return;
}
// otherwise, just save without validating (constraints will be validated on finalize)
} else
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
View next;
int event = formController.stepToNextScreenEvent();
switch (event) {
case FormEntryController.EVENT_QUESTION:
case FormEntryController.EVENT_GROUP:
// create a savepoint
if ((++viewCount) % SAVEPOINT_INTERVAL == 0) {
nonblockingCreateSavePointData();
}
next = createView(event, true);
showView(next, AnimationType.RIGHT);
break;
case FormEntryController.EVENT_END_OF_FORM:
case FormEntryController.EVENT_REPEAT:
next = createView(event, true);
showView(next, AnimationType.RIGHT);
break;
case FormEntryController.EVENT_PROMPT_NEW_REPEAT:
createRepeatDialog();
break;
case FormEntryController.EVENT_REPEAT_JUNCTURE:
Log.i(t, "repeat juncture: "
+ formController.getFormIndex().getReference());
// skip repeat junctures until we implement them
break;
default:
Log.w(t,
"JavaRosa added a new EVENT type and didn't tell us... shame on them.");
break;
}
} catch (JavaRosaException e) {
Log.e(t, e.getMessage(), e);
createErrorDialog(e.getCause().getMessage(), DO_NOT_EXIT);
}
}
/**
* Determines what should be displayed between a question, or the start
* screen and displays the appropriate view. Also saves answers to the data
* model without checking constraints.
*/
private void showPreviousView() {
try {
FormController formController = Collect.getInstance()
.getFormController();
// The answer is saved on a back swipe, but question constraints are
// ignored.
if (formController.currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
if (formController.getEvent() != FormEntryController.EVENT_BEGINNING_OF_FORM) {
int event = formController.stepToPreviousScreenEvent();
if (event == FormEntryController.EVENT_BEGINNING_OF_FORM
|| event == FormEntryController.EVENT_GROUP
|| event == FormEntryController.EVENT_QUESTION) {
// create savepoint
if ((++viewCount) % SAVEPOINT_INTERVAL == 0) {
nonblockingCreateSavePointData();
}
}
View next = createView(event, false);
showView(next, AnimationType.LEFT);
} else {
mBeenSwiped = false;
}
} catch (JavaRosaException e) {
Log.e(t, e.getMessage(), e);
createErrorDialog(e.getCause().getMessage(), DO_NOT_EXIT);
}
}
/**
* Displays the View specified by the parameter 'next', animating both the
* current view and next appropriately given the AnimationType. Also updates
* the progress bar.
*/
public void showView(View next, AnimationType from) {
// disable notifications...
if (mInAnimation != null) {
mInAnimation.setAnimationListener(null);
}
if (mOutAnimation != null) {
mOutAnimation.setAnimationListener(null);
}
// logging of the view being shown is already done, as this was handled
// by createView()
switch (from) {
case RIGHT:
mInAnimation = AnimationUtils.loadAnimation(this,
R.anim.push_left_in);
mOutAnimation = AnimationUtils.loadAnimation(this,
R.anim.push_left_out);
// if animation is left or right then it was a swipe, and we want to re-save on entry
mAutoSaved = false;
break;
case LEFT:
mInAnimation = AnimationUtils.loadAnimation(this,
R.anim.push_right_in);
mOutAnimation = AnimationUtils.loadAnimation(this,
R.anim.push_right_out);
mAutoSaved = false;
break;
case FADE:
mInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in);
mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out);
break;
}
// complete setup for animations...
mInAnimation.setAnimationListener(this);
mOutAnimation.setAnimationListener(this);
// drop keyboard before transition...
if (mCurrentView != null) {
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(mCurrentView.getWindowToken(),
0);
}
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
// adjust which view is in the layout container...
mStaleView = mCurrentView;
mCurrentView = next;
mQuestionHolder.addView(mCurrentView, lp);
mAnimationCompletionSet = 0;
if (mStaleView != null) {
// start OutAnimation for transition...
mStaleView.startAnimation(mOutAnimation);
// and remove the old view (MUST occur after start of animation!!!)
mQuestionHolder.removeView(mStaleView);
} else {
mAnimationCompletionSet = 2;
}
// start InAnimation for transition...
mCurrentView.startAnimation(mInAnimation);
String logString = "";
switch (from) {
case RIGHT:
logString = "next";
break;
case LEFT:
logString = "previous";
break;
case FADE:
logString = "refresh";
break;
}
Collect.getInstance().getActivityLogger().logInstanceAction(this, "showView", logString);
FormController formController = Collect.getInstance().getFormController();
if (formController.getEvent() == FormEntryController.EVENT_QUESTION
|| formController.getEvent() == FormEntryController.EVENT_GROUP
|| formController.getEvent() == FormEntryController.EVENT_REPEAT) {
FormEntryPrompt[] prompts = Collect.getInstance().getFormController()
.getQuestionPrompts();
for (FormEntryPrompt p : prompts) {
List<TreeElement> attrs = p.getBindAttributes();
for (int i = 0; i < attrs.size(); i++) {
if (!mAutoSaved && "saveIncomplete".equals(attrs.get(i).getName())) {
saveDataToDisk(false, false, null, false);
mAutoSaved = true;
}
}
}
}
}
// Hopefully someday we can use managed dialogs when the bugs are fixed
/*
* Ideally, we'd like to use Android to manage dialogs with onCreateDialog()
* and onPrepareDialog(), but dialogs with dynamic content are broken in 1.5
* (cupcake). We do use managed dialogs for our static loading
* ProgressDialog. The main issue we noticed and are waiting to see fixed
* is: onPrepareDialog() is not called after a screen orientation change.
* http://code.google.com/p/android/issues/detail?id=1639
*/
//
/**
* Creates and displays a dialog displaying the violated constraint.
*/
private void createConstraintToast(FormIndex index, int saveStatus) {
FormController formController = Collect.getInstance()
.getFormController();
String constraintText;
switch (saveStatus) {
case FormEntryController.ANSWER_CONSTRAINT_VIOLATED:
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createConstraintToast.ANSWER_CONSTRAINT_VIOLATED",
"show", index);
constraintText = formController
.getQuestionPromptConstraintText(index);
if (constraintText == null) {
constraintText = formController.getQuestionPrompt(index)
.getSpecialFormQuestionText("constraintMsg");
if (constraintText == null) {
constraintText = getString(R.string.invalid_answer_error);
}
}
break;
case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY:
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createConstraintToast.ANSWER_REQUIRED_BUT_EMPTY",
"show", index);
constraintText = formController
.getQuestionPromptRequiredText(index);
if (constraintText == null) {
constraintText = formController.getQuestionPrompt(index)
.getSpecialFormQuestionText("requiredMsg");
if (constraintText == null) {
constraintText = getString(R.string.required_answer_error);
}
}
break;
default:
return;
}
showCustomToast(constraintText, Toast.LENGTH_SHORT);
}
/**
* Creates a toast with the specified message.
*
* @param message
*/
private void showCustomToast(String message, int duration) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.toast_view, null);
// set the text in the view
TextView tv = (TextView) view.findViewById(R.id.message);
tv.setText(message);
Toast t = new Toast(this);
t.setView(view);
t.setDuration(duration);
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
}
/**
* Creates and displays a dialog asking the user if they'd like to create a
* repeat of the current group.
*/
private void createRepeatDialog() {
FormController formController = Collect.getInstance()
.getFormController();
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "createRepeatDialog", "show");
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
DialogInterface.OnClickListener repeatListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
FormController formController = Collect.getInstance()
.getFormController();
switch (i) {
case DialogInterface.BUTTON_POSITIVE: // yes, repeat
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "createRepeatDialog",
"addRepeat");
try {
formController.newRepeat();
} catch (Exception e) {
FormEntryActivity.this.createErrorDialog(
e.getMessage(), DO_NOT_EXIT);
return;
}
if (!formController.indexIsInFieldList()) {
// we are at a REPEAT event that does not have a
// field-list appearance
// step to the next visible field...
// which could be the start of a new repeat group...
showNextView();
} else {
// we are at a REPEAT event that has a field-list
// appearance
// just display this REPEAT event's group.
refreshCurrentView();
}
break;
case DialogInterface. BUTTON_NEGATIVE: // no, no repeat
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "createRepeatDialog",
"showNext");
//
// Make sure the error dialog will not disappear.
//
// When showNextView() popups an error dialog (because of a JavaRosaException)
// the issue is that the "add new repeat dialog" is referenced by mAlertDialog
// like the error dialog. When the "no repeat" is clicked, the error dialog
// is shown. Android by default dismisses the dialogs when a button is clicked,
// so instead of closing the first dialog, it closes the second.
new Thread() {
@Override
public void run() {
FormEntryActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
showNextView();
}
});
}
}.start();
break;
}
}
};
if (formController.getLastRepeatCount() > 0) {
mAlertDialog.setTitle(getString(R.string.leaving_repeat_ask));
mAlertDialog.setMessage(getString(R.string.add_another_repeat,
formController.getLastGroupText()));
mAlertDialog.setButton(getString(R.string.add_another),
repeatListener);
mAlertDialog.setButton2(getString(R.string.leave_repeat_yes),
repeatListener);
} else {
mAlertDialog.setTitle(getString(R.string.entering_repeat_ask));
mAlertDialog.setMessage(getString(R.string.add_repeat,
formController.getLastGroupText()));
mAlertDialog.setButton(getString(R.string.entering_repeat),
repeatListener);
mAlertDialog.setButton2(getString(R.string.add_repeat_no),
repeatListener);
}
mAlertDialog.setCancelable(false);
mBeenSwiped = false;
mAlertDialog.show();
}
/**
* Creates and displays dialog with the given errorMsg.
*/
private void createErrorDialog(String errorMsg, final boolean shouldExit) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "createErrorDialog",
"show." + Boolean.toString(shouldExit));
if (mAlertDialog != null && mAlertDialog.isShowing()) {
errorMsg = mErrorMessage + "\n\n" + errorMsg;
mErrorMessage = errorMsg;
} else {
mAlertDialog = new AlertDialog.Builder(this).create();
mErrorMessage = errorMsg;
}
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertDialog.setTitle(getString(R.string.error_occured));
mAlertDialog.setMessage(errorMsg);
DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON_POSITIVE:
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "createErrorDialog", "OK");
if (shouldExit) {
mErrorMessage = null;
finish();
}
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.ok), errorListener);
mBeenSwiped = false;
mAlertDialog.show();
}
/**
* Creates a confirm/cancel dialog for deleting repeats.
*/
private void createDeleteRepeatConfirmDialog() {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "createDeleteRepeatConfirmDialog",
"show");
FormController formController = Collect.getInstance()
.getFormController();
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
String name = formController.getLastRepeatedGroupName();
int repeatcount = formController.getLastRepeatedGroupRepeatCount();
if (repeatcount != -1) {
name += " (" + (repeatcount + 1) + ")";
}
mAlertDialog.setTitle(getString(R.string.delete_repeat_ask));
mAlertDialog
.setMessage(getString(R.string.delete_repeat_confirm, name));
DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
FormController formController = Collect.getInstance()
.getFormController();
switch (i) {
case DialogInterface.BUTTON_POSITIVE: // yes
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createDeleteRepeatConfirmDialog", "OK");
formController.deleteRepeat();
showPreviousView();
break;
case DialogInterface. BUTTON_NEGATIVE: // no
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createDeleteRepeatConfirmDialog", "cancel");
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.discard_group), quitListener);
mAlertDialog.setButton2(getString(R.string.delete_repeat_no),
quitListener);
mAlertDialog.show();
}
/**
* Saves data and writes it to disk. If exit is set, program will exit after
* save completes. Complete indicates whether the user has marked the
* isntancs as complete. If updatedSaveName is non-null, the instances
* content provider is updated with the new name
*/
// by default, save the current screen
private boolean saveDataToDisk(boolean exit, boolean complete, String updatedSaveName) {
return saveDataToDisk(exit, complete, updatedSaveName, true);
}
// but if you want save in the background, can't be current screen
private boolean saveDataToDisk(boolean exit, boolean complete, String updatedSaveName,
boolean current) {
// save current answer
if (current) {
if (!saveAnswersForCurrentScreen(complete)) {
Toast.makeText(this, getString(R.string.data_saved_error), Toast.LENGTH_SHORT)
.show();
return false;
}
}
synchronized (saveDialogLock) {
mSaveToDiskTask = new SaveToDiskTask(getIntent().getData(), exit, complete,
updatedSaveName);
mSaveToDiskTask.setFormSavedListener(this);
mAutoSaved = true;
showDialog(SAVING_DIALOG);
// show dialog before we execute...
mSaveToDiskTask.execute();
}
return true;
}
/**
* Create a dialog with options to save and exit, save, or quit without
* saving
*/
private void createQuitDialog() {
String title;
{
FormController formController = Collect.getInstance().getFormController();
title = (formController == null) ? null : formController.getFormTitle();
if ( title == null ) {
title = "<no form loaded>";
}
}
String[] items;
if (mAdminPreferences.getBoolean(AdminPreferencesActivity.KEY_SAVE_MID,
true)) {
String[] two = { getString(R.string.keep_changes),
getString(R.string.do_not_save) };
items = two;
} else {
String[] one = { getString(R.string.do_not_save) };
items = one;
}
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "createQuitDialog", "show");
mAlertDialog = new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_info)
.setTitle(
getString(R.string.quit_application, title))
.setNeutralButton(getString(R.string.do_not_exit),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createQuitDialog", "cancel");
dialog.cancel();
}
})
.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0: // save and exit
// this is slightly complicated because if the
// option is disabled in
// the admin menu, then case 0 actually becomes
// 'discard and exit'
// whereas if it's enabled it's 'save and exit'
if (mAdminPreferences
.getBoolean(
AdminPreferencesActivity.KEY_SAVE_MID,
true)) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createQuitDialog",
"saveAndExit");
saveDataToDisk(EXIT, isInstanceComplete(false),
null);
} else {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createQuitDialog",
"discardAndExit");
removeTempInstance();
finishReturnInstance();
}
break;
case 1: // discard changes and exit
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createQuitDialog",
"discardAndExit");
// close all open databases of external data.
Collect.getInstance().getExternalDataManager().close();
removeTempInstance();
finishReturnInstance();
break;
case 2:// do nothing
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createQuitDialog", "cancel");
break;
}
}
}).create();
mAlertDialog.show();
}
/**
* this method cleans up unneeded files when the user selects 'discard and
* exit'
*/
private void removeTempInstance() {
FormController formController = Collect.getInstance()
.getFormController();
// attempt to remove any scratch file
File temp = SaveToDiskTask.savepointFile(formController
.getInstancePath());
if (temp.exists()) {
temp.delete();
}
String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?";
String[] selectionArgs = { formController.getInstancePath()
.getAbsolutePath() };
boolean erase = false;
{
Cursor c = null;
try {
c = getContentResolver().query(InstanceColumns.CONTENT_URI,
null, selection, selectionArgs, null);
erase = (c.getCount() < 1);
} finally {
if (c != null) {
c.close();
}
}
}
// if it's not already saved, erase everything
if (erase) {
// delete media first
String instanceFolder = formController.getInstancePath()
.getParent();
Log.i(t, "attempting to delete: " + instanceFolder);
int images = MediaUtils
.deleteImagesInFolderFromMediaProvider(formController
.getInstancePath().getParentFile());
int audio = MediaUtils
.deleteAudioInFolderFromMediaProvider(formController
.getInstancePath().getParentFile());
int video = MediaUtils
.deleteVideoInFolderFromMediaProvider(formController
.getInstancePath().getParentFile());
Log.i(t, "removed from content providers: " + images
+ " image files, " + audio + " audio files," + " and "
+ video + " video files.");
File f = new File(instanceFolder);
if (f.exists() && f.isDirectory()) {
for (File del : f.listFiles()) {
Log.i(t, "deleting file: " + del.getAbsolutePath());
del.delete();
}
f.delete();
}
}
}
/**
* Confirm clear answer dialog
*/
private void createClearDialog(final QuestionWidget qw) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "createClearDialog", "show",
qw.getPrompt().getIndex());
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertDialog.setTitle(getString(R.string.clear_answer_ask));
String question = qw.getPrompt().getLongText();
if (question == null) {
question = "";
}
if (question.length() > 50) {
question = question.substring(0, 50) + "...";
}
mAlertDialog.setMessage(getString(R.string.clearanswer_confirm,
question));
DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON_POSITIVE: // yes
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "createClearDialog",
"clearAnswer", qw.getPrompt().getIndex());
clearAnswer(qw);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case DialogInterface. BUTTON_NEGATIVE: // no
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "createClearDialog",
"cancel", qw.getPrompt().getIndex());
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog
.setButton(getString(R.string.discard_answer), quitListener);
mAlertDialog.setButton2(getString(R.string.clear_answer_no),
quitListener);
mAlertDialog.show();
}
/**
* Creates and displays a dialog allowing the user to set the language for
* the form.
*/
private void createLanguageDialog() {
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "createLanguageDialog", "show");
FormController formController = Collect.getInstance()
.getFormController();
final String[] languages = formController.getLanguages();
int selected = -1;
if (languages != null) {
String language = formController.getLanguage();
for (int i = 0; i < languages.length; i++) {
if (language.equals(languages[i])) {
selected = i;
}
}
}
mAlertDialog = new AlertDialog.Builder(this)
.setSingleChoiceItems(languages, selected,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int whichButton) {
FormController formController = Collect
.getInstance().getFormController();
// Update the language in the content provider
// when selecting a new
// language
ContentValues values = new ContentValues();
values.put(FormsColumns.LANGUAGE,
languages[whichButton]);
String selection = FormsColumns.FORM_FILE_PATH
+ "=?";
String selectArgs[] = { mFormPath };
int updated = getContentResolver().update(
FormsColumns.CONTENT_URI, values,
selection, selectArgs);
Log.i(t, "Updated language to: "
+ languages[whichButton] + " in "
+ updated + " rows");
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(
this,
"createLanguageDialog",
"changeLanguage."
+ languages[whichButton]);
formController
.setLanguage(languages[whichButton]);
dialog.dismiss();
if (formController.currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
refreshCurrentView();
}
})
.setTitle(getString(R.string.change_language))
.setNegativeButton(getString(R.string.do_not_change),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int whichButton) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createLanguageDialog",
"cancel");
}
}).create();
mAlertDialog.show();
}
/**
* We use Android's dialog management for loading/saving progress dialogs
*/
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
Log.e(t, "Creating PROGRESS_DIALOG");
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onCreateDialog.PROGRESS_DIALOG",
"show");
mProgressDialog = new ProgressDialog(this);
DialogInterface.OnClickListener loadingButtonListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"onCreateDialog.PROGRESS_DIALOG", "cancel");
dialog.dismiss();
mFormLoaderTask.setFormLoaderListener(null);
FormLoaderTask t = mFormLoaderTask;
mFormLoaderTask = null;
t.cancel(true);
t.destroy();
finish();
}
};
mProgressDialog.setIcon(android.R.drawable.ic_dialog_info);
mProgressDialog.setTitle(getString(R.string.loading_form));
mProgressDialog.setMessage(getString(R.string.please_wait));
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setButton(getString(R.string.cancel_loading_form),
loadingButtonListener);
return mProgressDialog;
case SAVING_DIALOG:
Log.e(t, "Creating SAVING_DIALOG");
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onCreateDialog.SAVING_DIALOG",
"show");
mProgressDialog = new ProgressDialog(this);
DialogInterface.OnClickListener cancelSavingButtonListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"onCreateDialog.SAVING_DIALOG", "cancel");
dialog.dismiss();
cancelSaveToDiskTask();
}
};
mProgressDialog.setIcon(android.R.drawable.ic_dialog_info);
mProgressDialog.setTitle(getString(R.string.saving_form));
mProgressDialog.setMessage(getString(R.string.please_wait));
mProgressDialog.setIndeterminate(true);
mProgressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"onCreateDialog.SAVING_DIALOG", "OnDismissListener");
cancelSaveToDiskTask();
}
});
return mProgressDialog;
}
return null;
}
private void cancelSaveToDiskTask() {
synchronized (saveDialogLock) {
mSaveToDiskTask.setFormSavedListener(null);
boolean cancelled = mSaveToDiskTask.cancel(true);
Log.w(t, "Cancelled SaveToDiskTask! (" + cancelled + ")");
mSaveToDiskTask = null;
}
}
/**
* Dismiss any showing dialogs that we manually manage.
*/
private void dismissDialogs() {
Log.e(t, "Dismiss dialogs");
if (mAlertDialog != null && mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
}
@Override
protected void onPause() {
FormController formController = Collect.getInstance()
.getFormController();
dismissDialogs();
// make sure we're not already saving to disk. if we are, currentPrompt
// is getting constantly updated
if (mSaveToDiskTask == null
|| mSaveToDiskTask.getStatus() == AsyncTask.Status.FINISHED) {
if (mCurrentView != null && formController != null
&& formController.currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
}
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
if (mErrorMessage != null) {
if (mAlertDialog != null && !mAlertDialog.isShowing()) {
createErrorDialog(mErrorMessage, EXIT);
} else {
return;
}
}
FormController formController = Collect.getInstance().getFormController();
Collect.getInstance().getActivityLogger().open();
if (mFormLoaderTask != null) {
mFormLoaderTask.setFormLoaderListener(this);
if (formController == null
&& mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) {
FormController fec = mFormLoaderTask.getFormController();
if (fec != null) {
loadingComplete(mFormLoaderTask);
} else {
dismissDialog(PROGRESS_DIALOG);
FormLoaderTask t = mFormLoaderTask;
mFormLoaderTask = null;
t.cancel(true);
t.destroy();
// there is no formController -- fire MainMenu activity?
startActivity(new Intent(this, MainMenuActivity.class));
}
}
} else {
if (formController == null) {
// there is no formController -- fire MainMenu activity?
startActivity(new Intent(this, MainMenuActivity.class));
return;
} else {
refreshCurrentView();
}
}
if (mSaveToDiskTask != null) {
mSaveToDiskTask.setFormSavedListener(this);
}
// only check the buttons if it's enabled in preferences
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
String navigation = sharedPreferences.getString(
PreferencesActivity.KEY_NAVIGATION,
PreferencesActivity.KEY_NAVIGATION);
Boolean showButtons = false;
if (navigation.contains(PreferencesActivity.NAVIGATION_BUTTONS)) {
showButtons = true;
}
if (showButtons) {
mBackButton.setVisibility(View.VISIBLE);
mNextButton.setVisibility(View.VISIBLE);
} else {
mBackButton.setVisibility(View.GONE);
mNextButton.setVisibility(View.GONE);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "onKeyDown.KEYCODE_BACK", "quit");
createQuitDialog();
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (event.isAltPressed() && !mBeenSwiped) {
mBeenSwiped = true;
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"onKeyDown.KEYCODE_DPAD_RIGHT", "showNext");
showNextView();
return true;
}
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (event.isAltPressed() && !mBeenSwiped) {
mBeenSwiped = true;
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onKeyDown.KEYCODE_DPAD_LEFT",
"showPrevious");
showPreviousView();
return true;
}
break;
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onDestroy() {
if (mFormLoaderTask != null) {
mFormLoaderTask.setFormLoaderListener(null);
// We have to call cancel to terminate the thread, otherwise it
// lives on and retains the FEC in memory.
// but only if it's done, otherwise the thread never returns
if (mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) {
FormLoaderTask t = mFormLoaderTask;
mFormLoaderTask = null;
t.cancel(true);
t.destroy();
}
}
if (mSaveToDiskTask != null) {
mSaveToDiskTask.setFormSavedListener(null);
// We have to call cancel to terminate the thread, otherwise it
// lives on and retains the FEC in memory.
if (mSaveToDiskTask.getStatus() == AsyncTask.Status.FINISHED) {
mSaveToDiskTask.cancel(true);
mSaveToDiskTask = null;
}
}
super.onDestroy();
}
private int mAnimationCompletionSet = 0;
private void afterAllAnimations() {
Log.i(t, "afterAllAnimations");
if (mStaleView != null) {
if (mStaleView instanceof ODKView) {
// http://code.google.com/p/android/issues/detail?id=8488
((ODKView) mStaleView).recycleDrawables();
}
mStaleView = null;
}
if (mCurrentView instanceof ODKView) {
((ODKView) mCurrentView).setFocus(this);
}
mBeenSwiped = false;
}
@Override
public void onAnimationEnd(Animation animation) {
Log.i(t, "onAnimationEnd "
+ ((animation == mInAnimation) ? "in"
: ((animation == mOutAnimation) ? "out" : "other")));
if (mInAnimation == animation) {
mAnimationCompletionSet |= 1;
} else if (mOutAnimation == animation) {
mAnimationCompletionSet |= 2;
} else {
Log.e(t, "Unexpected animation");
}
if (mAnimationCompletionSet == 3) {
this.afterAllAnimations();
}
}
@Override
public void onAnimationRepeat(Animation animation) {
// Added by AnimationListener interface.
Log.i(t, "onAnimationRepeat "
+ ((animation == mInAnimation) ? "in"
: ((animation == mOutAnimation) ? "out" : "other")));
}
@Override
public void onAnimationStart(Animation animation) {
// Added by AnimationListener interface.
Log.i(t, "onAnimationStart "
+ ((animation == mInAnimation) ? "in"
: ((animation == mOutAnimation) ? "out" : "other")));
}
/**
* loadingComplete() is called by FormLoaderTask once it has finished
* loading a form.
*/
@Override
public void loadingComplete(FormLoaderTask task) {
dismissDialog(PROGRESS_DIALOG);
FormController formController = task.getFormController();
boolean pendingActivityResult = task.hasPendingActivityResult();
boolean hasUsedSavepoint = task.hasUsedSavepoint();
int requestCode = task.getRequestCode(); // these are bogus if
// pendingActivityResult is
// false
int resultCode = task.getResultCode();
Intent intent = task.getIntent();
mFormLoaderTask.setFormLoaderListener(null);
FormLoaderTask t = mFormLoaderTask;
mFormLoaderTask = null;
t.cancel(true);
t.destroy();
Collect.getInstance().setFormController(formController);
CompatibilityUtils.invalidateOptionsMenu(this);
Collect.getInstance().setExternalDataManager(task.getExternalDataManager());
// Set the language if one has already been set in the past
String[] languageTest = formController.getLanguages();
if (languageTest != null) {
String defaultLanguage = formController.getLanguage();
String newLanguage = "";
String selection = FormsColumns.FORM_FILE_PATH + "=?";
String selectArgs[] = { mFormPath };
Cursor c = null;
try {
c = getContentResolver().query(FormsColumns.CONTENT_URI, null,
selection, selectArgs, null);
if (c.getCount() == 1) {
c.moveToFirst();
newLanguage = c.getString(c
.getColumnIndex(FormsColumns.LANGUAGE));
}
} finally {
if (c != null) {
c.close();
}
}
// if somehow we end up with a bad language, set it to the default
try {
formController.setLanguage(newLanguage);
} catch (Exception e) {
formController.setLanguage(defaultLanguage);
}
}
if (pendingActivityResult) {
// set the current view to whatever group we were at...
refreshCurrentView();
// process the pending activity request...
onActivityResult(requestCode, resultCode, intent);
return;
}
// it can be a normal flow for a pending activity result to restore from
// a savepoint
// (the call flow handled by the above if statement). For all other use
// cases, the
// user should be notified, as it means they wandered off doing other
// things then
// returned to ODK Collect and chose Edit Saved Form, but that the
// savepoint for that
// form is newer than the last saved version of their form data.
if (hasUsedSavepoint) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(FormEntryActivity.this,
getString(R.string.savepoint_used),
Toast.LENGTH_LONG).show();
}
});
}
// Set saved answer path
if (formController.getInstancePath() == null) {
// Create new answer folder.
String time = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss",
Locale.ENGLISH).format(Calendar.getInstance().getTime());
String file = mFormPath.substring(mFormPath.lastIndexOf('/') + 1,
mFormPath.lastIndexOf('.'));
String path = Collect.INSTANCES_PATH + File.separator + file + "_"
+ time;
if (FileUtils.createFolder(path)) {
formController.setInstancePath(new File(path + File.separator
+ file + "_" + time + ".xml"));
}
} else {
Intent reqIntent = getIntent();
boolean showFirst = reqIntent.getBooleanExtra("start", false);
if (!showFirst) {
// we've just loaded a saved form, so start in the hierarchy
// view
Intent i = new Intent(this, FormHierarchyActivity.class);
startActivity(i);
return; // so we don't show the intro screen before jumping to
// the hierarchy
}
}
refreshCurrentView();
}
/**
* called by the FormLoaderTask if something goes wrong.
*/
@Override
public void loadingError(String errorMsg) {
dismissDialog(PROGRESS_DIALOG);
if (errorMsg != null) {
createErrorDialog(errorMsg, EXIT);
} else {
createErrorDialog(getString(R.string.parse_error), EXIT);
}
}
/**
* Called by SavetoDiskTask if everything saves correctly.
*/
@Override
public void savingComplete(SaveResult saveResult) {
dismissDialog(SAVING_DIALOG);
int saveStatus = saveResult.getSaveResult();
switch (saveStatus) {
case SaveToDiskTask.SAVED:
Toast.makeText(this, getString(R.string.data_saved_ok),
Toast.LENGTH_SHORT).show();
sendSavedBroadcast();
break;
case SaveToDiskTask.SAVED_AND_EXIT:
Toast.makeText(this, getString(R.string.data_saved_ok),
Toast.LENGTH_SHORT).show();
sendSavedBroadcast();
finishReturnInstance();
break;
case SaveToDiskTask.SAVE_ERROR:
String message;
if (saveResult.getSaveErrorMessage() != null) {
message = getString(R.string.data_saved_error) + ": " + saveResult.getSaveErrorMessage();
} else {
message = getString(R.string.data_saved_error);
}
Toast.makeText(this, message,
Toast.LENGTH_LONG).show();
break;
case FormEntryController.ANSWER_CONSTRAINT_VIOLATED:
case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY:
refreshCurrentView();
// get constraint behavior preference value with appropriate default
String constraint_behavior = PreferenceManager.getDefaultSharedPreferences(this)
.getString(PreferencesActivity.KEY_CONSTRAINT_BEHAVIOR,
PreferencesActivity.CONSTRAINT_BEHAVIOR_DEFAULT);
// an answer constraint was violated, so we need to display the proper toast(s)
// if constraint behavior is on_swipe, this will happen if we do a 'swipe' to the next question
if (constraint_behavior.equals(PreferencesActivity.CONSTRAINT_BEHAVIOR_ON_SWIPE))
next();
// otherwise, we can get the proper toast(s) by saving with constraint check
else
saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS);
break;
}
}
@Override
public void onProgressStep(String stepMessage) {
this.stepMessage = stepMessage;
if (mProgressDialog != null) {
mProgressDialog.setMessage(getString(R.string.please_wait) + "\n\n" + stepMessage);
}
}
/**
* Attempts to save an answer to the specified index.
*
* @param answer
* @param index
* @param evaluateConstraints
* @return status as determined in FormEntryController
*/
public int saveAnswer(IAnswerData answer, FormIndex index,
boolean evaluateConstraints) throws JavaRosaException {
FormController formController = Collect.getInstance()
.getFormController();
if (evaluateConstraints) {
return formController.answerQuestion(index, answer);
} else {
formController.saveAnswer(index, answer);
return FormEntryController.ANSWER_OK;
}
}
/**
* Checks the database to determine if the current instance being edited has
* already been 'marked completed'. A form can be 'unmarked' complete and
* then resaved.
*
* @return true if form has been marked completed, false otherwise.
*/
private boolean isInstanceComplete(boolean end) {
FormController formController = Collect.getInstance()
.getFormController();
// default to false if we're mid form
boolean complete = false;
// if we're at the end of the form, then check the preferences
if (end) {
// First get the value from the preferences
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
complete = sharedPreferences.getBoolean(
PreferencesActivity.KEY_COMPLETED_DEFAULT, true);
}
// Then see if we've already marked this form as complete before
String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?";
String[] selectionArgs = { formController.getInstancePath()
.getAbsolutePath() };
Cursor c = null;
try {
c = getContentResolver().query(InstanceColumns.CONTENT_URI, null,
selection, selectionArgs, null);
if (c != null && c.getCount() > 0) {
c.moveToFirst();
String status = c.getString(c
.getColumnIndex(InstanceColumns.STATUS));
if (InstanceProviderAPI.STATUS_COMPLETE.compareTo(status) == 0) {
complete = true;
}
}
} finally {
if (c != null) {
c.close();
}
}
return complete;
}
public void next() {
if (!mBeenSwiped) {
mBeenSwiped = true;
showNextView();
}
}
/**
* Returns the instance that was just filled out to the calling activity, if
* requested.
*/
private void finishReturnInstance() {
FormController formController = Collect.getInstance()
.getFormController();
String action = getIntent().getAction();
if (Intent.ACTION_PICK.equals(action)
|| Intent.ACTION_EDIT.equals(action)) {
// caller is waiting on a picked form
String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?";
String[] selectionArgs = { formController.getInstancePath()
.getAbsolutePath() };
Cursor c = null;
try {
c = getContentResolver().query(InstanceColumns.CONTENT_URI,
null, selection, selectionArgs, null);
if (c.getCount() > 0) {
// should only be one...
c.moveToFirst();
String id = c.getString(c
.getColumnIndex(InstanceColumns._ID));
Uri instance = Uri.withAppendedPath(
InstanceColumns.CONTENT_URI, id);
setResult(RESULT_OK, new Intent().setData(instance));
}
} finally {
if (c != null) {
c.close();
}
}
}
finish();
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
// only check the swipe if it's enabled in preferences
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
String navigation = sharedPreferences.getString(
PreferencesActivity.KEY_NAVIGATION,
PreferencesActivity.NAVIGATION_SWIPE);
Boolean doSwipe = false;
if (navigation.contains(PreferencesActivity.NAVIGATION_SWIPE)) {
doSwipe = true;
}
if (doSwipe) {
// Looks for user swipes. If the user has swiped, move to the
// appropriate screen.
// for all screens a swipe is left/right of at least
// .25" and up/down of less than .25"
// OR left/right of > .5"
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int xPixelLimit = (int) (dm.xdpi * .25);
int yPixelLimit = (int) (dm.ydpi * .25);
if (mCurrentView instanceof ODKView) {
if (((ODKView) mCurrentView).suppressFlingGesture(e1, e2,
velocityX, velocityY)) {
return false;
}
}
if (mBeenSwiped) {
return false;
}
if ((Math.abs(e1.getX() - e2.getX()) > xPixelLimit && Math.abs(e1
.getY() - e2.getY()) < yPixelLimit)
|| Math.abs(e1.getX() - e2.getX()) > xPixelLimit * 2) {
mBeenSwiped = true;
if (velocityX > 0) {
if (e1.getX() > e2.getX()) {
Log.e(t,
"showNextView VelocityX is bogus! " + e1.getX()
+ " > " + e2.getX());
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "onFling", "showNext");
showNextView();
} else {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onFling",
"showPrevious");
showPreviousView();
}
} else {
if (e1.getX() < e2.getX()) {
Log.e(t,
"showPreviousView VelocityX is bogus! "
+ e1.getX() + " < " + e2.getX());
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onFling",
"showPrevious");
showPreviousView();
} else {
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "onFling", "showNext");
showNextView();
}
}
return true;
}
}
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
// The onFling() captures the 'up' event so our view thinks it gets long
// pressed.
// We don't wnat that, so cancel it.
if (mCurrentView != null) {
mCurrentView.cancelLongPress();
}
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public void advance() {
next();
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
private void sendSavedBroadcast() {
Intent i = new Intent();
i.setAction("org.odk.collect.android.FormSaved");
this.sendBroadcast(i);
}
@Override
public void onSavePointError(String errorMessage) {
if (errorMessage != null && errorMessage.trim().length() > 0) {
Toast.makeText(this, getString(R.string.save_point_error, errorMessage), Toast.LENGTH_LONG).show();
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/activities/FormEntryActivity.java
|
Java
|
asf20
| 92,576
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.activities;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import android.app.TabActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
/**
* A host activity for {@link InstanceChooserList}.
*
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class InstanceChooserTabs extends TabActivity {
private static final String SAVED_TAB = "saved_tab";
private static final String COMPLETED_TAB = "completed_tab";
// count for tab menu bar
private int mSavedCount;
private int mCompletedCount;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(getString(R.string.app_name) + " > " + getString(R.string.review_data));
// create tab host and tweak color
final TabHost tabHost = getTabHost();
tabHost.setBackgroundColor(Color.WHITE);
tabHost.getTabWidget().setBackgroundColor(Color.BLACK);
// create intent for saved tab
Intent saved = new Intent(this, InstanceChooserList.class);
tabHost.addTab(tabHost.newTabSpec(SAVED_TAB)
.setIndicator(getString(R.string.saved_data, mSavedCount)).setContent(saved));
// create intent for completed tab
Intent completed = new Intent(this, InstanceChooserList.class);
tabHost.addTab(tabHost.newTabSpec(COMPLETED_TAB)
.setIndicator(getString(R.string.completed_data, mCompletedCount))
.setContent(completed));
// hack to set font size and padding in tab headers
// arrived at these paths by using hierarchy viewer
LinearLayout ll = (LinearLayout) tabHost.getChildAt(0);
TabWidget tw = (TabWidget) ll.getChildAt(0);
int fontsize = Collect.getQuestionFontsize();
RelativeLayout rls = (RelativeLayout) tw.getChildAt(0);
TextView tvs = (TextView) rls.getChildAt(1);
tvs.setTextSize(fontsize);
tvs.setPadding(0, 0, 0, 6);
RelativeLayout rlc = (RelativeLayout) tw.getChildAt(1);
TextView tvc = (TextView) rlc.getChildAt(1);
tvc.setTextSize(fontsize);
tvc.setPadding(0, 0, 0, 6);
if (mSavedCount >= mCompletedCount) {
getTabHost().setCurrentTabByTag(SAVED_TAB);
} else {
getTabHost().setCurrentTabByTag(COMPLETED_TAB);
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/activities/InstanceChooserTabs.java
|
Java
|
asf20
| 3,238
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.activities;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import android.app.TabActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
/**
* An example of tab content that launches an activity via
* {@link android.widget.TabHost.TabSpec#setContent(android.content.Intent)}
*/
public class FileManagerTabs extends TabActivity {
private TextView mTVFF;
private TextView mTVDF;
private static final String FORMS_TAB = "forms_tab";
private static final String DATA_TAB = "data_tab";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(getString(R.string.app_name) + " > "
+ getString(R.string.manage_files));
final TabHost tabHost = getTabHost();
tabHost.setBackgroundColor(Color.WHITE);
tabHost.getTabWidget().setBackgroundColor(Color.DKGRAY);
Intent remote = new Intent(this, DataManagerList.class);
tabHost.addTab(tabHost.newTabSpec(DATA_TAB)
.setIndicator(getString(R.string.data)).setContent(remote));
Intent local = new Intent(this, FormManagerList.class);
tabHost.addTab(tabHost.newTabSpec(FORMS_TAB)
.setIndicator(getString(R.string.forms)).setContent(local));
// hack to set font size
LinearLayout ll = (LinearLayout) tabHost.getChildAt(0);
TabWidget tw = (TabWidget) ll.getChildAt(0);
int fontsize = Collect.getQuestionFontsize();
ViewGroup rllf = (ViewGroup) tw.getChildAt(0);
mTVFF = getTextViewChild(rllf);
if (mTVFF != null) {
mTVFF.setTextSize(fontsize);
mTVFF.setTextColor(Color.WHITE);
mTVFF.setPadding(0, 0, 0, 6);
}
ViewGroup rlrf = (ViewGroup) tw.getChildAt(1);
mTVDF = getTextViewChild(rlrf);
if (mTVDF != null) {
mTVDF.setTextSize(fontsize);
mTVDF.setTextColor(Color.WHITE);
mTVDF.setPadding(0, 0, 0, 6);
}
}
private TextView getTextViewChild(ViewGroup viewGroup) {
for (int i = 0; i < viewGroup.getChildCount(); i++) {
View view = viewGroup.getChildAt(i);
if (view instanceof TextView) {
return (TextView) view;
}
}
return null;
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
}
|
0nima0-f
|
src/org/odk/collect/android/activities/FileManagerTabs.java
|
Java
|
asf20
| 3,179
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.activities;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.provider.InstanceProviderAPI;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
/**
* Responsible for displaying all the valid instances in the instance directory.
*
* @author Yaw Anokwa (yanokwa@gmail.com)
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class InstanceChooserList extends ListActivity {
private static final boolean EXIT = true;
private static final boolean DO_NOT_EXIT = false;
private AlertDialog mAlertDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// must be at the beginning of any activity that can be called from an external intent
try {
Collect.createODKDirs();
} catch (RuntimeException e) {
createErrorDialog(e.getMessage(), EXIT);
return;
}
setContentView(R.layout.chooser_list_layout);
setTitle(getString(R.string.app_name) + " > " + getString(R.string.review_data));
TextView tv = (TextView) findViewById(R.id.status_text);
tv.setVisibility(View.GONE);
String selection = InstanceColumns.STATUS + " != ?";
String[] selectionArgs = {InstanceProviderAPI.STATUS_SUBMITTED};
String sortOrder = InstanceColumns.STATUS + " DESC, " + InstanceColumns.DISPLAY_NAME + " ASC";
Cursor c = managedQuery(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, sortOrder);
String[] data = new String[] {
InstanceColumns.DISPLAY_NAME, InstanceColumns.DISPLAY_SUBTEXT
};
int[] view = new int[] {
R.id.text1, R.id.text2
};
// render total instance view
SimpleCursorAdapter instances =
new SimpleCursorAdapter(this, R.layout.two_item, c, data, view);
setListAdapter(instances);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
}
/**
* Stores the path of selected instance in the parent class and finishes.
*/
@Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
Cursor c = (Cursor) getListAdapter().getItem(position);
startManagingCursor(c);
Uri instanceUri =
ContentUris.withAppendedId(InstanceColumns.CONTENT_URI,
c.getLong(c.getColumnIndex(InstanceColumns._ID)));
Collect.getInstance().getActivityLogger().logAction(this, "onListItemClick", instanceUri.toString());
String action = getIntent().getAction();
if (Intent.ACTION_PICK.equals(action)) {
// caller is waiting on a picked form
setResult(RESULT_OK, new Intent().setData(instanceUri));
} else {
// the form can be edited if it is incomplete or if, when it was
// marked as complete, it was determined that it could be edited
// later.
String status = c.getString(c.getColumnIndex(InstanceColumns.STATUS));
String strCanEditWhenComplete =
c.getString(c.getColumnIndex(InstanceColumns.CAN_EDIT_WHEN_COMPLETE));
boolean canEdit = status.equals(InstanceProviderAPI.STATUS_INCOMPLETE)
|| Boolean.parseBoolean(strCanEditWhenComplete);
if (!canEdit) {
createErrorDialog(getString(R.string.cannot_edit_completed_form),
DO_NOT_EXIT);
return;
}
// caller wants to view/edit a form, so launch formentryactivity
startActivity(new Intent(Intent.ACTION_EDIT, instanceUri));
}
finish();
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
private void createErrorDialog(String errorMsg, final boolean shouldExit) {
Collect.getInstance().getActivityLogger().logAction(this, "createErrorDialog", "show");
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertDialog.setMessage(errorMsg);
DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON_POSITIVE:
Collect.getInstance().getActivityLogger().logAction(this, "createErrorDialog",
shouldExit ? "exitApplication" : "OK");
if (shouldExit) {
finish();
}
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.ok), errorListener);
mAlertDialog.show();
}
}
|
0nima0-f
|
src/org/odk/collect/android/activities/InstanceChooserList.java
|
Java
|
asf20
| 6,306
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.activities;
import java.util.ArrayList;
import java.util.List;
import org.javarosa.core.model.FormIndex;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryController;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.adapters.HierarchyListAdapter;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.exception.JavaRosaException;
import org.odk.collect.android.logic.FormController;
import org.odk.collect.android.logic.HierarchyElement;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class FormHierarchyActivity extends ListActivity {
private static final String t = "FormHierarchyActivity";
private static final int CHILD = 1;
private static final int EXPANDED = 2;
private static final int COLLAPSED = 3;
private static final int QUESTION = 4;
private static final String mIndent = " ";
private Button jumpPreviousButton;
List<HierarchyElement> formList;
TextView mPath;
FormIndex mStartIndex;
private FormIndex currentIndex;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hierarchy_layout);
FormController formController = Collect.getInstance().getFormController();
// We use a static FormEntryController to make jumping faster.
mStartIndex = formController.getFormIndex();
setTitle(getString(R.string.app_name) + " > "
+ formController.getFormTitle());
mPath = (TextView) findViewById(R.id.pathtext);
jumpPreviousButton = (Button) findViewById(R.id.jumpPreviousButton);
jumpPreviousButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "goUpLevelButton", "click");
goUpLevel();
}
});
Button jumpBeginningButton = (Button) findViewById(R.id.jumpBeginningButton);
jumpBeginningButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "jumpToBeginning", "click");
Collect.getInstance().getFormController().jumpToIndex(FormIndex
.createBeginningOfFormIndex());
setResult(RESULT_OK);
finish();
}
});
Button jumpEndButton = (Button) findViewById(R.id.jumpEndButton);
jumpEndButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "jumpToEnd", "click");
Collect.getInstance().getFormController().jumpToIndex(FormIndex.createEndOfFormIndex());
setResult(RESULT_OK);
finish();
}
});
refreshView();
// kinda slow, but works.
// this scrolls to the last question the user was looking at
if (getListAdapter() != null && getListView() != null) {
getListView().post(new Runnable() {
@Override
public void run() {
int position = 0;
for (int i = 0; i < getListAdapter().getCount(); i++) {
HierarchyElement he = (HierarchyElement) getListAdapter().getItem(i);
if (mStartIndex.equals(he.getFormIndex())) {
position = i;
break;
}
}
getListView().setSelection(position);
}
});
}
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
private void goUpLevel() {
Collect.getInstance().getFormController().stepToOuterScreenEvent();
refreshView();
}
private String getCurrentPath() {
FormController formController = Collect.getInstance().getFormController();
FormIndex index = formController.getFormIndex();
// move to enclosing group...
index = formController.stepIndexOut(index);
String path = "";
while (index != null) {
path =
formController.getCaptionPrompt(index).getLongText()
+ " ("
+ (formController.getCaptionPrompt(index)
.getMultiplicity() + 1) + ") > " + path;
index = formController.stepIndexOut(index);
}
// return path?
return path.substring(0, path.length() - 2);
}
public void refreshView() {
try {
FormController formController = Collect.getInstance().getFormController();
// Record the current index so we can return to the same place if the user hits 'back'.
currentIndex = formController.getFormIndex();
// If we're not at the first level, we're inside a repeated group so we want to only display
// everything enclosed within that group.
String contextGroupRef = "";
formList = new ArrayList<HierarchyElement>();
// If we're currently at a repeat node, record the name of the node and step to the next
// node to display.
if (formController.getEvent() == FormEntryController.EVENT_REPEAT) {
contextGroupRef =
formController.getFormIndex().getReference().toString(true);
formController.stepToNextEvent(FormController.STEP_INTO_GROUP);
} else {
FormIndex startTest = formController.stepIndexOut(currentIndex);
// If we have a 'group' tag, we want to step back until we hit a repeat or the
// beginning.
while (startTest != null
&& formController.getEvent(startTest) == FormEntryController.EVENT_GROUP) {
startTest = formController.stepIndexOut(startTest);
}
if (startTest == null) {
// check to see if the question is at the first level of the hierarchy. If it is,
// display the root level from the beginning.
formController.jumpToIndex(FormIndex
.createBeginningOfFormIndex());
} else {
// otherwise we're at a repeated group
formController.jumpToIndex(startTest);
}
// now test again for repeat. This should be true at this point or we're at the
// beginning
if (formController.getEvent() == FormEntryController.EVENT_REPEAT) {
contextGroupRef =
formController.getFormIndex().getReference().toString(true);
formController.stepToNextEvent(FormController.STEP_INTO_GROUP);
}
}
int event = formController.getEvent();
if (event == FormEntryController.EVENT_BEGINNING_OF_FORM) {
// The beginning of form has no valid prompt to display.
formController.stepToNextEvent(FormController.STEP_INTO_GROUP);
contextGroupRef = formController.getFormIndex().getReference().getParentRef().toString(true);
mPath.setVisibility(View.GONE);
jumpPreviousButton.setEnabled(false);
} else {
mPath.setVisibility(View.VISIBLE);
mPath.setText(getCurrentPath());
jumpPreviousButton.setEnabled(true);
}
// Refresh the current event in case we did step forward.
event = formController.getEvent();
// Big change from prior implementation:
//
// The ref strings now include the instance number designations
// i.e., [0], [1], etc. of the repeat groups (and also [1] for
// non-repeat elements).
//
// The contextGroupRef is now also valid for the top-level form.
//
// The repeatGroupRef is null if we are not skipping a repeat
// section.
//
String repeatGroupRef = null;
event_search: while (event != FormEntryController.EVENT_END_OF_FORM) {
// get the ref to this element
String currentRef = formController.getFormIndex().getReference().toString(true);
// retrieve the current group
String curGroup = (repeatGroupRef == null) ? contextGroupRef : repeatGroupRef;
if (!currentRef.startsWith(curGroup)) {
// We have left the current group
if ( repeatGroupRef == null ) {
// We are done.
break event_search;
} else {
// exit the inner repeat group
repeatGroupRef = null;
}
}
if (repeatGroupRef != null) {
// We're in a repeat group within the one we want to list
// skip this question/group/repeat and move to the next index.
event =
formController.stepToNextEvent(FormController.STEP_INTO_GROUP);
continue;
}
switch (event) {
case FormEntryController.EVENT_QUESTION:
FormEntryPrompt fp = formController.getQuestionPrompt();
String label = fp.getLongText();
if ( !fp.isReadOnly() || (label != null && label.length() > 0) ) {
// show the question if it is an editable field.
// or if it is read-only and the label is not blank.
formList.add(new HierarchyElement(fp.getLongText(), fp.getAnswerText(), null,
Color.WHITE, QUESTION, fp.getIndex()));
}
break;
case FormEntryController.EVENT_GROUP:
// ignore group events
break;
case FormEntryController.EVENT_PROMPT_NEW_REPEAT:
// this would display the 'add new repeat' dialog
// ignore it.
break;
case FormEntryController.EVENT_REPEAT:
FormEntryCaption fc = formController.getCaptionPrompt();
// push this repeat onto the stack.
repeatGroupRef = currentRef;
// Because of the guard conditions above, we will skip
// everything until we exit this repeat.
//
// Note that currentRef includes the multiplicity of the
// repeat (e.g., [0], [1], ...), so every repeat will be
// detected as different and reach this case statement.
// Only the [0] emits the repeat header.
// Every one displays the descend-into action element.
if (fc.getMultiplicity() == 0) {
// Display the repeat header for the group.
HierarchyElement group =
new HierarchyElement(fc.getLongText(), null, getResources()
.getDrawable(R.drawable.expander_ic_minimized), Color.WHITE,
COLLAPSED, fc.getIndex());
formList.add(group);
}
// Add this group name to the drop down list for this repeating group.
HierarchyElement h = formList.get(formList.size() - 1);
h.addChild(new HierarchyElement(mIndent + fc.getLongText() + " "
+ (fc.getMultiplicity() + 1), null, null, Color.WHITE, CHILD, fc
.getIndex()));
break;
}
event =
formController.stepToNextEvent(FormController.STEP_INTO_GROUP);
}
HierarchyListAdapter itla = new HierarchyListAdapter(this);
itla.setListItems(formList);
setListAdapter(itla);
// set the controller back to the current index in case the user hits 'back'
formController.jumpToIndex(currentIndex);
} catch (Exception e) {
Log.e(t, e.getMessage(), e);
createErrorDialog(e.getMessage());
}
}
/**
* Creates and displays dialog with the given errorMsg.
*/
private void createErrorDialog(String errorMsg) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "createErrorDialog", "show.");
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setIcon(android.R.drawable.ic_dialog_info);
alertDialog.setTitle(getString(R.string.error_occured));
alertDialog.setMessage(errorMsg);
DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON_POSITIVE:
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "createErrorDialog", "OK");
FormController formController = Collect.getInstance().getFormController();
formController.jumpToIndex(currentIndex);
break;
}
}
};
alertDialog.setCancelable(false);
alertDialog.setButton(getString(R.string.ok), errorListener);
alertDialog.show();
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
HierarchyElement h = (HierarchyElement) l.getItemAtPosition(position);
FormIndex index = h.getFormIndex();
if (index == null) {
goUpLevel();
return;
}
switch (h.getType()) {
case EXPANDED:
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onListItemClick", "COLLAPSED", h.getFormIndex());
h.setType(COLLAPSED);
ArrayList<HierarchyElement> children = h.getChildren();
for (int i = 0; i < children.size(); i++) {
formList.remove(position + 1);
}
h.setIcon(getResources().getDrawable(R.drawable.expander_ic_minimized));
h.setColor(Color.WHITE);
break;
case COLLAPSED:
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onListItemClick", "EXPANDED", h.getFormIndex());
h.setType(EXPANDED);
ArrayList<HierarchyElement> children1 = h.getChildren();
for (int i = 0; i < children1.size(); i++) {
Log.i(t, "adding child: " + children1.get(i).getFormIndex());
formList.add(position + 1 + i, children1.get(i));
}
h.setIcon(getResources().getDrawable(R.drawable.expander_ic_maximized));
h.setColor(Color.WHITE);
break;
case QUESTION:
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onListItemClick", "QUESTION-JUMP", index);
Collect.getInstance().getFormController().jumpToIndex(index);
if ( Collect.getInstance().getFormController().indexIsInFieldList() ) {
try {
Collect.getInstance().getFormController().stepToPreviousScreenEvent();
} catch (JavaRosaException e) {
Log.e(t, e.getMessage(), e);
createErrorDialog(e.getCause().getMessage());
return;
}
}
setResult(RESULT_OK);
finish();
return;
case CHILD:
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onListItemClick", "REPEAT-JUMP", h.getFormIndex());
Collect.getInstance().getFormController().jumpToIndex(h.getFormIndex());
setResult(RESULT_OK);
refreshView();
return;
}
// Should only get here if we've expanded or collapsed a group
HierarchyListAdapter itla = new HierarchyListAdapter(this);
itla.setListItems(formList);
setListAdapter(itla);
getListView().setSelection(position);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onKeyDown", "KEYCODE_BACK.JUMP", mStartIndex);
Collect.getInstance().getFormController().jumpToIndex(mStartIndex);
}
return super.onKeyDown(keyCode, event);
}
}
|
0nima0-f
|
src/org/odk/collect/android/activities/FormHierarchyActivity.java
|
Java
|
asf20
| 18,803
|
/*
* Copyright (C) 2011 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.activities;
import java.text.DecimalFormat;
import java.util.List;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.InfoLogger;
import org.odk.collect.android.widgets.GeoPointWidget;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
/**
* Version of the GeoPointMapActivity that uses the new Maps v2 API and Fragments to enable
* specifying a location via placing a tracker on a map.
*
* @author guisalmon@gmail.com
*
*/
public class GeoPointMapActivity extends FragmentActivity implements LocationListener, OnMarkerDragListener, OnMapLongClickListener {
private static final String LOCATION_COUNT = "locationCount";
private GoogleMap mMap;
private MarkerOptions mMarkerOption;
private Marker mMarker;
private LatLng mLatLng;
private TextView mLocationStatus;
private LocationManager mLocationManager;
private Location mLocation;
private Button mAcceptLocation;
private Button mCancelLocation;
private Button mReloadLocation;
private boolean mCaptureLocation = true;
private boolean mRefreshLocation = true;
private boolean mIsDragged = false;
private Button mShowLocation;
private boolean mGPSOn = false;
private boolean mNetworkOn = false;
private double mLocationAccuracy;
private int mLocationCount = 0;
private boolean mZoomed = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ( savedInstanceState != null ) {
mLocationCount = savedInstanceState.getInt(LOCATION_COUNT);
}
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.geopoint_layout);
Intent intent = getIntent();
mLocationAccuracy = GeoPointWidget.DEFAULT_LOCATION_ACCURACY;
if (intent != null && intent.getExtras() != null) {
if ( intent.hasExtra(GeoPointWidget.LOCATION) ) {
double[] location = intent.getDoubleArrayExtra(GeoPointWidget.LOCATION);
mLatLng = new LatLng(location[0], location[1]);
}
if ( intent.hasExtra(GeoPointWidget.ACCURACY_THRESHOLD) ) {
mLocationAccuracy = intent.getDoubleExtra(GeoPointWidget.ACCURACY_THRESHOLD, GeoPointWidget.DEFAULT_LOCATION_ACCURACY);
}
mCaptureLocation = !intent.getBooleanExtra(GeoPointWidget.READ_ONLY, false);
mRefreshLocation = mCaptureLocation;
}
/* Set up the map and the marker */
mMarkerOption = new MarkerOptions();
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
mMap.setOnMarkerDragListener(this);
mLocationStatus = (TextView) findViewById(R.id.location_status);
/*Zoom only if there's a previous location*/
if (mLatLng != null){
mLocationStatus.setVisibility(View.GONE);
mMarkerOption.position(mLatLng);
mMarker = mMap.addMarker(mMarkerOption);
mRefreshLocation = false; // just show this position; don't change it...
mMarker.setDraggable(mCaptureLocation);
mZoomed = true;
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mLatLng, 16));
}
mCancelLocation = (Button) findViewById(R.id.cancel_location);
mCancelLocation.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "cancelLocation", "cancel");
finish();
}
});
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// make sure we have a good location provider before continuing
List<String> providers = mLocationManager.getProviders(true);
for (String provider : providers) {
if (provider.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) {
mGPSOn = true;
}
if (provider.equalsIgnoreCase(LocationManager.NETWORK_PROVIDER)) {
mNetworkOn = true;
}
}
if (!mGPSOn && !mNetworkOn) {
Toast.makeText(getBaseContext(), getString(R.string.provider_disabled_error),
Toast.LENGTH_SHORT).show();
finish();
}
if ( mGPSOn ) {
Location loc = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if ( loc != null ) {
InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() +
" lastKnownLocation(GPS) lat: " +
loc.getLatitude() + " long: " +
loc.getLongitude() + " acc: " +
loc.getAccuracy() );
} else {
InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() +
" lastKnownLocation(GPS) null location");
}
}
if ( mNetworkOn ) {
Location loc = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if ( loc != null ) {
InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() +
" lastKnownLocation(Network) lat: " +
loc.getLatitude() + " long: " +
loc.getLongitude() + " acc: " +
loc.getAccuracy() );
} else {
InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() +
" lastKnownLocation(Network) null location");
}
}
mAcceptLocation = (Button) findViewById(R.id.accept_location);
if (mCaptureLocation){
mAcceptLocation.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "acceptLocation", "OK");
returnLocation();
}
});
mMap.setOnMapLongClickListener(this);
}else{
mAcceptLocation.setVisibility(View.GONE);
}
mReloadLocation = (Button) findViewById(R.id.reload_location);
if (mCaptureLocation) {
mReloadLocation.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mRefreshLocation = true;
mReloadLocation.setVisibility(View.GONE);
mLocationStatus.setVisibility(View.VISIBLE);
if (mGPSOn) {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, GeoPointMapActivity.this);
}
if (mNetworkOn) {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, GeoPointMapActivity.this);
}
}
});
mReloadLocation.setVisibility(!mRefreshLocation ? View.VISIBLE : View.GONE);
} else {
mReloadLocation.setVisibility(View.GONE);
}
// Focuses on marked location
mShowLocation = ((Button) findViewById(R.id.show_location));
mShowLocation.setVisibility(View.VISIBLE);
mShowLocation.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "showLocation", "onClick");
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mLatLng,
16));
}
});
mShowLocation.setClickable(mMarker != null);
}
private void stopGeolocating() {
mRefreshLocation = false;
mReloadLocation.setVisibility(View.VISIBLE);
mLocationManager.removeUpdates(this);
mMarker.setDraggable(true);
mLocationStatus.setVisibility(View.GONE);
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
private void returnLocation() {
if (mIsDragged){
Log.i(getClass().getName(), "IsDragged !!!");
Intent i = new Intent();
i.putExtra(
FormEntryActivity.LOCATION_RESULT,
mLatLng.latitude + " " + mLatLng.longitude + " "
+ 0 + " " + 0);
setResult(RESULT_OK, i);
} else if (mLocation != null) {
Log.i(getClass().getName(), "IsNotDragged !!!");
Intent i = new Intent();
i.putExtra(
FormEntryActivity.LOCATION_RESULT,
mLocation.getLatitude() + " " + mLocation.getLongitude() + " "
+ mLocation.getAltitude() + " " + mLocation.getAccuracy());
setResult(RESULT_OK, i);
}
finish();
}
private String truncateFloat(float f) {
return new DecimalFormat("#.##").format(f);
}
@Override
protected void onPause() {
super.onPause();
mLocationManager.removeUpdates(this);
}
@Override
protected void onResume() {
super.onResume();
if ( mRefreshLocation ) {
mLocationStatus.setVisibility(View.VISIBLE);
if (mGPSOn) {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, this);
}
if (mNetworkOn) {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
}
}
@Override
public void onLocationChanged(Location location) {
if (mRefreshLocation) {
mLocation = location;
if (mLocation != null) {
// Bug report: cached GeoPoint is being returned as the first value.
// Wait for the 2nd value to be returned, which is hopefully not cached?
++mLocationCount;
InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() +
" onLocationChanged(" + mLocationCount + ") lat: " +
mLocation.getLatitude() + " long: " +
mLocation.getLongitude() + " acc: " +
mLocation.getAccuracy() );
if (mLocationCount > 1) {
mLocationStatus.setText(getString(R.string.location_provider_accuracy,
mLocation.getProvider(), truncateFloat(mLocation.getAccuracy())));
mLatLng = new LatLng(mLocation.getLatitude(),
mLocation.getLongitude());
if ( !mZoomed ) {
mZoomed = true;
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mLatLng, 16));
} else {
mMap.animateCamera(CameraUpdateFactory.newLatLng(mLatLng));
}
// create a marker on the map or move the existing marker to the
// new location
if (mMarker == null) {
mMarkerOption.position(mLatLng);
mMarker = mMap.addMarker(mMarkerOption);
mShowLocation.setClickable(true);
} else {
mMarker.setPosition(mLatLng);
}
//If location is accurate enough, stop updating position and make the marker draggable
if (mLocation.getAccuracy() <= mLocationAccuracy) {
stopGeolocating();
}
}
} else {
InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() +
" onLocationChanged(" + mLocationCount + ") null location");
}
}
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onMarkerDrag(Marker arg0) {
}
@Override
public void onMarkerDragEnd(Marker marker) {
mLatLng = marker.getPosition();
mAcceptLocation.setClickable(true);
mIsDragged = true;
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mLatLng, mMap.getCameraPosition().zoom));
}
@Override
public void onMarkerDragStart(Marker arg0) {
stopGeolocating();
}
@Override
public void onMapLongClick(LatLng latLng) {
if (mMarker == null) {
mMarkerOption.position(latLng);
mMarker = mMap.addMarker(mMarkerOption);
mShowLocation.setClickable(true);
} else {
mMarker.setPosition(latLng);
}
mLatLng=latLng;
mIsDragged = true;
stopGeolocating();
mMarker.setDraggable(true);
}
}
|
0nima0-f
|
src/org/odk/collect/android/activities/GeoPointMapActivity.java
|
Java
|
asf20
| 13,796
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.activities;
import java.text.DecimalFormat;
import java.util.List;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.InfoLogger;
import org.odk.collect.android.widgets.GeoPointWidget;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.widget.Toast;
public class GeoPointActivity extends Activity implements LocationListener {
private static final String LOCATION_COUNT = "locationCount";
private ProgressDialog mLocationDialog;
private LocationManager mLocationManager;
private Location mLocation;
private boolean mGPSOn = false;
private boolean mNetworkOn = false;
private double mLocationAccuracy;
private int mLocationCount = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ( savedInstanceState != null ) {
mLocationCount = savedInstanceState.getInt(LOCATION_COUNT);
}
Intent intent = getIntent();
mLocationAccuracy = GeoPointWidget.DEFAULT_LOCATION_ACCURACY;
if (intent != null && intent.getExtras() != null) {
if ( intent.hasExtra(GeoPointWidget.ACCURACY_THRESHOLD) ) {
mLocationAccuracy = intent.getDoubleExtra(GeoPointWidget.ACCURACY_THRESHOLD, GeoPointWidget.DEFAULT_LOCATION_ACCURACY);
}
}
setTitle(getString(R.string.app_name) + " > " + getString(R.string.get_location));
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// make sure we have a good location provider before continuing
List<String> providers = mLocationManager.getProviders(true);
for (String provider : providers) {
if (provider.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) {
mGPSOn = true;
}
if (provider.equalsIgnoreCase(LocationManager.NETWORK_PROVIDER)) {
mNetworkOn = true;
}
}
if (!mGPSOn && !mNetworkOn) {
Toast.makeText(getBaseContext(), getString(R.string.provider_disabled_error),
Toast.LENGTH_SHORT).show();
finish();
}
if ( mGPSOn ) {
Location loc = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if ( loc != null ) {
InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() +
" lastKnownLocation(GPS) lat: " +
loc.getLatitude() + " long: " +
loc.getLongitude() + " acc: " +
loc.getAccuracy() );
} else {
InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() +
" lastKnownLocation(GPS) null location");
}
}
if ( mNetworkOn ) {
Location loc = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if ( loc != null ) {
InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() +
" lastKnownLocation(Network) lat: " +
loc.getLatitude() + " long: " +
loc.getLongitude() + " acc: " +
loc.getAccuracy() );
} else {
InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() +
" lastKnownLocation(Network) null location");
}
}
setupLocationDialog();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(LOCATION_COUNT, mLocationCount);
}
@Override
protected void onPause() {
super.onPause();
// stops the GPS. Note that this will turn off the GPS if the screen goes to sleep.
mLocationManager.removeUpdates(this);
// We're not using managed dialogs, so we have to dismiss the dialog to prevent it from
// leaking memory.
if (mLocationDialog != null && mLocationDialog.isShowing())
mLocationDialog.dismiss();
}
@Override
protected void onResume() {
super.onResume();
if (mGPSOn) {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
if (mNetworkOn) {
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
mLocationDialog.show();
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
/**
* Sets up the look and actions for the progress dialog while the GPS is searching.
*/
private void setupLocationDialog() {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "setupLocationDialog", "show");
// dialog displayed while fetching gps location
mLocationDialog = new ProgressDialog(this);
DialogInterface.OnClickListener geopointButtonListener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
Collect.getInstance().getActivityLogger().logInstanceAction(this, "acceptLocation", "OK");
returnLocation();
break;
case DialogInterface. BUTTON_NEGATIVE:
Collect.getInstance().getActivityLogger().logInstanceAction(this, "cancelLocation", "cancel");
mLocation = null;
finish();
break;
}
}
};
// back button doesn't cancel
mLocationDialog.setCancelable(false);
mLocationDialog.setIndeterminate(true);
mLocationDialog.setIcon(android.R.drawable.ic_dialog_info);
mLocationDialog.setTitle(getString(R.string.getting_location));
mLocationDialog.setMessage(getString(R.string.please_wait_long));
mLocationDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.accept_location),
geopointButtonListener);
mLocationDialog.setButton(DialogInterface. BUTTON_NEGATIVE, getString(R.string.cancel_location),
geopointButtonListener);
}
private void returnLocation() {
if (mLocation != null) {
Intent i = new Intent();
i.putExtra(
FormEntryActivity.LOCATION_RESULT,
mLocation.getLatitude() + " " + mLocation.getLongitude() + " "
+ mLocation.getAltitude() + " " + mLocation.getAccuracy());
setResult(RESULT_OK, i);
}
finish();
}
@Override
public void onLocationChanged(Location location) {
mLocation = location;
if (mLocation != null) {
// Bug report: cached GeoPoint is being returned as the first value.
// Wait for the 2nd value to be returned, which is hopefully not cached?
++mLocationCount;
InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() +
" onLocationChanged(" + mLocationCount + ") lat: " +
mLocation.getLatitude() + " long: " +
mLocation.getLongitude() + " acc: " +
mLocation.getAccuracy() );
if (mLocationCount > 1) {
mLocationDialog.setMessage(getString(R.string.location_provider_accuracy,
mLocation.getProvider(), truncateDouble(mLocation.getAccuracy())));
if (mLocation.getAccuracy() <= mLocationAccuracy) {
returnLocation();
}
}
} else {
InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() +
" onLocationChanged(" + mLocationCount + ") null location");
}
}
private String truncateDouble(float number) {
DecimalFormat df = new DecimalFormat("#.##");
return df.format(number);
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case LocationProvider.AVAILABLE:
if (mLocation != null) {
mLocationDialog.setMessage(getString(R.string.location_accuracy,
mLocation.getAccuracy()));
}
break;
case LocationProvider.OUT_OF_SERVICE:
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
break;
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/activities/GeoPointActivity.java
|
Java
|
asf20
| 9,894
|
package org.odk.collect.android.activities;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.TypedValue;
import android.widget.TextView;
public class NotificationActivity extends Activity {
public final static String NOTIFICATION_KEY = "message";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notification_layout);
String note = this.getIntent().getStringExtra(NOTIFICATION_KEY);
if (note == null) {
note = getString(R.string.notification_error);
}
TextView notificationText = (TextView)findViewById(R.id.notification);
notificationText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, Collect.getQuestionFontsize());
notificationText.setTypeface(null, Typeface.BOLD);
notificationText.setPadding(0, 0, 0, 7);
notificationText.setText(note);
}
}
|
0nima0-f
|
src/org/odk/collect/android/activities/NotificationActivity.java
|
Java
|
asf20
| 1,078
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.activities;
import java.util.ArrayList;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.odk.collect.android.provider.InstanceProviderAPI;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import org.odk.collect.android.receivers.NetworkReceiver;
import org.odk.collect.android.utilities.CompatibilityUtils;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
/**
* Responsible for displaying all the valid forms in the forms directory. Stores
* the path to selected form for use by {@link MainMenuActivity}.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class InstanceUploaderList extends ListActivity implements
OnLongClickListener {
private static final String BUNDLE_SELECTED_ITEMS_KEY = "selected_items";
private static final String BUNDLE_TOGGLED_KEY = "toggled";
private static final int MENU_PREFERENCES = Menu.FIRST;
private static final int MENU_SHOW_UNSENT = Menu.FIRST + 1;
private static final int INSTANCE_UPLOADER = 0;
private static final int GOOGLE_USER_DIALOG = 1;
private Button mUploadButton;
private Button mToggleButton;
private boolean mShowUnsent = true;
private SimpleCursorAdapter mInstances;
private ArrayList<Long> mSelected = new ArrayList<Long>();
private boolean mRestored = false;
private boolean mToggled = false;
public Cursor getUnsentCursor() {
// get all complete or failed submission instances
String selection = InstanceColumns.STATUS + "=? or "
+ InstanceColumns.STATUS + "=?";
String selectionArgs[] = { InstanceProviderAPI.STATUS_COMPLETE,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED };
String sortOrder = InstanceColumns.DISPLAY_NAME + " ASC";
Cursor c = managedQuery(InstanceColumns.CONTENT_URI, null, selection,
selectionArgs, sortOrder);
return c;
}
public Cursor getAllCursor() {
// get all complete or failed submission instances
String selection = InstanceColumns.STATUS + "=? or "
+ InstanceColumns.STATUS + "=? or " + InstanceColumns.STATUS
+ "=?";
String selectionArgs[] = { InstanceProviderAPI.STATUS_COMPLETE,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED,
InstanceProviderAPI.STATUS_SUBMITTED };
String sortOrder = InstanceColumns.DISPLAY_NAME + " ASC";
Cursor c = managedQuery(InstanceColumns.CONTENT_URI, null, selection,
selectionArgs, sortOrder);
return c;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.instance_uploader_list);
// set up long click listener
mUploadButton = (Button) findViewById(R.id.upload_button);
mUploadButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
if (NetworkReceiver.running == true) {
Toast.makeText(
InstanceUploaderList.this,
"Background send running, please try again shortly",
Toast.LENGTH_SHORT).show();
} else if (ni == null || !ni.isConnected()) {
Collect.getInstance().getActivityLogger()
.logAction(this, "uploadButton", "noConnection");
Toast.makeText(InstanceUploaderList.this,
R.string.no_connection, Toast.LENGTH_SHORT).show();
} else {
Collect.getInstance()
.getActivityLogger()
.logAction(this, "uploadButton",
Integer.toString(mSelected.size()));
if (mSelected.size() > 0) {
// items selected
uploadSelectedFiles();
mToggled = false;
mSelected.clear();
InstanceUploaderList.this.getListView().clearChoices();
mUploadButton.setEnabled(false);
} else {
// no items selected
Toast.makeText(getApplicationContext(),
getString(R.string.noselect_error),
Toast.LENGTH_SHORT).show();
}
}
}
});
mToggleButton = (Button) findViewById(R.id.toggle_button);
mToggleButton.setLongClickable(true);
mToggleButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// toggle selections of items to all or none
ListView ls = getListView();
mToggled = !mToggled;
Collect.getInstance()
.getActivityLogger()
.logAction(this, "toggleButton",
Boolean.toString(mToggled));
// remove all items from selected list
mSelected.clear();
for (int pos = 0; pos < ls.getCount(); pos++) {
ls.setItemChecked(pos, mToggled);
// add all items if mToggled sets to select all
if (mToggled)
mSelected.add(ls.getItemIdAtPosition(pos));
}
mUploadButton.setEnabled(!(mSelected.size() == 0));
}
});
mToggleButton.setOnLongClickListener(this);
Cursor c = mShowUnsent ? getUnsentCursor() : getAllCursor();
String[] data = new String[] { InstanceColumns.DISPLAY_NAME,
InstanceColumns.DISPLAY_SUBTEXT };
int[] view = new int[] { R.id.text1, R.id.text2 };
// render total instance view
mInstances = new SimpleCursorAdapter(this,
R.layout.two_item_multiple_choice, c, data, view);
setListAdapter(mInstances);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
getListView().setItemsCanFocus(false);
mUploadButton.setEnabled(!(mSelected.size() == 0));
// set title
setTitle(getString(R.string.app_name) + " > "
+ getString(R.string.send_data));
// if current activity is being reinitialized due to changing
// orientation restore all check
// marks for ones selected
if (mRestored) {
ListView ls = getListView();
for (long id : mSelected) {
for (int pos = 0; pos < ls.getCount(); pos++) {
if (id == ls.getItemIdAtPosition(pos)) {
ls.setItemChecked(pos, true);
break;
}
}
}
mRestored = false;
}
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
private void uploadSelectedFiles() {
// send list of _IDs.
long[] instanceIDs = new long[mSelected.size()];
for (int i = 0; i < mSelected.size(); i++) {
instanceIDs[i] = mSelected.get(i);
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String server = prefs.getString(PreferencesActivity.KEY_PROTOCOL, null);
if (server.equalsIgnoreCase(getString(R.string.protocol_google_maps_engine))) {
// if it's maps engine, start the maps-engine uploader
// first make sure we have a google account selected
String googleUsername = prefs.getString(
PreferencesActivity.KEY_SELECTED_GOOGLE_ACCOUNT, null);
if (googleUsername == null || googleUsername.equals("")) {
showDialog(GOOGLE_USER_DIALOG);
return;
}
Intent i = new Intent(this, GoogleMapsEngineUploaderActivity.class);
i.putExtra(FormEntryActivity.KEY_INSTANCES, instanceIDs);
startActivityForResult(i, INSTANCE_UPLOADER);
} else {
// otherwise, do the normal agregate/other thing.
Intent i = new Intent(this, InstanceUploaderActivity.class);
i.putExtra(FormEntryActivity.KEY_INSTANCES, instanceIDs);
startActivityForResult(i, INSTANCE_UPLOADER);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Collect.getInstance().getActivityLogger()
.logAction(this, "onCreateOptionsMenu", "show");
super.onCreateOptionsMenu(menu);
CompatibilityUtils.setShowAsAction(
menu.add(0, MENU_PREFERENCES, 0, R.string.general_preferences)
.setIcon(R.drawable.ic_menu_preferences),
MenuItem.SHOW_AS_ACTION_NEVER);
CompatibilityUtils.setShowAsAction(
menu.add(0, MENU_SHOW_UNSENT, 1, R.string.change_view)
.setIcon(R.drawable.ic_menu_manage),
MenuItem.SHOW_AS_ACTION_NEVER);
return true;
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case MENU_PREFERENCES:
Collect.getInstance().getActivityLogger()
.logAction(this, "onMenuItemSelected", "MENU_PREFERENCES");
createPreferencesMenu();
return true;
case MENU_SHOW_UNSENT:
Collect.getInstance().getActivityLogger()
.logAction(this, "onMenuItemSelected", "MENU_SHOW_UNSENT");
showSentAndUnsentChoices();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
private void createPreferencesMenu() {
Intent i = new Intent(this, PreferencesActivity.class);
startActivity(i);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// get row id from db
Cursor c = (Cursor) getListAdapter().getItem(position);
long k = c.getLong(c.getColumnIndex(InstanceColumns._ID));
Collect.getInstance().getActivityLogger()
.logAction(this, "onListItemClick", Long.toString(k));
// add/remove from selected list
if (mSelected.contains(k))
mSelected.remove(k);
else
mSelected.add(k);
mUploadButton.setEnabled(!(mSelected.size() == 0));
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
long[] selectedArray = savedInstanceState
.getLongArray(BUNDLE_SELECTED_ITEMS_KEY);
for (int i = 0; i < selectedArray.length; i++)
mSelected.add(selectedArray[i]);
mToggled = savedInstanceState.getBoolean(BUNDLE_TOGGLED_KEY);
mRestored = true;
mUploadButton.setEnabled(selectedArray.length > 0);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
long[] selectedArray = new long[mSelected.size()];
for (int i = 0; i < mSelected.size(); i++)
selectedArray[i] = mSelected.get(i);
outState.putLongArray(BUNDLE_SELECTED_ITEMS_KEY, selectedArray);
outState.putBoolean(BUNDLE_TOGGLED_KEY, mToggled);
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (resultCode == RESULT_CANCELED) {
return;
}
switch (requestCode) {
// returns with a form path, start entry
case INSTANCE_UPLOADER:
if (intent.getBooleanExtra(FormEntryActivity.KEY_SUCCESS, false)) {
mSelected.clear();
getListView().clearChoices();
if (mInstances.isEmpty()) {
finish();
}
}
break;
default:
break;
}
super.onActivityResult(requestCode, resultCode, intent);
}
private void showUnsent() {
mShowUnsent = true;
Cursor c = mShowUnsent ? getUnsentCursor() : getAllCursor();
Cursor old = mInstances.getCursor();
try {
mInstances.changeCursor(c);
} finally {
if (old != null) {
old.close();
this.stopManagingCursor(old);
}
}
getListView().invalidate();
}
private void showAll() {
mShowUnsent = false;
Cursor c = mShowUnsent ? getUnsentCursor() : getAllCursor();
Cursor old = mInstances.getCursor();
try {
mInstances.changeCursor(c);
} finally {
if (old != null) {
old.close();
this.stopManagingCursor(old);
}
}
getListView().invalidate();
}
@Override
public boolean onLongClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logAction(this, "toggleButton.longClick",
Boolean.toString(mToggled));
return showSentAndUnsentChoices();
}
private boolean showSentAndUnsentChoices() {
/**
* Create a dialog with options to save and exit, save, or quit without
* saving
*/
String[] items = { getString(R.string.show_unsent_forms),
getString(R.string.show_sent_and_unsent_forms) };
Collect.getInstance().getActivityLogger()
.logAction(this, "changeView", "show");
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_info)
.setTitle(getString(R.string.change_view))
.setNeutralButton(getString(R.string.cancel),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
Collect.getInstance()
.getActivityLogger()
.logAction(this, "changeView", "cancel");
dialog.cancel();
}
})
.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0: // show unsent
Collect.getInstance()
.getActivityLogger()
.logAction(this, "changeView", "showUnsent");
InstanceUploaderList.this.showUnsent();
break;
case 1: // show all
Collect.getInstance().getActivityLogger()
.logAction(this, "changeView", "showAll");
InstanceUploaderList.this.showAll();
break;
case 2:// do nothing
break;
}
}
}).create();
alertDialog.show();
return true;
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case GOOGLE_USER_DIALOG:
AlertDialog.Builder gudBuilder = new AlertDialog.Builder(this);
gudBuilder.setTitle(R.string.no_google_account);
gudBuilder
.setMessage("You have selected Google Maps Engine as your server, please select a corresponding Google Account in the General Settings before continuing");
gudBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
gudBuilder.setCancelable(false);
return gudBuilder.create();
}
return null;
}
}
|
0nima0-f
|
src/org/odk/collect/android/activities/InstanceUploaderList.java
|
Java
|
asf20
| 15,275
|
/*
* Copyright (C) 2012 University of Washington
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.activities;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.ColorPickerDialog;
import org.odk.collect.android.utilities.FileUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
/**
* Modified from the FingerPaint example found in The Android Open Source
* Project.
*
* @author BehrAtherton@gmail.com
*
*/
public class DrawActivity extends Activity {
public static final String t = "DrawActivity";
public static final String OPTION = "option";
public static final String OPTION_SIGNATURE = "signature";
public static final String OPTION_ANNOTATE = "annotate";
public static final String OPTION_DRAW = "draw";
public static final String REF_IMAGE = "refImage";
public static final String EXTRA_OUTPUT = android.provider.MediaStore.EXTRA_OUTPUT;
public static final String SAVEPOINT_IMAGE = "savepointImage"; // during
// restore
// incoming options...
private String loadOption = null;
private File refImage = null;
private File output = null;
private File savepointImage = null;
private Button btnDrawColor;
private Button btnFinished;
private Button btnReset;
private Button btnCancel;
private Paint paint;
private Paint pointPaint;
private int currentColor = 0xFF000000;
private DrawView drawView;
private String alertTitleString;
private AlertDialog alertDialog;
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
try {
saveFile(savepointImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if ( savepointImage.exists() ) {
outState.putString(SAVEPOINT_IMAGE, savepointImage.getAbsolutePath());
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
Bundle extras = getIntent().getExtras();
if (extras == null) {
loadOption = OPTION_DRAW;
refImage = null;
savepointImage = new File(Collect.TMPDRAWFILE_PATH);
savepointImage.delete();
output = new File(Collect.TMPFILE_PATH);
} else {
loadOption = extras.getString(OPTION);
if (loadOption == null) {
loadOption = OPTION_DRAW;
}
// refImage can also be present if resuming a drawing
Uri uri = (Uri) extras.get(REF_IMAGE);
if (uri != null) {
refImage = new File(uri.getPath());
}
String savepoint = extras.getString(SAVEPOINT_IMAGE);
if (savepoint != null) {
savepointImage = new File(savepoint);
if (!savepointImage.exists() && refImage != null
&& refImage.exists()) {
FileUtils.copyFile(refImage, savepointImage);
}
} else {
savepointImage = new File(Collect.TMPDRAWFILE_PATH);
savepointImage.delete();
if (refImage != null && refImage.exists()) {
FileUtils.copyFile(refImage, savepointImage);
}
}
uri = (Uri) extras.get(EXTRA_OUTPUT);
if (uri != null) {
output = new File(uri.getPath());
} else {
output = new File(Collect.TMPFILE_PATH);
}
}
// At this point, we have:
// loadOption -- type of activity (draw, signature, annotate)
// refImage -- original image to work with
// savepointImage -- drawing to use as a starting point (may be copy of
// original)
// output -- where the output should be written
if (OPTION_SIGNATURE.equals(loadOption)) {
// set landscape
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
alertTitleString = getString(R.string.quit_application,
getString(R.string.sign_button));
} else if (OPTION_ANNOTATE.equals(loadOption)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
alertTitleString = getString(R.string.quit_application,
getString(R.string.markup_image));
} else {
alertTitleString = getString(R.string.quit_application,
getString(R.string.draw_image));
}
setTitle(getString(R.string.app_name) + " > "
+ getString(R.string.draw_image));
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout v = (RelativeLayout) inflater.inflate(
R.layout.draw_layout, null);
LinearLayout ll = (LinearLayout) v.findViewById(R.id.drawViewLayout);
drawView = new DrawView(this, OPTION_SIGNATURE.equals(loadOption),
savepointImage);
ll.addView(drawView);
setContentView(v);
paint = new Paint();
paint.setAntiAlias(true);
paint.setDither(true);
paint.setColor(currentColor);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(10);
pointPaint = new Paint();
pointPaint.setAntiAlias(true);
pointPaint.setDither(true);
pointPaint.setColor(currentColor);
pointPaint.setStyle(Paint.Style.FILL_AND_STROKE);
pointPaint.setStrokeWidth(10);
btnDrawColor = (Button) findViewById(R.id.btnSelectColor);
btnDrawColor.setTextColor(getInverseColor(currentColor));
btnDrawColor.getBackground().setColorFilter(currentColor,
PorterDuff.Mode.SRC_ATOP);
btnDrawColor.setText(getString(R.string.set_color));
btnDrawColor.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(
DrawActivity.this,
"setColorButton",
"click",
Collect.getInstance().getFormController()
.getFormIndex());
ColorPickerDialog cpd = new ColorPickerDialog(
DrawActivity.this,
new ColorPickerDialog.OnColorChangedListener() {
public void colorChanged(String key, int color) {
btnDrawColor
.setTextColor(getInverseColor(color));
btnDrawColor.getBackground().setColorFilter(
color, PorterDuff.Mode.SRC_ATOP);
currentColor = color;
paint.setColor(color);
pointPaint.setColor(color);
}
}, "key", currentColor, currentColor,
getString(R.string.select_drawing_color));
cpd.show();
}
});
btnFinished = (Button) findViewById(R.id.btnFinishDraw);
btnFinished.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(
DrawActivity.this,
"saveAndCloseButton",
"click",
Collect.getInstance().getFormController()
.getFormIndex());
SaveAndClose();
}
});
btnReset = (Button) findViewById(R.id.btnResetDraw);
btnReset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(
DrawActivity.this,
"resetButton",
"click",
Collect.getInstance().getFormController()
.getFormIndex());
Reset();
}
});
btnCancel = (Button) findViewById(R.id.btnCancelDraw);
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(
DrawActivity.this,
"cancelAndCloseButton",
"click",
Collect.getInstance().getFormController()
.getFormIndex());
CancelAndClose();
}
});
}
private int getInverseColor(int color) {
int red = Color.red(color);
int green = Color.green(color);
int blue = Color.blue(color);
int alpha = Color.alpha(color);
return Color.argb(alpha, 255 - red, 255 - green, 255 - blue);
}
private void SaveAndClose() {
try {
saveFile(output);
setResult(Activity.RESULT_OK);
} catch (FileNotFoundException e) {
e.printStackTrace();
setResult(Activity.RESULT_CANCELED);
}
this.finish();
}
private void saveFile(File f) throws FileNotFoundException {
if ( drawView.getWidth() == 0 || drawView.getHeight() == 0 ) {
// apparently on 4.x, the orientation change notification can occur
// sometime before the view is rendered. In that case, the view
// dimensions will not be known.
Log.e(t,"view has zero width or zero height");
} else {
FileOutputStream fos;
fos = new FileOutputStream(f);
Bitmap bitmap = Bitmap.createBitmap(drawView.getWidth(),
drawView.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawView.draw(canvas);
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fos);
try {
if ( fos != null ) {
fos.flush();
fos.close();
}
} catch ( Exception e) {
}
}
}
private void Reset() {
savepointImage.delete();
if (!OPTION_SIGNATURE.equals(loadOption) && refImage != null
&& refImage.exists()) {
FileUtils.copyFile(refImage, savepointImage);
}
drawView.reset();
drawView.invalidate();
}
private void CancelAndClose() {
setResult(Activity.RESULT_CANCELED);
this.finish();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "onKeyDown.KEYCODE_BACK", "quit");
createQuitDrawDialog();
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (event.isAltPressed()) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"onKeyDown.KEYCODE_DPAD_RIGHT", "showNext");
createQuitDrawDialog();
return true;
}
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (event.isAltPressed()) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onKeyDown.KEYCODE_DPAD_LEFT",
"showPrevious");
createQuitDrawDialog();
return true;
}
break;
}
return super.onKeyDown(keyCode, event);
}
/**
* Create a dialog with options to save and exit, save, or quit without
* saving
*/
private void createQuitDrawDialog() {
String[] items = { getString(R.string.keep_changes),
getString(R.string.do_not_save) };
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "createQuitDrawDialog", "show");
alertDialog = new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_info)
.setTitle(alertTitleString)
.setNeutralButton(getString(R.string.do_not_exit),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createQuitDrawDialog",
"cancel");
dialog.cancel();
}
})
.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0: // save and exit
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createQuitDrawDialog",
"saveAndExit");
SaveAndClose();
break;
case 1: // discard changes and exit
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createQuitDrawDialog",
"discardAndExit");
CancelAndClose();
break;
case 2:// do nothing
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createQuitDrawDialog", "cancel");
break;
}
}
}).create();
alertDialog.show();
}
public class DrawView extends View {
private boolean isSignature;
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mCurrentPath;
private Paint mBitmapPaint;
private File mBackgroundBitmapFile;
public DrawView(final Context c) {
super(c);
isSignature = false;
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
mCurrentPath = new Path();
setBackgroundColor(0xFFFFFFFF);
mBackgroundBitmapFile = new File(Collect.TMPDRAWFILE_PATH);
}
public DrawView(Context c, boolean isSignature, File f) {
this(c);
this.isSignature = isSignature;
mBackgroundBitmapFile = f;
}
public void reset() {
Display display = ((WindowManager) getContext().getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
resetImage(screenWidth, screenHeight);
}
public void resetImage(int w, int h) {
if (mBackgroundBitmapFile.exists()) {
mBitmap = FileUtils.getBitmapScaledToDisplay(
mBackgroundBitmapFile, w, h).copy(
Bitmap.Config.ARGB_8888, true);
// mBitmap =
// Bitmap.createScaledBitmap(BitmapFactory.decodeFile(mBackgroundBitmapFile.getPath()),
// w, h, true);
mCanvas = new Canvas(mBitmap);
} else {
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
mCanvas.drawColor(0xFFFFFFFF);
if (isSignature)
drawSignLine();
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
resetImage(w, h);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(0xFFAAAAAA);
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mCurrentPath, paint);
}
private float mX, mY;
private void touch_start(float x, float y) {
mCurrentPath.reset();
mCurrentPath.moveTo(x, y);
mX = x;
mY = y;
}
public void drawSignLine() {
mCanvas.drawLine(0, (int) (mCanvas.getHeight() * .7),
mCanvas.getWidth(), (int) (mCanvas.getHeight() * .7), paint);
}
private void touch_move(float x, float y) {
mCurrentPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
private void touch_up() {
if (mCurrentPath.isEmpty()) {
mCanvas.drawPoint(mX, mY, pointPaint);
} else {
mCurrentPath.lineTo(mX, mY);
// commit the path to our offscreen
mCanvas.drawPath(mCurrentPath, paint);
}
// kill this so we don't double draw
mCurrentPath.reset();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/activities/DrawActivity.java
|
Java
|
asf20
| 16,699
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.activities;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.Map.Entry;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.preferences.AdminPreferencesActivity;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.odk.collect.android.provider.InstanceProviderAPI;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import org.odk.collect.android.utilities.CompatibilityUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**
* Responsible for displaying buttons to launch the major activities. Launches
* some activities based on returns of others.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class MainMenuActivity extends Activity {
private static final String t = "MainMenuActivity";
private static final int PASSWORD_DIALOG = 1;
// menu options
private static final int MENU_PREFERENCES = Menu.FIRST;
private static final int MENU_ADMIN = Menu.FIRST + 1;
// buttons
private Button mEnterDataButton;
private Button mManageFilesButton;
private Button mSendDataButton;
private Button mReviewDataButton;
private Button mGetFormsButton;
private View mReviewSpacer;
private View mGetFormsSpacer;
private AlertDialog mAlertDialog;
private SharedPreferences mAdminPreferences;
private int mCompletedCount;
private int mSavedCount;
private Cursor mFinalizedCursor;
private Cursor mSavedCursor;
private IncomingHandler mHandler = new IncomingHandler(this);
private MyContentObserver mContentObserver = new MyContentObserver();
private static boolean EXIT = true;
// private static boolean DO_NOT_EXIT = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// must be at the beginning of any activity that can be called from an
// external intent
Log.i(t, "Starting up, creating directories");
try {
Collect.createODKDirs();
} catch (RuntimeException e) {
createErrorDialog(e.getMessage(), EXIT);
return;
}
setContentView(R.layout.main_menu);
{
// dynamically construct the "ODK Collect vA.B" string
TextView mainMenuMessageLabel = (TextView) findViewById(R.id.main_menu_header);
mainMenuMessageLabel.setText(Collect.getInstance()
.getVersionedAppName());
}
setTitle(getString(R.string.app_name) + " > "
+ getString(R.string.main_menu));
File f = new File(Collect.ODK_ROOT + "/collect.settings");
if (f.exists()) {
boolean success = loadSharedPreferencesFromFile(f);
if (success) {
Toast.makeText(this,
"Settings successfully loaded from file",
Toast.LENGTH_LONG).show();
f.delete();
} else {
Toast.makeText(
this,
"Sorry, settings file is corrupt and should be deleted or replaced",
Toast.LENGTH_LONG).show();
}
}
mReviewSpacer = findViewById(R.id.review_spacer);
mGetFormsSpacer = findViewById(R.id.get_forms_spacer);
mAdminPreferences = this.getSharedPreferences(
AdminPreferencesActivity.ADMIN_PREFERENCES, 0);
// enter data button. expects a result.
mEnterDataButton = (Button) findViewById(R.id.enter_data);
mEnterDataButton.setText(getString(R.string.enter_data_button));
mEnterDataButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger()
.logAction(this, "fillBlankForm", "click");
Intent i = new Intent(getApplicationContext(),
FormChooserList.class);
startActivity(i);
}
});
// review data button. expects a result.
mReviewDataButton = (Button) findViewById(R.id.review_data);
mReviewDataButton.setText(getString(R.string.review_data_button));
mReviewDataButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger()
.logAction(this, "editSavedForm", "click");
Intent i = new Intent(getApplicationContext(),
InstanceChooserList.class);
startActivity(i);
}
});
// send data button. expects a result.
mSendDataButton = (Button) findViewById(R.id.send_data);
mSendDataButton.setText(getString(R.string.send_data_button));
mSendDataButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger()
.logAction(this, "uploadForms", "click");
Intent i = new Intent(getApplicationContext(),
InstanceUploaderList.class);
startActivity(i);
}
});
// manage forms button. no result expected.
mGetFormsButton = (Button) findViewById(R.id.get_forms);
mGetFormsButton.setText(getString(R.string.get_forms));
mGetFormsButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger()
.logAction(this, "downloadBlankForms", "click");
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(MainMenuActivity.this);
String protocol = sharedPreferences.getString(
PreferencesActivity.KEY_PROTOCOL, getString(R.string.protocol_odk_default));
Intent i = null;
if (protocol.equalsIgnoreCase(getString(R.string.protocol_google_maps_engine))) {
i = new Intent(getApplicationContext(),
GoogleDriveActivity.class);
} else {
i = new Intent(getApplicationContext(),
FormDownloadList.class);
}
startActivity(i);
}
});
// manage forms button. no result expected.
mManageFilesButton = (Button) findViewById(R.id.manage_forms);
mManageFilesButton.setText(getString(R.string.manage_files));
mManageFilesButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger()
.logAction(this, "deleteSavedForms", "click");
Intent i = new Intent(getApplicationContext(),
FileManagerTabs.class);
startActivity(i);
}
});
// count for finalized instances
String selection = InstanceColumns.STATUS + "=? or "
+ InstanceColumns.STATUS + "=?";
String selectionArgs[] = { InstanceProviderAPI.STATUS_COMPLETE,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED };
try {
mFinalizedCursor = managedQuery(InstanceColumns.CONTENT_URI, null,
selection, selectionArgs, null);
} catch (Exception e) {
createErrorDialog(e.getMessage(), EXIT);
return;
}
if (mFinalizedCursor != null) {
startManagingCursor(mFinalizedCursor);
}
mCompletedCount = mFinalizedCursor != null ? mFinalizedCursor.getCount() : 0;
getContentResolver().registerContentObserver(InstanceColumns.CONTENT_URI, true, mContentObserver);
// mFinalizedCursor.registerContentObserver(mContentObserver);
// count for finalized instances
String selectionSaved = InstanceColumns.STATUS + "=?";
String selectionArgsSaved[] = { InstanceProviderAPI.STATUS_INCOMPLETE };
try {
mSavedCursor = managedQuery(InstanceColumns.CONTENT_URI, null,
selectionSaved, selectionArgsSaved, null);
} catch (Exception e) {
createErrorDialog(e.getMessage(), EXIT);
return;
}
if (mSavedCursor != null) {
startManagingCursor(mSavedCursor);
}
mSavedCount = mSavedCursor != null ? mSavedCursor.getCount() : 0;
// don't need to set a content observer because it can't change in the
// background
updateButtons();
}
@Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = this.getSharedPreferences(
AdminPreferencesActivity.ADMIN_PREFERENCES, 0);
boolean edit = sharedPreferences.getBoolean(
AdminPreferencesActivity.KEY_EDIT_SAVED, true);
if (!edit) {
mReviewDataButton.setVisibility(View.GONE);
mReviewSpacer.setVisibility(View.GONE);
} else {
mReviewDataButton.setVisibility(View.VISIBLE);
mReviewSpacer.setVisibility(View.VISIBLE);
}
boolean send = sharedPreferences.getBoolean(
AdminPreferencesActivity.KEY_SEND_FINALIZED, true);
if (!send) {
mSendDataButton.setVisibility(View.GONE);
} else {
mSendDataButton.setVisibility(View.VISIBLE);
}
boolean get_blank = sharedPreferences.getBoolean(
AdminPreferencesActivity.KEY_GET_BLANK, true);
if (!get_blank) {
mGetFormsButton.setVisibility(View.GONE);
mGetFormsSpacer.setVisibility(View.GONE);
} else {
mGetFormsButton.setVisibility(View.VISIBLE);
mGetFormsSpacer.setVisibility(View.VISIBLE);
}
boolean delete_saved = sharedPreferences.getBoolean(
AdminPreferencesActivity.KEY_DELETE_SAVED, true);
if (!delete_saved) {
mManageFilesButton.setVisibility(View.GONE);
} else {
mManageFilesButton.setVisibility(View.VISIBLE);
}
}
@Override
protected void onPause() {
super.onPause();
if (mAlertDialog != null && mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Collect.getInstance().getActivityLogger()
.logAction(this, "onCreateOptionsMenu", "show");
super.onCreateOptionsMenu(menu);
CompatibilityUtils.setShowAsAction(
menu.add(0, MENU_PREFERENCES, 0, R.string.general_preferences)
.setIcon(R.drawable.ic_menu_preferences),
MenuItem.SHOW_AS_ACTION_NEVER);
CompatibilityUtils.setShowAsAction(
menu.add(0, MENU_ADMIN, 0, R.string.admin_preferences)
.setIcon(R.drawable.ic_menu_login),
MenuItem.SHOW_AS_ACTION_NEVER);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_PREFERENCES:
Collect.getInstance()
.getActivityLogger()
.logAction(this, "onOptionsItemSelected",
"MENU_PREFERENCES");
Intent ig = new Intent(this, PreferencesActivity.class);
startActivity(ig);
return true;
case MENU_ADMIN:
Collect.getInstance().getActivityLogger()
.logAction(this, "onOptionsItemSelected", "MENU_ADMIN");
String pw = mAdminPreferences.getString(
AdminPreferencesActivity.KEY_ADMIN_PW, "");
if ("".equalsIgnoreCase(pw)) {
Intent i = new Intent(getApplicationContext(),
AdminPreferencesActivity.class);
startActivity(i);
} else {
showDialog(PASSWORD_DIALOG);
Collect.getInstance().getActivityLogger()
.logAction(this, "createAdminPasswordDialog", "show");
}
return true;
}
return super.onOptionsItemSelected(item);
}
private void createErrorDialog(String errorMsg, final boolean shouldExit) {
Collect.getInstance().getActivityLogger()
.logAction(this, "createErrorDialog", "show");
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertDialog.setMessage(errorMsg);
DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON_POSITIVE:
Collect.getInstance()
.getActivityLogger()
.logAction(this, "createErrorDialog",
shouldExit ? "exitApplication" : "OK");
if (shouldExit) {
finish();
}
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.ok), errorListener);
mAlertDialog.show();
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PASSWORD_DIALOG:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final AlertDialog passwordDialog = builder.create();
passwordDialog.setTitle(getString(R.string.enter_admin_password));
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
input.setTransformationMethod(PasswordTransformationMethod
.getInstance());
passwordDialog.setView(input, 20, 10, 20, 10);
passwordDialog.setButton(AlertDialog.BUTTON_POSITIVE,
getString(R.string.ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
String value = input.getText().toString();
String pw = mAdminPreferences.getString(
AdminPreferencesActivity.KEY_ADMIN_PW, "");
if (pw.compareTo(value) == 0) {
Intent i = new Intent(getApplicationContext(),
AdminPreferencesActivity.class);
startActivity(i);
input.setText("");
passwordDialog.dismiss();
} else {
Toast.makeText(
MainMenuActivity.this,
getString(R.string.admin_password_incorrect),
Toast.LENGTH_SHORT).show();
Collect.getInstance()
.getActivityLogger()
.logAction(this, "adminPasswordDialog",
"PASSWORD_INCORRECT");
}
}
});
passwordDialog.setButton(AlertDialog.BUTTON_NEGATIVE,
getString(R.string.cancel),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance()
.getActivityLogger()
.logAction(this, "adminPasswordDialog",
"cancel");
input.setText("");
return;
}
});
passwordDialog.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
return passwordDialog;
}
return null;
}
private void updateButtons() {
if (mFinalizedCursor != null && !mFinalizedCursor.isClosed()) {
mFinalizedCursor.requery();
mCompletedCount = mFinalizedCursor.getCount();
if (mCompletedCount > 0) {
mSendDataButton.setText(getString(R.string.send_data_button, mCompletedCount));
} else {
mSendDataButton.setText(getString(R.string.send_data));
}
} else {
mSendDataButton.setText(getString(R.string.send_data));
Log.w(t, "Cannot update \"Send Finalized\" button label since the database is closed. Perhaps the app is running in the background?");
}
if (mSavedCursor != null && !mSavedCursor.isClosed()) {
mSavedCursor.requery();
mSavedCount = mSavedCursor.getCount();
if (mSavedCount > 0) {
mReviewDataButton.setText(getString(R.string.review_data_button,
mSavedCount));
} else {
mReviewDataButton.setText(getString(R.string.review_data));
}
} else {
mReviewDataButton.setText(getString(R.string.review_data));
Log.w(t, "Cannot update \"Edit Form\" button label since the database is closed. Perhaps the app is running in the background?");
}
}
/**
* notifies us that something changed
*
*/
private class MyContentObserver extends ContentObserver {
public MyContentObserver() {
super(null);
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
mHandler.sendEmptyMessage(0);
}
}
/*
* Used to prevent memory leaks
*/
static class IncomingHandler extends Handler {
private final WeakReference<MainMenuActivity> mTarget;
IncomingHandler(MainMenuActivity target) {
mTarget = new WeakReference<MainMenuActivity>(target);
}
@Override
public void handleMessage(Message msg) {
MainMenuActivity target = mTarget.get();
if (target != null) {
target.updateButtons();
}
}
}
private boolean loadSharedPreferencesFromFile(File src) {
// this should probably be in a thread if it ever gets big
boolean res = false;
ObjectInputStream input = null;
try {
input = new ObjectInputStream(new FileInputStream(src));
Editor prefEdit = PreferenceManager.getDefaultSharedPreferences(
this).edit();
prefEdit.clear();
// first object is preferences
Map<String, ?> entries = (Map<String, ?>) input.readObject();
for (Entry<String, ?> entry : entries.entrySet()) {
Object v = entry.getValue();
String key = entry.getKey();
if (v instanceof Boolean)
prefEdit.putBoolean(key, ((Boolean) v).booleanValue());
else if (v instanceof Float)
prefEdit.putFloat(key, ((Float) v).floatValue());
else if (v instanceof Integer)
prefEdit.putInt(key, ((Integer) v).intValue());
else if (v instanceof Long)
prefEdit.putLong(key, ((Long) v).longValue());
else if (v instanceof String)
prefEdit.putString(key, ((String) v));
}
prefEdit.commit();
// second object is admin options
Editor adminEdit = getSharedPreferences(AdminPreferencesActivity.ADMIN_PREFERENCES, 0).edit();
adminEdit.clear();
// first object is preferences
Map<String, ?> adminEntries = (Map<String, ?>) input.readObject();
for (Entry<String, ?> entry : adminEntries.entrySet()) {
Object v = entry.getValue();
String key = entry.getKey();
if (v instanceof Boolean)
adminEdit.putBoolean(key, ((Boolean) v).booleanValue());
else if (v instanceof Float)
adminEdit.putFloat(key, ((Float) v).floatValue());
else if (v instanceof Integer)
adminEdit.putInt(key, ((Integer) v).intValue());
else if (v instanceof Long)
adminEdit.putLong(key, ((Long) v).longValue());
else if (v instanceof String)
adminEdit.putString(key, ((String) v));
}
adminEdit.commit();
res = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return res;
}
}
|
0nima0-f
|
src/org/odk/collect/android/activities/MainMenuActivity.java
|
Java
|
asf20
| 19,436
|
/*
* Copyright (C) 2011 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.activities;
import java.util.ArrayList;
import org.odk.collect.android.R;
import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
/**
* Allows the user to create desktop shortcuts to any form currently avaiable to Collect
*
* @author ctsims
* @author carlhartung (modified for ODK)
*/
public class AndroidShortcuts extends Activity {
private Uri[] mCommands;
private String[] mNames;
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
final Intent intent = getIntent();
final String action = intent.getAction();
// The Android needs to know what shortcuts are available, generate the list
if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) {
buildMenuList();
}
}
/**
* Builds a list of shortcuts
*/
private void buildMenuList() {
ArrayList<String> names = new ArrayList<String>();
ArrayList<Uri> commands = new ArrayList<Uri>();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select ODK Shortcut");
Cursor c = null;
try {
c = getContentResolver().query(FormsColumns.CONTENT_URI, null, null, null, null);
if (c.getCount() > 0) {
c.moveToPosition(-1);
while (c.moveToNext()) {
String formName = c.getString(c.getColumnIndex(FormsColumns.DISPLAY_NAME));
names.add(formName);
Uri uri =
Uri.withAppendedPath(FormsColumns.CONTENT_URI,
c.getString(c.getColumnIndex(FormsColumns._ID)));
commands.add(uri);
}
}
} finally {
if ( c != null ) {
c.close();
}
}
mNames = names.toArray(new String[0]);
mCommands = commands.toArray(new Uri[0]);
builder.setItems(this.mNames, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
returnShortcut(mNames[item], mCommands[item]);
}
});
builder.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
AndroidShortcuts sc = AndroidShortcuts.this;
sc.setResult(RESULT_CANCELED);
sc.finish();
return;
}
});
AlertDialog alert = builder.create();
alert.show();
}
/**
* Returns the results to the calling intent.
*/
private void returnShortcut(String name, Uri command) {
Intent shortcutIntent = new Intent(Intent.ACTION_VIEW);
shortcutIntent.setData(command);
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
Parcelable iconResource = Intent.ShortcutIconResource.fromContext(this, R.drawable.notes);
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
// Now, return the result to the launcher
setResult(RESULT_OK, intent);
finish();
return;
}
}
|
0nima0-f
|
src/org/odk/collect/android/activities/AndroidShortcuts.java
|
Java
|
asf20
| 4,179
|
/*
* Copyright (C) 2011 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.activities;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.preferences.PreferencesActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class SplashScreenActivity extends Activity {
private static final int mSplashTimeout = 2000; // milliseconds
private static final boolean EXIT = true;
private int mImageMaxWidth;
private AlertDialog mAlertDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// must be at the beginning of any activity that can be called from an external intent
try {
Collect.createODKDirs();
} catch (RuntimeException e) {
createErrorDialog(e.getMessage(), EXIT);
return;
}
mImageMaxWidth = getWindowManager().getDefaultDisplay().getWidth();
// this splash screen should be a blank slate
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash_screen);
// get the shared preferences object
SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = mSharedPreferences.edit();
// get the package info object with version number
PackageInfo packageInfo = null;
try {
packageInfo =
getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
boolean firstRun = mSharedPreferences.getBoolean(PreferencesActivity.KEY_FIRST_RUN, true);
boolean showSplash =
mSharedPreferences.getBoolean(PreferencesActivity.KEY_SHOW_SPLASH, false);
String splashPath =
mSharedPreferences.getString(PreferencesActivity.KEY_SPLASH_PATH,
getString(R.string.default_splash_path));
// if you've increased version code, then update the version number and set firstRun to true
if (mSharedPreferences.getLong(PreferencesActivity.KEY_LAST_VERSION, 0) < packageInfo.versionCode) {
editor.putLong(PreferencesActivity.KEY_LAST_VERSION, packageInfo.versionCode);
editor.commit();
firstRun = true;
}
// do all the first run things
if (firstRun || showSplash) {
editor.putBoolean(PreferencesActivity.KEY_FIRST_RUN, false);
editor.commit();
startSplashScreen(splashPath);
} else {
endSplashScreen();
}
}
private void endSplashScreen() {
// launch new activity and close splash screen
startActivity(new Intent(SplashScreenActivity.this, MainMenuActivity.class));
finish();
}
// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
Bitmap b = null;
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int scale = 1;
if (o.outHeight > mImageMaxWidth || o.outWidth > mImageMaxWidth) {
scale =
(int) Math.pow(
2,
(int) Math.round(Math.log(mImageMaxWidth
/ (double) Math.max(o.outHeight, o.outWidth))
/ Math.log(0.5)));
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
}
return b;
}
private void startSplashScreen(String path) {
// add items to the splash screen here. makes things less distracting.
ImageView iv = (ImageView) findViewById(R.id.splash);
LinearLayout ll = (LinearLayout) findViewById(R.id.splash_default);
File f = new File(path);
if (f.exists()) {
iv.setImageBitmap(decodeFile(f));
ll.setVisibility(View.GONE);
iv.setVisibility(View.VISIBLE);
}
// create a thread that counts up to the timeout
Thread t = new Thread() {
int count = 0;
@Override
public void run() {
try {
super.run();
while (count < mSplashTimeout) {
sleep(100);
count += 100;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
endSplashScreen();
}
}
};
t.start();
}
private void createErrorDialog(String errorMsg, final boolean shouldExit) {
Collect.getInstance().getActivityLogger().logAction(this, "createErrorDialog", "show");
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertDialog.setMessage(errorMsg);
DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON_POSITIVE:
Collect.getInstance().getActivityLogger().logAction(this, "createErrorDialog", "OK");
if (shouldExit) {
finish();
}
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.ok), errorListener);
mAlertDialog.show();
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
}
|
0nima0-f
|
src/org/odk/collect/android/activities/SplashScreenActivity.java
|
Java
|
asf20
| 8,068
|
/*
* Copyright (C) 2014 Nafundi
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/**
* @author Carl Hartung (chartung@nafundi.com)
*/
package org.odk.collect.android.activities;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;
import org.odk.collect.android.R;
import org.odk.collect.android.adapters.FileArrayAdapter;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.GoogleDriveFormDownloadListener;
import org.odk.collect.android.listeners.TaskListener;
import org.odk.collect.android.logic.DriveListItem;
import org.odk.collect.android.preferences.PreferencesActivity;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.model.FileList;
import com.google.api.services.drive.model.ParentList;
public class GoogleDriveActivity extends ListActivity implements OnConnectionFailedListener,
TaskListener, GoogleDriveFormDownloadListener {
private final static int PROGRESS_DIALOG = 1;
private final static int GOOGLE_USER_DIALOG = 3;
private ProgressDialog mProgressDialog;
private AlertDialog mAlertDialog;
private Button mRootButton;
private Button mBackButton;
private Button mDownloadButton;
private ImageButton mSearchButton;
private EditText mSearchText;
private Stack<String> mCurrentPath = new Stack<String>();
private String mAlertMsg;
private boolean mAlertShowing;
private static final int RESOLVE_CONNECTION_REQUEST_CODE = 5555;
private static final int COMPLETE_AUTHORIZATION_REQUEST_CODE = 4322;
private String rootId = null;
private boolean MyDrive;
private FileArrayAdapter adapter;
private RetrieveDriveFileContentsAsyncTask mRetrieveDriveFileContentsAsyncTask;
private GetFileTask mGetFileTask;
private String mGoogleUsername = null;
private String mParentId;
private ArrayList<DriveListItem> toDownload;
private static final String MY_DRIVE_KEY = "mydrive";
private static final String PATH_KEY = "path";
private static final String DRIVE_ITEMS_KEY = "drive_list";
private static final String PARENT_KEY = "parent";
private static final String ALERT_MSG_KEY = "alertmsg";
private static final String ALERT_SHOWING_KEY = "alertshowing";
private static final String ROOT_KEY = "root";
private static final String FILE_LIST_KEY = "fileList";
private static final String PARENT_ID_KEY = "parentId";
private static final String CURRENT_ID_KEY = "currentDir";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(getString(R.string.app_name) + " > " + getString(R.string.google_drive));
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setProgressBarVisibility(true);
setContentView(R.layout.drive_layout);
mParentId = null;
mAlertShowing = false;
toDownload = new ArrayList<DriveListItem>();
// ensure we have a google account selected
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
mGoogleUsername = prefs.getString(PreferencesActivity.KEY_SELECTED_GOOGLE_ACCOUNT, null);
if (mGoogleUsername == null || mGoogleUsername.equals("")) {
showDialog(GOOGLE_USER_DIALOG);
return;
}
if (savedInstanceState != null && savedInstanceState.containsKey(MY_DRIVE_KEY)) {
// recover state on rotate
MyDrive = savedInstanceState.getBoolean(MY_DRIVE_KEY);
String[] patharray = savedInstanceState.getStringArray(PATH_KEY);
mCurrentPath = buildPath(patharray);
TextView empty = (TextView)findViewById(android.R.id.empty);
getListView().setEmptyView(empty);
mParentId = savedInstanceState.getString(PARENT_KEY);
mAlertMsg = savedInstanceState.getString(ALERT_MSG_KEY);
mAlertShowing = savedInstanceState.getBoolean(ALERT_SHOWING_KEY);
ArrayList<DriveListItem> dl = savedInstanceState
.getParcelableArrayList(DRIVE_ITEMS_KEY);
adapter = new FileArrayAdapter(GoogleDriveActivity.this, R.layout.two_item_image, dl);
setListAdapter(adapter);
} else {
// new
TextView emptyView = new TextView(this);
emptyView.setText(getString(R.string.gme_search_browse));
emptyView.setGravity(Gravity.CENTER);
emptyView.setTextSize(21);
getListView().getEmptyView().setVisibility(View.INVISIBLE);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
((ViewGroup)getListView().getParent()).addView(emptyView, lp);
getListView().setEmptyView(emptyView);
MyDrive = false;
if (testNetwork()) {
} else {
createAlertDialog(getString(R.string.no_connection));
}
}
// restore any task state
if (getLastNonConfigurationInstance() instanceof RetrieveDriveFileContentsAsyncTask) {
mRetrieveDriveFileContentsAsyncTask = (RetrieveDriveFileContentsAsyncTask)getLastNonConfigurationInstance();
setProgressBarIndeterminateVisibility(true);
} else {
mGetFileTask = (GetFileTask)getLastNonConfigurationInstance();
if (mGetFileTask != null) {
mGetFileTask.setGoogleDriveFormDownloadListener(this);
}
}
if (mGetFileTask != null && mGetFileTask.getStatus() == AsyncTask.Status.FINISHED) {
try {
dismissDialog(PROGRESS_DIALOG);
} catch (Exception e) {
e.printStackTrace();
// don't care...
}
}
if (mAlertShowing) {
try {
dismissDialog(PROGRESS_DIALOG);
} catch (Exception e) {
e.printStackTrace();
// don't care...
}
createAlertDialog(mAlertMsg);
}
mRootButton = (Button)findViewById(R.id.root_button);
if (MyDrive) {
mRootButton.setText(getString(R.string.go_shared));
} else {
mRootButton.setText(getString(R.string.go_drive));
}
mRootButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (testNetwork()) {
toDownload.clear();
mRootButton.setEnabled(false);
mSearchButton.setEnabled(false);
mBackButton.setEnabled(false);
mDownloadButton.setEnabled(false);
listFiles(ROOT_KEY);
MyDrive = !MyDrive;
} else {
createAlertDialog(getString(R.string.no_connection));
}
mCurrentPath.clear();
mCurrentPath.add((String)mRootButton.getText());
}
});
mBackButton = (Button)findViewById(R.id.back_button);
mBackButton.setEnabled(mParentId != null);
mBackButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBackButton.setEnabled(false);
mRootButton.setEnabled(false);
mDownloadButton.setEnabled(false);
toDownload.clear();
getListView().getEmptyView().setVisibility(View.INVISIBLE);
TextView empty = (TextView)findViewById(android.R.id.empty);
empty.setVisibility(View.VISIBLE);
getListView().setEmptyView(empty);
if (testNetwork()) {
if (mParentId == null) {
mParentId = ROOT_KEY;
}
listFiles(mParentId);
mCurrentPath.pop();
// }
} else {
createAlertDialog(getString(R.string.no_connection));
}
}
});
mDownloadButton = (Button)findViewById(R.id.download_button);
mDownloadButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
getFiles();
}
});
mSearchText = (EditText)findViewById(R.id.search_text);
mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
executeSearch();
return true;
}
return false;
}
});
mSearchButton = (ImageButton)findViewById(R.id.search_button);
mSearchButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
executeSearch();
}
});
}
void executeSearch() {
String searchString = mSearchText.getText().toString();
if (searchString.length() > 0) {
toDownload.clear();
mSearchButton.setEnabled(false);
mBackButton.setEnabled(false);
mDownloadButton.setEnabled(false);
mRootButton.setEnabled(false);
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mSearchText.getWindowToken(), 0);
mCurrentPath.clear();
listFiles(ROOT_KEY, mSearchText.getText().toString());
} else {
Toast.makeText(this, R.string.no_blank_search, Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(MY_DRIVE_KEY, MyDrive);
ArrayList<DriveListItem> dl = new ArrayList<DriveListItem>();
for (int i = 0; i < getListView().getCount(); i++) {
dl.add((DriveListItem)getListView().getItemAtPosition(i));
}
outState.putParcelableArrayList(DRIVE_ITEMS_KEY, dl);
outState.putStringArray(PATH_KEY, mCurrentPath.toArray(new String[mCurrentPath.size()]));
outState.putString(PARENT_KEY, mParentId);
outState.putBoolean(ALERT_SHOWING_KEY, mAlertShowing);
outState.putString(ALERT_MSG_KEY, mAlertMsg);
super.onSaveInstanceState(outState);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
getListView().getEmptyView().setVisibility(View.INVISIBLE);
TextView empty = (TextView)findViewById(android.R.id.empty);
empty.setVisibility(View.VISIBLE);
getListView().setEmptyView(empty);
DriveListItem o = adapter.getItem(position);
if (o != null && o.getType() == DriveListItem.DIR) {
if (testNetwork()) {
toDownload.clear();
mSearchText.setText(null);
listFiles(o.getDriveId());
mCurrentPath.push(o.getName());
} else {
createAlertDialog(getString(R.string.no_connection));
}
} else {
// file clicked, download the file, mark checkbox.
CheckBox cb = (CheckBox)v.findViewById(R.id.checkbox);
cb.setChecked(!cb.isChecked());
if (toDownload.contains(o) && !cb.isChecked()) {
toDownload.remove(o);
} else {
toDownload.add(o);
}
mDownloadButton.setEnabled(toDownload.size() > 0);
}
}
private void getFiles() {
StringBuilder messageBuilder = new StringBuilder();
for (int i = 0; i < toDownload.size(); i++) {
DriveListItem o = toDownload.get(i);
messageBuilder.append(o.getName());
if (i != toDownload.size() - 1) {
messageBuilder.append(", ");
}
}
mAlertMsg = getString(R.string.drive_get_file, messageBuilder.toString());
showDialog(PROGRESS_DIALOG);
mGetFileTask = new GetFileTask();
mGetFileTask.setGoogleDriveFormDownloadListener(this);
mGetFileTask.execute(toDownload);
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(this, RESOLVE_CONNECTION_REQUEST_CODE);
} catch (IntentSender.SendIntentException e) {
// Unable to resolve, message user appropriately
}
} else {
GooglePlayServicesUtil.getErrorDialog(connectionResult.getErrorCode(), this, 0).show();
}
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
Collect.getInstance().getActivityLogger()
.logAction(this, "onCreateDialog.PROGRESS_DIALOG", "show");
mProgressDialog = new ProgressDialog(this);
DialogInterface.OnClickListener loadingButtonListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance().getActivityLogger()
.logAction(this, "onCreateDialog.PROGRESS_DIALOG", "cancel");
dialog.dismiss();
mGetFileTask.cancel(true);
mGetFileTask.setGoogleDriveFormDownloadListener(null);
}
};
mProgressDialog.setTitle(getString(R.string.downloading_data));
mProgressDialog.setMessage(mAlertMsg);
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setCancelable(false);
mProgressDialog.setButton(getString(R.string.cancel), loadingButtonListener);
return mProgressDialog;
case GOOGLE_USER_DIALOG:
AlertDialog.Builder gudBuilder = new AlertDialog.Builder(this);
gudBuilder.setTitle(getString(R.string.no_google_account));
gudBuilder.setMessage(getString(R.string.gme_set_account));
gudBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
gudBuilder.setCancelable(false);
return gudBuilder.create();
}
return null;
}
private void createAlertDialog(String message) {
Collect.getInstance().getActivityLogger().logAction(this, "createAlertDialog", "show");
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setTitle(getString(R.string.download_forms_result));
mAlertDialog.setMessage(message);
DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON1: // ok
Collect.getInstance().getActivityLogger()
.logAction(this, "createAlertDialog", "OK");
mAlertShowing = false;
finish();
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.ok), quitListener);
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertShowing = true;
mAlertMsg = message;
mAlertDialog.show();
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
switch (requestCode) {
case COMPLETE_AUTHORIZATION_REQUEST_CODE:
if (resultCode == Activity.RESULT_OK) {
if (testNetwork()) {
listFiles(ROOT_KEY);
} else {
createAlertDialog(getString(R.string.no_connection));
}
} else {
// User denied access, show him the account chooser again
}
break;
}
if (resultCode == RESULT_CANCELED) {
finish();
}
}
@Override
public Object onRetainNonConfigurationInstance() {
if (mRetrieveDriveFileContentsAsyncTask != null
&& mRetrieveDriveFileContentsAsyncTask.getStatus() == AsyncTask.Status.RUNNING) {
return mRetrieveDriveFileContentsAsyncTask;
}
return mGetFileTask;
}
// List<com.google.api.services.drive.model.File>
private class RetrieveDriveFileContentsAsyncTask extends
AsyncTask<String, HashMap<String, Object>, HashMap<String, Object>> {
private TaskListener listener;
public void setTaskListener(TaskListener tl) {
listener = tl;
}
@Override
protected HashMap<String, Object> doInBackground(String... params) {
HashMap<String, Object> results = new HashMap<String, Object>();
String currentDir = params[0];
String parentId = ROOT_KEY;
String query = null;
if (params.length == 2) {
// TODO: *.xml or .xml or xml
// then search mimetype
query = "title contains '" + params[1] + "' and trashed=false";
}
Collection<String> collection = new ArrayList<String>();
collection.add(com.google.api.services.drive.DriveScopes.DRIVE);
GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(
GoogleDriveActivity.this.getApplicationContext(), collection);
com.google.api.services.drive.Drive service = new com.google.api.services.drive.Drive.Builder(
AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential).build();
credential.setSelectedAccountName(mGoogleUsername);
if (rootId == null) {
com.google.api.services.drive.model.File rootfile = null;
try {
rootfile = service.files().get(ROOT_KEY).execute();
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), COMPLETE_AUTHORIZATION_REQUEST_CODE);
return null;
} catch (IOException e) {
e.printStackTrace();
}
rootId = rootfile.getId();
}
String requestString = "'" + currentDir + "' in parents and trashed=false";
Files.List request = null;
try {
ParentList parents = service.parents().list(currentDir).execute();
if (parents.getItems().size() > 0) {
parentId = parents.getItems().get(0).getId();
if (parents.getItems().get(0).getIsRoot()) {
rootId = parentId;
}
} else {
parentId = null;
}
// Sharedwithme, and root:
if (!MyDrive && currentDir.equals(ROOT_KEY)) {
requestString = "trashed=false and sharedWithMe=true";
}
request = service.files().list().setQ(requestString);
} catch (IOException e1) {
e1.printStackTrace();
}
// If there's a query parameter, we're searching for all the files.
if (query != null) {
try {
request = service.files().list().setQ(query);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
results.put(PARENT_ID_KEY, parentId);
results.put(CURRENT_ID_KEY, currentDir);
do {
try {
FileList fa = request.execute();
List<com.google.api.services.drive.model.File> driveFileListPage = new ArrayList<com.google.api.services.drive.model.File>();
driveFileListPage.addAll(fa.getItems());
request.setPageToken(fa.getNextPageToken());
HashMap<String, Object> nextPage = new HashMap<String, Object>();
nextPage.put(PARENT_ID_KEY, parentId);
nextPage.put(CURRENT_ID_KEY, currentDir);
nextPage.put(FILE_LIST_KEY, driveFileListPage);
publishProgress(nextPage);
} catch (IOException e) {
e.printStackTrace();
}
} while (request.getPageToken() != null && request.getPageToken().length() > 0);
return results;
}
@Override
protected void onPostExecute(HashMap<String, Object> results) {
super.onPostExecute(results);
if (results == null) {
// was an auth request
return;
}
if (listener != null) {
listener.taskComplete(results);
}
}
@Override
protected void onProgressUpdate(HashMap<String, Object>... values) {
super.onProgressUpdate(values);
List<com.google.api.services.drive.model.File> fileList = (List<com.google.api.services.drive.model.File>)values[0]
.get(FILE_LIST_KEY);
String parentId = (String)values[0].get(PARENT_ID_KEY);
String currentDir = (String)values[0].get(CURRENT_ID_KEY);
List<DriveListItem> dirs = new ArrayList<DriveListItem>();
List<DriveListItem> forms = new ArrayList<DriveListItem>();
for (com.google.api.services.drive.model.File f : fileList) {
if (f.getMimeType().equals("application/xml")) {
forms.add(new DriveListItem(f.getTitle(), "", f.getModifiedDate(), "", "",
DriveListItem.FILE, f.getId(), currentDir));
} else if (f.getMimeType().equals("application/xhtml")) {
forms.add(new DriveListItem(f.getTitle(), "", f.getModifiedDate(), "", "",
DriveListItem.FILE, f.getId(), currentDir));
} else if (f.getMimeType().equals("application/vnd.google-apps.folder")) {
dirs.add(new DriveListItem(f.getTitle(), "", f.getModifiedDate(), "", "",
DriveListItem.DIR, f.getId(), parentId));
} else {
// skip the rest of the files
}
}
Collections.sort(dirs);
Collections.sort(forms);
dirs.addAll(forms);
if (adapter == null) {
adapter = new FileArrayAdapter(GoogleDriveActivity.this, R.layout.two_item_image,
dirs);
GoogleDriveActivity.this.setListAdapter(adapter);
} else {
adapter.addAll(dirs);
}
adapter.sort(new Comparator<DriveListItem>() {
@Override
public int compare(DriveListItem lhs, DriveListItem rhs) {
if (lhs.getType() != rhs.getType()) {
if (lhs.getType() == DriveListItem.DIR) {
return -1;
} else {
return 1;
}
} else {
return lhs.getName().compareTo(rhs.getName());
}
}
});
adapter.notifyDataSetChanged();
}
}
private Stack<String> buildPath(String[] path) {
Stack<String> pathStack = new Stack<String>();
for (int i = 0; i < path.length; i++) {
pathStack.push(path[i]);
}
return pathStack;
}
private class GetFileTask extends
AsyncTask<ArrayList<DriveListItem>, Boolean, HashMap<String, Object>> {
private GoogleDriveFormDownloadListener listener;
public void setGoogleDriveFormDownloadListener(GoogleDriveFormDownloadListener gl) {
listener = gl;
}
@Override
protected HashMap<String, Object> doInBackground(ArrayList<DriveListItem>... params) {
HashMap<String, Object> results = new HashMap<String, Object>();
ArrayList<DriveListItem> fileItems = params[0];
Collection<String> collection = new ArrayList<String>();
collection.add(com.google.api.services.drive.DriveScopes.DRIVE);
GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(
GoogleDriveActivity.this.getApplicationContext(), collection);
com.google.api.services.drive.Drive service = new com.google.api.services.drive.Drive.Builder(
AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential).build();
credential.setSelectedAccountName(mGoogleUsername);
for (int k = 0; k < fileItems.size(); k++) {
DriveListItem fileItem = fileItems.get(k);
String mediaDir = fileItem.getName().substring(0, fileItem.getName().length() - 4)
+ "-media";
String requestString = "'" + fileItem.getParentId()
+ "' in parents and trashed=false and title='" + mediaDir + "'";
Files.List request = null;
List<com.google.api.services.drive.model.File> driveFileList = new ArrayList<com.google.api.services.drive.model.File>();
try {
request = service.files().list().setQ(requestString);
} catch (IOException e1) {
e1.printStackTrace();
results.put(fileItem.getName(), e1.getMessage());
return results;
}
do {
try {
FileList fa = request.execute();
driveFileList.addAll(fa.getItems());
request.setPageToken(fa.getNextPageToken());
} catch (Exception e2) {
e2.printStackTrace();
results.put(fileItem.getName(), e2.getMessage());
return results;
}
} while (request.getPageToken() != null && request.getPageToken().length() > 0);
if (driveFileList.size() > 1) {
results.put(fileItem.getName(),
"More than one media folder detected, please remove one and try again");
return results;
} else if (driveFileList.size() == 1) {
requestString = "'" + driveFileList.get(0).getId()
+ "' in parents and trashed=false";
List<com.google.api.services.drive.model.File> mediaFileList = new ArrayList<com.google.api.services.drive.model.File>();
try {
request = service.files().list().setQ(requestString);
do {
try {
FileList fa = request.execute();
mediaFileList.addAll(fa.getItems());
request.setPageToken(fa.getNextPageToken());
} catch (Exception e2) {
e2.printStackTrace();
results.put(fileItem.getName(), e2.getMessage());
return results;
}
} while (request.getPageToken() != null
&& request.getPageToken().length() > 0);
} catch (Exception e) {
e.printStackTrace();
results.put(fileItem.getName(), e.getMessage());
return results;
}
} else {
// zero.. just downloda the .xml file
}
try {
com.google.api.services.drive.model.File df = service.files()
.get(fileItem.getDriveId()).execute();
InputStream is = downloadFile(service, df);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
FileWriter fw = new FileWriter(Collect.FORMS_PATH + File.separator
+ fileItem.getName());
int c;
while ((c = reader.read()) != -1) {
fw.write(c);
}
fw.flush();
fw.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
results.put(fileItem.getName(), e.getMessage());
return results;
}
results.put(fileItem.getName(), Collect.getInstance().getString(R.string.success));
}
return results;
}
private InputStream downloadFile(com.google.api.services.drive.Drive service,
com.google.api.services.drive.model.File file) {
if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
try {
HttpResponse resp = service.getRequestFactory()
.buildGetRequest(new GenericUrl(file.getDownloadUrl())).execute();
return resp.getContent();
} catch (IOException e) {
// An error occurred.
e.printStackTrace();
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
}
@Override
protected void onPostExecute(HashMap<String, Object> results) {
listener.formDownloadComplete(results);
}
}
@Override
public void taskComplete(HashMap<String, Object> results) {
mRootButton.setEnabled(true);
mDownloadButton.setEnabled(toDownload.size() > 0);
mSearchButton.setEnabled(true);
setProgressBarIndeterminateVisibility(false);
if (results == null) {
// if results was null, then got a google exception
// requiring the user to authorize
return;
}
String parentId = (String)results.get(PARENT_ID_KEY);
String currentDir = (String)results.get(CURRENT_ID_KEY);
if (MyDrive) {
mRootButton.setText(getString(R.string.go_shared));
} else {
mRootButton.setText(getString(R.string.go_drive));
}
if (currentDir.equals(rootId) || (currentDir.equals("root"))) {
mBackButton.setEnabled(false);
} else {
mBackButton.setEnabled(true);
}
mParentId = parentId;
if (mCurrentPath.empty()) {
if (MyDrive) {
mCurrentPath.add(getString(R.string.go_drive));
} else {
mCurrentPath.add(getString(R.string.go_shared));
}
}
}
@Override
protected void onPause() {
if (mRetrieveDriveFileContentsAsyncTask != null) {
mRetrieveDriveFileContentsAsyncTask.setTaskListener(null);
}
if (mGetFileTask != null) {
mGetFileTask.setGoogleDriveFormDownloadListener(null);
}
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
if (mRetrieveDriveFileContentsAsyncTask != null) {
mRetrieveDriveFileContentsAsyncTask.setTaskListener(this);
}
if (mGetFileTask != null) {
mGetFileTask.setGoogleDriveFormDownloadListener(this);
}
}
@Override
public void formDownloadComplete(HashMap<String, Object> results) {
try {
dismissDialog(PROGRESS_DIALOG);
} catch (Exception e) {
// tried to close a dialog not open. don't care.
}
StringBuilder sb = new StringBuilder();
Iterator<String> it = results.keySet().iterator();
while (it.hasNext()) {
String id = it.next();
sb.append(id + " :: " + results.get(id) + "\n");
}
if (sb.length() > 1) {
sb.setLength(sb.length() - 1);
}
createAlertDialog(sb.toString());
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
private boolean testNetwork() {
ConnectivityManager manager = (ConnectivityManager)this
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo currentNetworkInfo = manager.getActiveNetworkInfo();
if (currentNetworkInfo == null) {
return false;
}
return (currentNetworkInfo.getState() == NetworkInfo.State.CONNECTED);
}
public void listFiles(String dir, String query) {
setProgressBarIndeterminateVisibility(true);
adapter = null;
mRetrieveDriveFileContentsAsyncTask = new RetrieveDriveFileContentsAsyncTask();
mRetrieveDriveFileContentsAsyncTask.setTaskListener(GoogleDriveActivity.this);
if (query != null) {
mRetrieveDriveFileContentsAsyncTask.execute(dir, query);
} else {
mRetrieveDriveFileContentsAsyncTask.execute(dir);
}
}
public void listFiles(String dir) {
listFiles(dir, null);
}
}
|
0nima0-f
|
src/org/odk/collect/android/activities/GoogleDriveActivity.java
|
Java
|
asf20
| 37,379
|
/*
* Copyright (C) 2011 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.activities;
import java.text.DecimalFormat;
import java.util.List;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.InfoLogger;
import org.odk.collect.android.widgets.GeoPointWidget;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
public class GeoPointMapActivitySdk7 extends MapActivity implements LocationListener {
private static final String LOCATION_COUNT = "locationCount";
private MapView mMapView;
private TextView mLocationStatus;
private MapController mMapController;
private LocationManager mLocationManager;
private Overlay mLocationOverlay;
private Overlay mGeoPointOverlay;
private GeoPoint mGeoPoint;
private Location mLocation;
private Button mAcceptLocation;
private Button mCancelLocation;
private boolean mCaptureLocation = true;
private Button mShowLocation;
private boolean mGPSOn = false;
private boolean mNetworkOn = false;
private double mLocationAccuracy;
private int mLocationCount = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ( savedInstanceState != null ) {
mLocationCount = savedInstanceState.getInt(LOCATION_COUNT);
}
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.geopoint_layout_sdk7);
Intent intent = getIntent();
mLocationAccuracy = GeoPointWidget.DEFAULT_LOCATION_ACCURACY;
if (intent != null && intent.getExtras() != null) {
if ( intent.hasExtra(GeoPointWidget.LOCATION) ) {
double[] location = intent.getDoubleArrayExtra(GeoPointWidget.LOCATION);
mGeoPoint = new GeoPoint((int) (location[0] * 1E6), (int) (location[1] * 1E6));
}
if ( intent.hasExtra(GeoPointWidget.ACCURACY_THRESHOLD) ) {
mLocationAccuracy = intent.getDoubleExtra(GeoPointWidget.ACCURACY_THRESHOLD, GeoPointWidget.DEFAULT_LOCATION_ACCURACY);
}
mCaptureLocation = !intent.getBooleanExtra(GeoPointWidget.READ_ONLY, false);
}
/**
* Add the MapView dynamically to the placeholding frame so as to not
* incur the wrath of Android Lint...
*/
FrameLayout frame = (FrameLayout) findViewById(R.id.mapview_placeholder);
String apiKey = "017Xo9E6R7WmcCITvo-lU2V0ERblKPqCcguwxSQ";
// String apiKey = "0wsgFhRvVBLVpgaFzmwaYuqfU898z_2YtlKSlkg";
mMapView = new MapView(this, apiKey);
mMapView.setClickable(true);
mMapView.setId(R.id.mapview);
LayoutParams p = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
frame.addView(mMapView, p);
mCancelLocation = (Button) findViewById(R.id.cancel_location);
mCancelLocation.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "cancelLocation", "cancel");
finish();
}
});
mMapController = mMapView.getController();
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mMapView.setBuiltInZoomControls(true);
mMapView.setSatellite(false);
mMapController.setZoom(16);
// make sure we have a good location provider before continuing
List<String> providers = mLocationManager.getProviders(true);
for (String provider : providers) {
if (provider.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) {
mGPSOn = true;
}
if (provider.equalsIgnoreCase(LocationManager.NETWORK_PROVIDER)) {
mNetworkOn = true;
}
}
if (!mGPSOn && !mNetworkOn) {
Toast.makeText(getBaseContext(), getString(R.string.provider_disabled_error),
Toast.LENGTH_SHORT).show();
finish();
}
if ( mGPSOn ) {
Location loc = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if ( loc != null ) {
InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() +
" lastKnownLocation(GPS) lat: " +
loc.getLatitude() + " long: " +
loc.getLongitude() + " acc: " +
loc.getAccuracy() );
} else {
InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() +
" lastKnownLocation(GPS) null location");
}
}
if ( mNetworkOn ) {
Location loc = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if ( loc != null ) {
InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() +
" lastKnownLocation(Network) lat: " +
loc.getLatitude() + " long: " +
loc.getLongitude() + " acc: " +
loc.getAccuracy() );
} else {
InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() +
" lastKnownLocation(Network) null location");
}
}
mLocationOverlay = new MyLocationOverlay(this, mMapView);
mMapView.getOverlays().add(mLocationOverlay);
if (mCaptureLocation) {
mLocationStatus = (TextView) findViewById(R.id.location_status);
mAcceptLocation = (Button) findViewById(R.id.accept_location);
mAcceptLocation.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "acceptLocation", "OK");
returnLocation();
}
});
} else {
mGeoPointOverlay = new Marker(mGeoPoint);
mMapView.getOverlays().add(mGeoPointOverlay);
((Button) findViewById(R.id.accept_location)).setVisibility(View.GONE);
((TextView) findViewById(R.id.location_status)).setVisibility(View.GONE);
mShowLocation = ((Button) findViewById(R.id.show_location));
mShowLocation.setVisibility(View.VISIBLE);
mShowLocation.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "showLocation", "onClick");
mMapController.animateTo(mGeoPoint);
}
});
}
if ( mGeoPoint != null ) {
mMapController.animateTo(mGeoPoint);
}
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
private void returnLocation() {
if (mLocation != null) {
Intent i = new Intent();
i.putExtra(
FormEntryActivity.LOCATION_RESULT,
mLocation.getLatitude() + " " + mLocation.getLongitude() + " "
+ mLocation.getAltitude() + " " + mLocation.getAccuracy());
setResult(RESULT_OK, i);
}
finish();
}
private String truncateFloat(float f) {
return new DecimalFormat("#.##").format(f);
}
@Override
protected void onPause() {
super.onPause();
mLocationManager.removeUpdates(this);
((MyLocationOverlay) mLocationOverlay).disableMyLocation();
}
@Override
protected void onResume() {
super.onResume();
if (mCaptureLocation) {
((MyLocationOverlay) mLocationOverlay).enableMyLocation();
if (mGPSOn) {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
if (mNetworkOn) {
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
}
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
@Override
public void onLocationChanged(Location location) {
if (mCaptureLocation) {
mLocation = location;
if (mLocation != null) {
// Bug report: cached GeoPoint is being returned as the first value.
// Wait for the 2nd value to be returned, which is hopefully not cached?
++mLocationCount;
InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() +
" onLocationChanged(" + mLocationCount + ") lat: " +
mLocation.getLatitude() + " long: " +
mLocation.getLongitude() + " acc: " +
mLocation.getAccuracy() );
if (mLocationCount > 1) {
mLocationStatus.setText(getString(R.string.location_provider_accuracy,
mLocation.getProvider(), truncateFloat(mLocation.getAccuracy())));
mGeoPoint =
new GeoPoint((int) (mLocation.getLatitude() * 1E6),
(int) (mLocation.getLongitude() * 1E6));
mMapController.animateTo(mGeoPoint);
if (mLocation.getAccuracy() <= mLocationAccuracy) {
returnLocation();
}
}
} else {
InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() +
" onLocationChanged(" + mLocationCount + ") null location");
}
}
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
class Marker extends Overlay {
GeoPoint gp = null;
public Marker(GeoPoint gp) {
super();
this.gp = gp;
}
@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
super.draw(canvas, mapView, shadow);
Point screenPoint = new Point();
mMapView.getProjection().toPixels(gp, screenPoint);
canvas.drawBitmap(BitmapFactory.decodeResource(getResources(),
R.drawable.ic_maps_indicator_current_position), screenPoint.x, screenPoint.y - 8,
null); // -8 as image is 16px high
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/activities/GeoPointMapActivitySdk7.java
|
Java
|
asf20
| 12,086
|
/*
* Copyright (C) 2013 Nafundi
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.activities;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
public class BearingActivity extends Activity implements SensorEventListener {
private ProgressDialog mBearingDialog;
private SensorManager mSensorManager;
private Sensor accelerometer;
private Sensor magnetometer;
private static float[] mAccelerometer = null;
private static float[] mGeomagnetic = null;
private String mBearing = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(getString(R.string.app_name) + " > " + getString(R.string.get_bearing));
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
magnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
setupBearingDialog();
}
@Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this, accelerometer);
mSensorManager.unregisterListener(this, magnetometer);
if (mBearingDialog != null && mBearingDialog.isShowing())
mBearingDialog.dismiss();
}
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME);
mSensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_GAME);
mBearingDialog.show();
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
/**
* Sets up the look and actions for the progress dialog while the compass is
* searching.
*/
private void setupBearingDialog() {
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "setupBearingDialog", "show");
// dialog displayed while fetching bearing
mBearingDialog = new ProgressDialog(this);
DialogInterface.OnClickListener geopointButtonListener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "acceptBearing", "OK");
returnBearing();
break;
case DialogInterface.BUTTON_NEGATIVE:
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "cancelBearing", "cancel");
mBearing = null;
finish();
break;
}
}
};
// back button doesn't cancel
mBearingDialog.setCancelable(false);
mBearingDialog.setIndeterminate(true);
mBearingDialog.setIcon(android.R.drawable.ic_dialog_info);
mBearingDialog.setTitle(getString(R.string.getting_bearing));
mBearingDialog.setMessage(getString(R.string.please_wait_long));
mBearingDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.accept_bearing),
geopointButtonListener);
mBearingDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.cancel_location),
geopointButtonListener);
}
private void returnBearing() {
if (mBearing != null) {
Intent i = new Intent();
i.putExtra(
FormEntryActivity.BEARING_RESULT, mBearing);
setResult(RESULT_OK, i);
}
finish();
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
// onSensorChanged gets called for each sensor so we have to remember
// the values
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
mAccelerometer = event.values;
}
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
mGeomagnetic = event.values;
}
if (mAccelerometer != null && mGeomagnetic != null) {
float R[] = new float[9];
float I[] = new float[9];
boolean success = SensorManager.getRotationMatrix(R, I, mAccelerometer, mGeomagnetic);
if (success) {
float orientation[] = new float[3];
SensorManager.getOrientation(R, orientation);
// at this point, orientation contains the azimuth(direction),
// pitch and roll values.
double azimuth = 180 * orientation[0] / Math.PI;
// double pitch = 180 * orientation[1] / Math.PI;
// double roll = 180 * orientation[2] / Math.PI;
double degrees = normalizeDegree(azimuth);
mBearing = String.format("%.3f", degrees);
String dir = "N";
if ((degrees > 0 && degrees <= 22.5) || degrees > 337.5) {
dir = "N";
} else if (degrees > 22.5 && degrees <= 67.5) {
dir = "NE";
} else if (degrees > 67.5 && degrees <= 112.5) {
dir = "E";
} else if (degrees > 112.5 && degrees <= 157.5) {
dir = "SE";
} else if (degrees > 157.5 && degrees <= 222.5) {
dir = "S";
} else if (degrees > 222.5 && degrees <= 247.5) {
dir = "SW";
} else if (degrees > 247.5 && degrees <= 292.5) {
dir = "W";
} else if (degrees > 292.5 && degrees <= 337.5) {
dir = "NW";
}
mBearingDialog.setMessage("Dir: " + dir + " Bearing: " + mBearing);
}
}
}
private double normalizeDegree(double value) {
if (value >= 0.0f && value <= 180.0f) {
return value;
} else {
return 180 + (180 + value);
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/activities/BearingActivity.java
|
Java
|
asf20
| 7,581
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.activities;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.DiskSyncListener;
import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns;
import org.odk.collect.android.tasks.DiskSyncTask;
import org.odk.collect.android.utilities.VersionHidingCursorAdapter;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
/**
* Responsible for displaying all the valid forms in the forms directory. Stores the path to
* selected form for use by {@link MainMenuActivity}.
*
* @author Yaw Anokwa (yanokwa@gmail.com)
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class FormChooserList extends ListActivity implements DiskSyncListener {
private static final String t = "FormChooserList";
private static final boolean EXIT = true;
private static final String syncMsgKey = "syncmsgkey";
private DiskSyncTask mDiskSyncTask;
private AlertDialog mAlertDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// must be at the beginning of any activity that can be called from an external intent
try {
Collect.createODKDirs();
} catch (RuntimeException e) {
createErrorDialog(e.getMessage(), EXIT);
return;
}
setContentView(R.layout.chooser_list_layout);
setTitle(getString(R.string.app_name) + " > " + getString(R.string.enter_data));
String sortOrder = FormsColumns.DISPLAY_NAME + " ASC, " + FormsColumns.JR_VERSION + " DESC";
Cursor c = managedQuery(FormsColumns.CONTENT_URI, null, null, null, sortOrder);
String[] data = new String[] {
FormsColumns.DISPLAY_NAME, FormsColumns.DISPLAY_SUBTEXT, FormsColumns.JR_VERSION
};
int[] view = new int[] {
R.id.text1, R.id.text2, R.id.text3
};
// render total instance view
SimpleCursorAdapter instances =
new VersionHidingCursorAdapter(FormsColumns.JR_VERSION, this, R.layout.two_item, c, data, view);
setListAdapter(instances);
if (savedInstanceState != null && savedInstanceState.containsKey(syncMsgKey)) {
TextView tv = (TextView) findViewById(R.id.status_text);
tv.setText(savedInstanceState.getString(syncMsgKey));
}
// DiskSyncTask checks the disk for any forms not already in the content provider
// that is, put here by dragging and dropping onto the SDCard
mDiskSyncTask = (DiskSyncTask) getLastNonConfigurationInstance();
if (mDiskSyncTask == null) {
Log.i(t, "Starting new disk sync task");
mDiskSyncTask = new DiskSyncTask();
mDiskSyncTask.setDiskSyncListener(this);
mDiskSyncTask.execute((Void[]) null);
}
}
@Override
public Object onRetainNonConfigurationInstance() {
// pass the thread on restart
return mDiskSyncTask;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
TextView tv = (TextView) findViewById(R.id.status_text);
outState.putString(syncMsgKey, tv.getText().toString());
}
/**
* Stores the path of selected form and finishes.
*/
@Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
// get uri to form
long idFormsTable = ((SimpleCursorAdapter) getListAdapter()).getItemId(position);
Uri formUri = ContentUris.withAppendedId(FormsColumns.CONTENT_URI, idFormsTable);
Collect.getInstance().getActivityLogger().logAction(this, "onListItemClick", formUri.toString());
String action = getIntent().getAction();
if (Intent.ACTION_PICK.equals(action)) {
// caller is waiting on a picked form
setResult(RESULT_OK, new Intent().setData(formUri));
} else {
// caller wants to view/edit a form, so launch formentryactivity
startActivity(new Intent(Intent.ACTION_EDIT, formUri));
}
finish();
}
@Override
protected void onResume() {
mDiskSyncTask.setDiskSyncListener(this);
super.onResume();
if (mDiskSyncTask.getStatus() == AsyncTask.Status.FINISHED) {
SyncComplete(mDiskSyncTask.getStatusMessage());
}
}
@Override
protected void onPause() {
mDiskSyncTask.setDiskSyncListener(null);
super.onPause();
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
/**
* Called by DiskSyncTask when the task is finished
*/
@Override
public void SyncComplete(String result) {
Log.i(t, "disk sync task complete");
TextView tv = (TextView) findViewById(R.id.status_text);
tv.setText(result);
}
/**
* Creates a dialog with the given message. Will exit the activity when the user preses "ok" if
* shouldExit is set to true.
*
* @param errorMsg
* @param shouldExit
*/
private void createErrorDialog(String errorMsg, final boolean shouldExit) {
Collect.getInstance().getActivityLogger().logAction(this, "createErrorDialog", "show");
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertDialog.setMessage(errorMsg);
DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON_POSITIVE:
Collect.getInstance().getActivityLogger().logAction(this, "createErrorDialog",
shouldExit ? "exitApplication" : "OK");
if (shouldExit) {
finish();
}
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.ok), errorListener);
mAlertDialog.show();
}
}
|
0nima0-f
|
src/org/odk/collect/android/activities/FormChooserList.java
|
Java
|
asf20
| 7,456
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.activities;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.InstanceUploaderListener;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import org.odk.collect.android.tasks.InstanceUploaderTask;
import org.odk.collect.android.utilities.WebUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
/**
* Activity to upload completed forms.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class InstanceUploaderActivity extends Activity implements InstanceUploaderListener {
private final static String t = "InstanceUploaderActivity";
private final static int PROGRESS_DIALOG = 1;
private final static int AUTH_DIALOG = 2;
private final static String AUTH_URI = "auth";
private static final String ALERT_MSG = "alertmsg";
private static final String ALERT_SHOWING = "alertshowing";
private static final String TO_SEND = "tosend";
private ProgressDialog mProgressDialog;
private AlertDialog mAlertDialog;
private String mAlertMsg;
private boolean mAlertShowing;
private InstanceUploaderTask mInstanceUploaderTask;
// maintain a list of what we've yet to send, in case we're interrupted by auth requests
private Long[] mInstancesToSend;
// maintain a list of what we've sent, in case we're interrupted by auth requests
private HashMap<String, String> mUploadedInstances;
private String mUrl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(t, "onCreate: " + ((savedInstanceState == null) ? "creating" : "re-initializing"));
mAlertMsg = getString(R.string.please_wait);
mAlertShowing = false;
mUploadedInstances = new HashMap<String, String>();
setTitle(getString(R.string.app_name) + " > " + getString(R.string.send_data));
// get any simple saved state...
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(ALERT_MSG)) {
mAlertMsg = savedInstanceState.getString(ALERT_MSG);
}
if (savedInstanceState.containsKey(ALERT_SHOWING)) {
mAlertShowing = savedInstanceState.getBoolean(ALERT_SHOWING, false);
}
mUrl = savedInstanceState.getString(AUTH_URI);
}
// and if we are resuming, use the TO_SEND list of not-yet-sent submissions
// Otherwise, construct the list from the incoming intent value
long[] selectedInstanceIDs = null;
if (savedInstanceState != null && savedInstanceState.containsKey(TO_SEND)) {
selectedInstanceIDs = savedInstanceState.getLongArray(TO_SEND);
} else {
// get instances to upload...
Intent intent = getIntent();
selectedInstanceIDs = intent.getLongArrayExtra(FormEntryActivity.KEY_INSTANCES);
}
mInstancesToSend = new Long[(selectedInstanceIDs == null) ? 0 : selectedInstanceIDs.length];
if ( selectedInstanceIDs != null ) {
for ( int i = 0 ; i < selectedInstanceIDs.length ; ++i ) {
mInstancesToSend[i] = selectedInstanceIDs[i];
}
}
// at this point, we don't expect this to be empty...
if (mInstancesToSend.length == 0) {
Log.e(t, "onCreate: No instances to upload!");
// drop through -- everything will process through OK
} else {
Log.i(t, "onCreate: Beginning upload of " + mInstancesToSend.length + " instances!");
}
// get the task if we've changed orientations. If it's null it's a new upload.
mInstanceUploaderTask = (InstanceUploaderTask) getLastNonConfigurationInstance();
if (mInstanceUploaderTask == null) {
// setup dialog and upload task
showDialog(PROGRESS_DIALOG);
mInstanceUploaderTask = new InstanceUploaderTask();
// register this activity with the new uploader task
mInstanceUploaderTask.setUploaderListener(InstanceUploaderActivity.this);
mInstanceUploaderTask.execute(mInstancesToSend);
}
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onResume() {
Log.i(t, "onResume: Resuming upload of " + mInstancesToSend.length + " instances!");
if (mInstanceUploaderTask != null) {
mInstanceUploaderTask.setUploaderListener(this);
}
if (mAlertShowing) {
createAlertDialog(mAlertMsg);
}
super.onResume();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(ALERT_MSG, mAlertMsg);
outState.putBoolean(ALERT_SHOWING, mAlertShowing);
outState.putString(AUTH_URI, mUrl);
long[] toSend = new long[mInstancesToSend.length];
for ( int i = 0 ; i < mInstancesToSend.length ; ++i ) {
toSend[i] = mInstancesToSend[i];
}
outState.putLongArray(TO_SEND, toSend);
}
@Override
public Object onRetainNonConfigurationInstance() {
return mInstanceUploaderTask;
}
@Override
protected void onPause() {
Log.i(t, "onPause: Pausing upload of " + mInstancesToSend.length + " instances!");
super.onPause();
if (mAlertDialog != null && mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
@Override
protected void onDestroy() {
if (mInstanceUploaderTask != null) {
mInstanceUploaderTask.setUploaderListener(null);
}
super.onDestroy();
}
@Override
public void uploadingComplete(HashMap<String, String> result) {
Log.i(t, "uploadingComplete: Processing results (" + result.size() + ") from upload of " + mInstancesToSend.length + " instances!");
try {
dismissDialog(PROGRESS_DIALOG);
} catch (Exception e) {
// tried to close a dialog not open. don't care.
}
StringBuilder selection = new StringBuilder();
Set<String> keys = result.keySet();
Iterator<String> it = keys.iterator();
String[] selectionArgs = new String[keys.size()];
int i = 0;
while (it.hasNext()) {
String id = it.next();
selection.append(InstanceColumns._ID + "=?");
selectionArgs[i++] = id;
if (i != keys.size()) {
selection.append(" or ");
}
}
StringBuilder message = new StringBuilder();
{
Cursor results = null;
try {
results = getContentResolver().query(InstanceColumns.CONTENT_URI,
null, selection.toString(), selectionArgs, null);
if (results.getCount() > 0) {
results.moveToPosition(-1);
while (results.moveToNext()) {
String name =
results.getString(results.getColumnIndex(InstanceColumns.DISPLAY_NAME));
String id = results.getString(results.getColumnIndex(InstanceColumns._ID));
message.append(name + " - " + result.get(id) + "\n\n");
}
} else {
message.append(getString(R.string.no_forms_uploaded));
}
} finally {
if ( results != null ) {
results.close();
}
}
}
createAlertDialog(message.toString().trim());
}
@Override
public void progressUpdate(int progress, int total) {
mAlertMsg = getString(R.string.sending_items, progress, total);
mProgressDialog.setMessage(mAlertMsg);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.PROGRESS_DIALOG", "show");
mProgressDialog = new ProgressDialog(this);
DialogInterface.OnClickListener loadingButtonListener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.PROGRESS_DIALOG", "cancel");
dialog.dismiss();
mInstanceUploaderTask.cancel(true);
mInstanceUploaderTask.setUploaderListener(null);
finish();
}
};
mProgressDialog.setTitle(getString(R.string.uploading_data));
mProgressDialog.setMessage(mAlertMsg);
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setCancelable(false);
mProgressDialog.setButton(getString(R.string.cancel), loadingButtonListener);
return mProgressDialog;
case AUTH_DIALOG:
Log.i(t, "onCreateDialog(AUTH_DIALOG): for upload of " + mInstancesToSend.length + " instances!");
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.AUTH_DIALOG", "show");
AlertDialog.Builder b = new AlertDialog.Builder(this);
LayoutInflater factory = LayoutInflater.from(this);
final View dialogView = factory.inflate(R.layout.server_auth_dialog, null);
// Get the server, username, and password from the settings
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String server = mUrl;
if (server == null) {
Log.e(t, "onCreateDialog(AUTH_DIALOG): No failing mUrl specified for upload of " + mInstancesToSend.length + " instances!");
// if the bundle is null, we're looking for a formlist
String submissionUrl = getString(R.string.default_odk_submission);
server =
settings.getString(PreferencesActivity.KEY_SERVER_URL,
getString(R.string.default_server_url))
+ settings.getString(PreferencesActivity.KEY_SUBMISSION_URL, submissionUrl);
}
final String url = server;
Log.i(t, "Trying connecting to: " + url);
EditText username = (EditText) dialogView.findViewById(R.id.username_edit);
String storedUsername = settings.getString(PreferencesActivity.KEY_USERNAME, null);
username.setText(storedUsername);
EditText password = (EditText) dialogView.findViewById(R.id.password_edit);
String storedPassword = settings.getString(PreferencesActivity.KEY_PASSWORD, null);
password.setText(storedPassword);
b.setTitle(getString(R.string.server_requires_auth));
b.setMessage(getString(R.string.server_auth_credentials, url));
b.setView(dialogView);
b.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.AUTH_DIALOG", "OK");
EditText username = (EditText) dialogView.findViewById(R.id.username_edit);
EditText password = (EditText) dialogView.findViewById(R.id.password_edit);
Uri u = Uri.parse(url);
WebUtils.addCredentials(username.getText().toString(), password.getText()
.toString(), u.getHost());
showDialog(PROGRESS_DIALOG);
mInstanceUploaderTask = new InstanceUploaderTask();
// register this activity with the new uploader task
mInstanceUploaderTask.setUploaderListener(InstanceUploaderActivity.this);
mInstanceUploaderTask.execute(mInstancesToSend);
}
});
b.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.AUTH_DIALOG", "cancel");
finish();
}
});
b.setCancelable(false);
return b.create();
}
return null;
}
@Override
public void authRequest(Uri url, HashMap<String, String> doneSoFar) {
if (mProgressDialog.isShowing()) {
// should always be showing here
mProgressDialog.dismiss();
}
// add our list of completed uploads to "completed"
// and remove them from our toSend list.
ArrayList<Long> workingSet = new ArrayList<Long>();
Collections.addAll(workingSet, mInstancesToSend);
if (doneSoFar != null) {
Set<String> uploadedInstances = doneSoFar.keySet();
Iterator<String> itr = uploadedInstances.iterator();
while (itr.hasNext()) {
Long removeMe = Long.valueOf(itr.next());
boolean removed = workingSet.remove(removeMe);
if (removed) {
Log.i(t, removeMe
+ " was already sent, removing from queue before restarting task");
}
}
mUploadedInstances.putAll(doneSoFar);
}
// and reconstruct the pending set of instances to send
Long[] updatedToSend = new Long[workingSet.size()];
for ( int i = 0 ; i < workingSet.size() ; ++i ) {
updatedToSend[i] = workingSet.get(i);
}
mInstancesToSend = updatedToSend;
mUrl = url.toString();
showDialog(AUTH_DIALOG);
}
private void createAlertDialog(String message) {
Collect.getInstance().getActivityLogger().logAction(this, "createAlertDialog", "show");
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setTitle(getString(R.string.upload_results));
mAlertDialog.setMessage(message);
DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON_POSITIVE: // ok
Collect.getInstance().getActivityLogger().logAction(this, "createAlertDialog", "OK");
// always exit this activity since it has no interface
mAlertShowing = false;
finish();
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.ok), quitListener);
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertShowing = true;
mAlertMsg = message;
mAlertDialog.show();
}
}
|
0nima0-f
|
src/org/odk/collect/android/activities/InstanceUploaderActivity.java
|
Java
|
asf20
| 17,129
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.activities;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.FormDownloaderListener;
import org.odk.collect.android.listeners.FormListDownloaderListener;
import org.odk.collect.android.logic.FormDetails;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.odk.collect.android.tasks.DownloadFormListTask;
import org.odk.collect.android.tasks.DownloadFormsTask;
import org.odk.collect.android.utilities.CompatibilityUtils;
import org.odk.collect.android.utilities.WebUtils;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
/**
* Responsible for displaying, adding and deleting all the valid forms in the forms directory. One
* caveat. If the server requires authentication, a dialog will pop up asking when you request the
* form list. If somehow you manage to wait long enough and then try to download selected forms and
* your authorization has timed out, it won't again ask for authentication, it will just throw a 401
* and you'll have to hit 'refresh' where it will ask for credentials again. Technically a server
* could point at other servers requiring authentication to download the forms, but the current
* implementation in Collect doesn't allow for that. Mostly this is just because it's a pain in the
* butt to keep track of which forms we've downloaded and where we're needing to authenticate. I
* think we do something similar in the instanceuploader task/activity, so should change the
* implementation eventually.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class FormDownloadList extends ListActivity implements FormListDownloaderListener,
FormDownloaderListener {
private static final String t = "RemoveFileManageList";
private static final int PROGRESS_DIALOG = 1;
private static final int AUTH_DIALOG = 2;
private static final int MENU_PREFERENCES = Menu.FIRST;
private static final String BUNDLE_TOGGLED_KEY = "toggled";
private static final String BUNDLE_SELECTED_COUNT = "selectedcount";
private static final String BUNDLE_FORM_MAP = "formmap";
private static final String DIALOG_TITLE = "dialogtitle";
private static final String DIALOG_MSG = "dialogmsg";
private static final String DIALOG_SHOWING = "dialogshowing";
private static final String FORMLIST = "formlist";
public static final String LIST_URL = "listurl";
private static final String FORMNAME = "formname";
private static final String FORMDETAIL_KEY = "formdetailkey";
private static final String FORMID_DISPLAY = "formiddisplay";
private String mAlertMsg;
private boolean mAlertShowing = false;
private String mAlertTitle;
private AlertDialog mAlertDialog;
private ProgressDialog mProgressDialog;
private Button mDownloadButton;
private DownloadFormListTask mDownloadFormListTask;
private DownloadFormsTask mDownloadFormsTask;
private Button mToggleButton;
private Button mRefreshButton;
private HashMap<String, FormDetails> mFormNamesAndURLs = new HashMap<String,FormDetails>();
private SimpleAdapter mFormListAdapter;
private ArrayList<HashMap<String, String>> mFormList;
private boolean mToggled = false;
private int mSelectedCount = 0;
private static final boolean EXIT = true;
private static final boolean DO_NOT_EXIT = false;
private boolean mShouldExit;
private static final String SHOULD_EXIT = "shouldexit";
@SuppressWarnings("unchecked")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.remote_file_manage_list);
setTitle(getString(R.string.app_name) + " > " + getString(R.string.get_forms));
mAlertMsg = getString(R.string.please_wait);
// need white background before load
getListView().setBackgroundColor(Color.WHITE);
mDownloadButton = (Button) findViewById(R.id.add_button);
mDownloadButton.setEnabled(selectedItemCount() > 0);
mDownloadButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// this is callled in downloadSelectedFiles():
// Collect.getInstance().getActivityLogger().logAction(this, "downloadSelectedFiles", ...);
downloadSelectedFiles();
mToggled = false;
clearChoices();
}
});
mToggleButton = (Button) findViewById(R.id.toggle_button);
mToggleButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// toggle selections of items to all or none
ListView ls = getListView();
mToggled = !mToggled;
Collect.getInstance().getActivityLogger().logAction(this, "toggleFormCheckbox", Boolean.toString(mToggled));
for (int pos = 0; pos < ls.getCount(); pos++) {
ls.setItemChecked(pos, mToggled);
}
mDownloadButton.setEnabled(!(selectedItemCount() == 0));
}
});
mRefreshButton = (Button) findViewById(R.id.refresh_button);
mRefreshButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logAction(this, "refreshForms", "");
mToggled = false;
downloadFormList();
FormDownloadList.this.getListView().clearChoices();
clearChoices();
}
});
if (savedInstanceState != null) {
// If the screen has rotated, the hashmap with the form ids and urls is passed here.
if (savedInstanceState.containsKey(BUNDLE_FORM_MAP)) {
mFormNamesAndURLs =
(HashMap<String, FormDetails>) savedInstanceState
.getSerializable(BUNDLE_FORM_MAP);
}
// indicating whether or not select-all is on or off.
if (savedInstanceState.containsKey(BUNDLE_TOGGLED_KEY)) {
mToggled = savedInstanceState.getBoolean(BUNDLE_TOGGLED_KEY);
}
// how many items we've selected
// Android should keep track of this, but broken on rotate...
if (savedInstanceState.containsKey(BUNDLE_SELECTED_COUNT)) {
mSelectedCount = savedInstanceState.getInt(BUNDLE_SELECTED_COUNT);
mDownloadButton.setEnabled(!(mSelectedCount == 0));
}
// to restore alert dialog.
if (savedInstanceState.containsKey(DIALOG_TITLE)) {
mAlertTitle = savedInstanceState.getString(DIALOG_TITLE);
}
if (savedInstanceState.containsKey(DIALOG_MSG)) {
mAlertMsg = savedInstanceState.getString(DIALOG_MSG);
}
if (savedInstanceState.containsKey(DIALOG_SHOWING)) {
mAlertShowing = savedInstanceState.getBoolean(DIALOG_SHOWING);
}
if (savedInstanceState.containsKey(SHOULD_EXIT)) {
mShouldExit = savedInstanceState.getBoolean(SHOULD_EXIT);
}
}
if (savedInstanceState != null && savedInstanceState.containsKey(FORMLIST)) {
mFormList =
(ArrayList<HashMap<String, String>>) savedInstanceState.getSerializable(FORMLIST);
} else {
mFormList = new ArrayList<HashMap<String, String>>();
}
if (getLastNonConfigurationInstance() instanceof DownloadFormListTask) {
mDownloadFormListTask = (DownloadFormListTask) getLastNonConfigurationInstance();
if (mDownloadFormListTask.getStatus() == AsyncTask.Status.FINISHED) {
try {
dismissDialog(PROGRESS_DIALOG);
} catch (IllegalArgumentException e) {
Log.i(t, "Attempting to close a dialog that was not previously opened");
}
mDownloadFormsTask = null;
}
} else if (getLastNonConfigurationInstance() instanceof DownloadFormsTask) {
mDownloadFormsTask = (DownloadFormsTask) getLastNonConfigurationInstance();
if (mDownloadFormsTask.getStatus() == AsyncTask.Status.FINISHED) {
try {
dismissDialog(PROGRESS_DIALOG);
} catch (IllegalArgumentException e) {
Log.i(t, "Attempting to close a dialog that was not previously opened");
}
mDownloadFormsTask = null;
}
} else if (getLastNonConfigurationInstance() == null) {
// first time, so get the formlist
downloadFormList();
}
String[] data = new String[] {
FORMNAME, FORMID_DISPLAY, FORMDETAIL_KEY
};
int[] view = new int[] {
R.id.text1, R.id.text2
};
mFormListAdapter =
new SimpleAdapter(this, mFormList, R.layout.two_item_multiple_choice, data, view);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
getListView().setItemsCanFocus(false);
setListAdapter(mFormListAdapter);
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
private void clearChoices() {
FormDownloadList.this.getListView().clearChoices();
mDownloadButton.setEnabled(false);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
mDownloadButton.setEnabled(!(selectedItemCount() == 0));
Object o = getListAdapter().getItem(position);
@SuppressWarnings("unchecked")
HashMap<String, String> item = (HashMap<String, String>) o;
FormDetails detail = mFormNamesAndURLs.get(item.get(FORMDETAIL_KEY));
if ( detail != null ) {
Collect.getInstance().getActivityLogger().logAction(this, "onListItemClick", detail.downloadUrl);
} else {
Collect.getInstance().getActivityLogger().logAction(this, "onListItemClick", "<missing form detail>");
}
}
/**
* Starts the download task and shows the progress dialog.
*/
private void downloadFormList() {
ConnectivityManager connectivityManager =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
if (ni == null || !ni.isConnected()) {
Toast.makeText(this, R.string.no_connection, Toast.LENGTH_SHORT).show();
} else {
mFormNamesAndURLs = new HashMap<String, FormDetails>();
if (mProgressDialog != null) {
// This is needed because onPrepareDialog() is broken in 1.6.
mProgressDialog.setMessage(getString(R.string.please_wait));
}
showDialog(PROGRESS_DIALOG);
if (mDownloadFormListTask != null &&
mDownloadFormListTask.getStatus() != AsyncTask.Status.FINISHED) {
return; // we are already doing the download!!!
} else if (mDownloadFormListTask != null) {
mDownloadFormListTask.setDownloaderListener(null);
mDownloadFormListTask.cancel(true);
mDownloadFormListTask = null;
}
mDownloadFormListTask = new DownloadFormListTask();
mDownloadFormListTask.setDownloaderListener(this);
mDownloadFormListTask.execute();
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(BUNDLE_TOGGLED_KEY, mToggled);
outState.putInt(BUNDLE_SELECTED_COUNT, selectedItemCount());
outState.putSerializable(BUNDLE_FORM_MAP, mFormNamesAndURLs);
outState.putString(DIALOG_TITLE, mAlertTitle);
outState.putString(DIALOG_MSG, mAlertMsg);
outState.putBoolean(DIALOG_SHOWING, mAlertShowing);
outState.putBoolean(SHOULD_EXIT, mShouldExit);
outState.putSerializable(FORMLIST, mFormList);
}
/**
* returns the number of items currently selected in the list.
*
* @return
*/
private int selectedItemCount() {
int count = 0;
SparseBooleanArray sba = getListView().getCheckedItemPositions();
for (int i = 0; i < getListView().getCount(); i++) {
if (sba.get(i, false)) {
count++;
}
}
return count;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Collect.getInstance().getActivityLogger().logAction(this, "onCreateOptionsMenu", "show");
super.onCreateOptionsMenu(menu);
CompatibilityUtils.setShowAsAction(
menu.add(0, MENU_PREFERENCES, 0, R.string.general_preferences)
.setIcon(R.drawable.ic_menu_preferences),
MenuItem.SHOW_AS_ACTION_NEVER);
return true;
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case MENU_PREFERENCES:
Collect.getInstance().getActivityLogger().logAction(this, "onMenuItemSelected", "MENU_PREFERENCES");
Intent i = new Intent(this, PreferencesActivity.class);
startActivity(i);
return true;
}
return super.onMenuItemSelected(featureId, item);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.PROGRESS_DIALOG", "show");
mProgressDialog = new ProgressDialog(this);
DialogInterface.OnClickListener loadingButtonListener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.PROGRESS_DIALOG", "OK");
dialog.dismiss();
// we use the same progress dialog for both
// so whatever isn't null is running
if (mDownloadFormListTask != null) {
mDownloadFormListTask.setDownloaderListener(null);
mDownloadFormListTask.cancel(true);
mDownloadFormListTask = null;
}
if (mDownloadFormsTask != null) {
mDownloadFormsTask.setDownloaderListener(null);
mDownloadFormsTask.cancel(true);
mDownloadFormsTask = null;
}
}
};
mProgressDialog.setTitle(getString(R.string.downloading_data));
mProgressDialog.setMessage(mAlertMsg);
mProgressDialog.setIcon(android.R.drawable.ic_dialog_info);
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setButton(getString(R.string.cancel), loadingButtonListener);
return mProgressDialog;
case AUTH_DIALOG:
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.AUTH_DIALOG", "show");
AlertDialog.Builder b = new AlertDialog.Builder(this);
LayoutInflater factory = LayoutInflater.from(this);
final View dialogView = factory.inflate(R.layout.server_auth_dialog, null);
// Get the server, username, and password from the settings
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String server =
settings.getString(PreferencesActivity.KEY_SERVER_URL,
getString(R.string.default_server_url));
String formListUrl = getString(R.string.default_odk_formlist);
final String url =
server + settings.getString(PreferencesActivity.KEY_FORMLIST_URL, formListUrl);
Log.i(t, "Trying to get formList from: " + url);
EditText username = (EditText) dialogView.findViewById(R.id.username_edit);
String storedUsername = settings.getString(PreferencesActivity.KEY_USERNAME, null);
username.setText(storedUsername);
EditText password = (EditText) dialogView.findViewById(R.id.password_edit);
String storedPassword = settings.getString(PreferencesActivity.KEY_PASSWORD, null);
password.setText(storedPassword);
b.setTitle(getString(R.string.server_requires_auth));
b.setMessage(getString(R.string.server_auth_credentials, url));
b.setView(dialogView);
b.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.AUTH_DIALOG", "OK");
EditText username = (EditText) dialogView.findViewById(R.id.username_edit);
EditText password = (EditText) dialogView.findViewById(R.id.password_edit);
Uri u = Uri.parse(url);
WebUtils.addCredentials(username.getText().toString(), password.getText()
.toString(), u.getHost());
downloadFormList();
}
});
b.setNegativeButton(getString(R.string.cancel),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.AUTH_DIALOG", "Cancel");
finish();
}
});
b.setCancelable(false);
mAlertShowing = false;
return b.create();
}
return null;
}
/**
* starts the task to download the selected forms, also shows progress dialog
*/
@SuppressWarnings("unchecked")
private void downloadSelectedFiles() {
int totalCount = 0;
ArrayList<FormDetails> filesToDownload = new ArrayList<FormDetails>();
SparseBooleanArray sba = getListView().getCheckedItemPositions();
for (int i = 0; i < getListView().getCount(); i++) {
if (sba.get(i, false)) {
HashMap<String, String> item =
(HashMap<String, String>) getListAdapter().getItem(i);
filesToDownload.add(mFormNamesAndURLs.get(item.get(FORMDETAIL_KEY)));
}
}
totalCount = filesToDownload.size();
Collect.getInstance().getActivityLogger().logAction(this, "downloadSelectedFiles", Integer.toString(totalCount));
if (totalCount > 0) {
// show dialog box
showDialog(PROGRESS_DIALOG);
mDownloadFormsTask = new DownloadFormsTask();
mDownloadFormsTask.setDownloaderListener(this);
mDownloadFormsTask.execute(filesToDownload);
} else {
Toast.makeText(getApplicationContext(), R.string.noselect_error, Toast.LENGTH_SHORT)
.show();
}
}
@Override
public Object onRetainNonConfigurationInstance() {
if (mDownloadFormsTask != null) {
return mDownloadFormsTask;
} else {
return mDownloadFormListTask;
}
}
@Override
protected void onDestroy() {
if (mDownloadFormListTask != null) {
mDownloadFormListTask.setDownloaderListener(null);
}
if (mDownloadFormsTask != null) {
mDownloadFormsTask.setDownloaderListener(null);
}
super.onDestroy();
}
@Override
protected void onResume() {
if (mDownloadFormListTask != null) {
mDownloadFormListTask.setDownloaderListener(this);
}
if (mDownloadFormsTask != null) {
mDownloadFormsTask.setDownloaderListener(this);
}
if (mAlertShowing) {
createAlertDialog(mAlertTitle, mAlertMsg, mShouldExit);
}
super.onResume();
}
@Override
protected void onPause() {
if (mAlertDialog != null && mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
super.onPause();
}
/**
* Called when the form list has finished downloading. results will either contain a set of
* <formname, formdetails> tuples, or one tuple of DL.ERROR.MSG and the associated message.
*
* @param result
*/
public void formListDownloadingComplete(HashMap<String, FormDetails> result) {
dismissDialog(PROGRESS_DIALOG);
mDownloadFormListTask.setDownloaderListener(null);
mDownloadFormListTask = null;
if (result == null) {
Log.e(t, "Formlist Downloading returned null. That shouldn't happen");
// Just displayes "error occured" to the user, but this should never happen.
createAlertDialog(getString(R.string.load_remote_form_error),
getString(R.string.error_occured), EXIT);
return;
}
if (result.containsKey(DownloadFormListTask.DL_AUTH_REQUIRED)) {
// need authorization
showDialog(AUTH_DIALOG);
} else if (result.containsKey(DownloadFormListTask.DL_ERROR_MSG)) {
// Download failed
String dialogMessage =
getString(R.string.list_failed_with_error,
result.get(DownloadFormListTask.DL_ERROR_MSG).errorStr);
String dialogTitle = getString(R.string.load_remote_form_error);
createAlertDialog(dialogTitle, dialogMessage, DO_NOT_EXIT);
} else {
// Everything worked. Clear the list and add the results.
mFormNamesAndURLs = result;
mFormList.clear();
ArrayList<String> ids = new ArrayList<String>(mFormNamesAndURLs.keySet());
for (int i = 0; i < result.size(); i++) {
String formDetailsKey = ids.get(i);
FormDetails details = mFormNamesAndURLs.get(formDetailsKey);
HashMap<String, String> item = new HashMap<String, String>();
item.put(FORMNAME, details.formName);
item.put(FORMID_DISPLAY,
((details.formVersion == null) ? "" : (getString(R.string.version) + " " + details.formVersion + " ")) +
"ID: " + details.formID );
item.put(FORMDETAIL_KEY, formDetailsKey);
// Insert the new form in alphabetical order.
if (mFormList.size() == 0) {
mFormList.add(item);
} else {
int j;
for (j = 0; j < mFormList.size(); j++) {
HashMap<String, String> compareMe = mFormList.get(j);
String name = compareMe.get(FORMNAME);
if (name.compareTo(mFormNamesAndURLs.get(ids.get(i)).formName) > 0) {
break;
}
}
mFormList.add(j, item);
}
}
mFormListAdapter.notifyDataSetChanged();
}
}
/**
* Creates an alert dialog with the given tite and message. If shouldExit is set to true, the
* activity will exit when the user clicks "ok".
*
* @param title
* @param message
* @param shouldExit
*/
private void createAlertDialog(String title, String message, final boolean shouldExit) {
Collect.getInstance().getActivityLogger().logAction(this, "createAlertDialog", "show");
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setTitle(title);
mAlertDialog.setMessage(message);
DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON_POSITIVE: // ok
Collect.getInstance().getActivityLogger().logAction(this, "createAlertDialog", "OK");
// just close the dialog
mAlertShowing = false;
// successful download, so quit
if (shouldExit) {
finish();
}
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.ok), quitListener);
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertMsg = message;
mAlertTitle = title;
mAlertShowing = true;
mShouldExit = shouldExit;
mAlertDialog.show();
}
@Override
public void progressUpdate(String currentFile, int progress, int total) {
mAlertMsg = getString(R.string.fetching_file, currentFile, progress, total);
mProgressDialog.setMessage(mAlertMsg);
}
@Override
public void formsDownloadingComplete(HashMap<FormDetails, String> result) {
if (mDownloadFormsTask != null) {
mDownloadFormsTask.setDownloaderListener(null);
}
if (mProgressDialog.isShowing()) {
// should always be true here
mProgressDialog.dismiss();
}
Set<FormDetails> keys = result.keySet();
StringBuilder b = new StringBuilder();
for (FormDetails k : keys) {
b.append(k.formName +
" (" +
((k.formVersion != null) ?
(this.getString(R.string.version) + ": " + k.formVersion + " ")
: "") +
"ID: " + k.formID + ") - " +
result.get(k));
b.append("\n\n");
}
createAlertDialog(getString(R.string.download_forms_result), b.toString().trim(), EXIT);
}
}
|
0nima0-f
|
src/org/odk/collect/android/activities/FormDownloadList.java
|
Java
|
asf20
| 28,589
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.adapters;
import org.odk.collect.android.logic.HierarchyElement;
import org.odk.collect.android.views.HierarchyElementView;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import java.util.ArrayList;
import java.util.List;
public class HierarchyListAdapter extends BaseAdapter {
private Context mContext;
private List<HierarchyElement> mItems = new ArrayList<HierarchyElement>();
public HierarchyListAdapter(Context context) {
mContext = context;
}
@Override
public int getCount() {
return mItems.size();
}
@Override
public Object getItem(int position) {
return mItems.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
HierarchyElementView hev;
if (convertView == null) {
hev = new HierarchyElementView(mContext, mItems.get(position));
} else {
hev = (HierarchyElementView) convertView;
hev.setPrimaryText(mItems.get(position).getPrimaryText());
hev.setSecondaryText(mItems.get(position).getSecondaryText());
hev.setIcon(mItems.get(position).getIcon());
hev.setColor(mItems.get(position).getColor());
}
if (mItems.get(position).getSecondaryText() == null
|| mItems.get(position).getSecondaryText().equals("")) {
hev.showSecondary(false);
} else {
hev.showSecondary(true);
}
return hev;
}
/**
* Sets the list of items for this adapter to use.
*/
public void setListItems(List<HierarchyElement> it) {
mItems = it;
}
}
|
0nima0-f
|
src/org/odk/collect/android/adapters/HierarchyListAdapter.java
|
Java
|
asf20
| 2,468
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.adapters;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.odk.collect.android.R;
import org.odk.collect.android.logic.DriveListItem;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
public class FileArrayAdapter extends ArrayAdapter<DriveListItem> {
private Context c;
private int id;
private List<DriveListItem> items;
public FileArrayAdapter(Context context, int textViewResourceId,
List<DriveListItem> objects) {
super(context, textViewResourceId, objects);
c = context;
id = textViewResourceId;
items = objects;
}
public DriveListItem getItem(int i) {
return items.get(i);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(id, null);
}
/* create a new view of my layout and inflate it in the row */
//convertView = ( RelativeLayout ) inflater.inflate( resource, null );
final DriveListItem o = items.get(position);
if (o != null) {
String dateModified = null;
if (o.getDate() != null) {
dateModified = new SimpleDateFormat(getContext().getString(
R.string.modified_on_date_at_time), Locale.getDefault())
.format(new Date(o.getDate().getValue()));
}
TextView t1 = (TextView) v.findViewById(R.id.text1);
TextView t2 = (TextView) v.findViewById(R.id.text2);
ImageView iv = (ImageView) v.findViewById(R.id.image);
CheckBox cb = (CheckBox) v.findViewById(R.id.checkbox);
if (o.getType() == 1) {
Drawable d = c.getResources().getDrawable(R.drawable.ic_download);
iv.setImageDrawable(d);
cb.setVisibility(View.VISIBLE);
}
if (o.getType() == 3) {
Drawable d = c.getResources().getDrawable(R.drawable.ic_back);
iv.setImageDrawable(d);
}
if (o.getType() == 2 || o.getType() == 4 || o.getType() == 5) {
Drawable d = c.getResources().getDrawable(R.drawable.ic_folder);
iv.setImageDrawable(d);
}
if (t1 != null)
t1.setText(o.getName());
if (t2 != null)
t2.setText(dateModified);
}
return v;
}
}
|
0nima0-f
|
src/org/odk/collect/android/adapters/FileArrayAdapter.java
|
Java
|
asf20
| 3,551
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.odk.collect.android.provider;
import android.net.Uri;
import android.provider.BaseColumns;
/**
* Convenience definitions for NotePadProvider
*/
public final class InstanceProviderAPI {
public static final String AUTHORITY = "org.odk.collect.android.provider.odk.instances";
// This class cannot be instantiated
private InstanceProviderAPI() {}
// status for instances
public static final String STATUS_INCOMPLETE = "incomplete";
public static final String STATUS_COMPLETE = "complete";
public static final String STATUS_SUBMITTED = "submitted";
public static final String STATUS_SUBMISSION_FAILED = "submissionFailed";
/**
* Notes table
*/
public static final class InstanceColumns implements BaseColumns {
// This class cannot be instantiated
private InstanceColumns() {}
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/instances");
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.odk.instance";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.odk.instance";
// These are the only things needed for an insert
public static final String DISPLAY_NAME = "displayName";
public static final String SUBMISSION_URI = "submissionUri";
public static final String INSTANCE_FILE_PATH = "instanceFilePath";
public static final String JR_FORM_ID = "jrFormId";
public static final String JR_VERSION = "jrVersion";
//public static final String FORM_ID = "formId";
// these are generated for you (but you can insert something else if you want)
public static final String STATUS = "status";
public static final String CAN_EDIT_WHEN_COMPLETE = "canEditWhenComplete";
public static final String LAST_STATUS_CHANGE_DATE = "date";
public static final String DISPLAY_SUBTEXT = "displaySubtext";
//public static final String DISPLAY_SUB_SUBTEXT = "displaySubSubtext";
// public static final String DEFAULT_SORT_ORDER = "modified DESC";
// public static final String TITLE = "title";
// public static final String NOTE = "note";
// public static final String CREATED_DATE = "created";
// public static final String MODIFIED_DATE = "modified";
}
}
|
0nima0-f
|
src/org/odk/collect/android/provider/InstanceProviderAPI.java
|
Java
|
asf20
| 3,005
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.provider;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.database.ODKSQLiteOpenHelper;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import org.odk.collect.android.utilities.MediaUtils;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
/**
*
*/
public class InstanceProvider extends ContentProvider {
private static final String t = "InstancesProvider";
private static final String DATABASE_NAME = "instances.db";
private static final int DATABASE_VERSION = 3;
private static final String INSTANCES_TABLE_NAME = "instances";
private static HashMap<String, String> sInstancesProjectionMap;
private static final int INSTANCES = 1;
private static final int INSTANCE_ID = 2;
private static final UriMatcher sUriMatcher;
/**
* This class helps open, create, and upgrade the database file.
*/
private static class DatabaseHelper extends ODKSQLiteOpenHelper {
DatabaseHelper(String databaseName) {
super(Collect.METADATA_PATH, databaseName, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + INSTANCES_TABLE_NAME + " ("
+ InstanceColumns._ID + " integer primary key, "
+ InstanceColumns.DISPLAY_NAME + " text not null, "
+ InstanceColumns.SUBMISSION_URI + " text, "
+ InstanceColumns.CAN_EDIT_WHEN_COMPLETE + " text, "
+ InstanceColumns.INSTANCE_FILE_PATH + " text not null, "
+ InstanceColumns.JR_FORM_ID + " text not null, "
+ InstanceColumns.JR_VERSION + " text, "
+ InstanceColumns.STATUS + " text not null, "
+ InstanceColumns.LAST_STATUS_CHANGE_DATE + " date not null, "
+ InstanceColumns.DISPLAY_SUBTEXT + " text not null );");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
int initialVersion = oldVersion;
if ( oldVersion == 1 ) {
db.execSQL("ALTER TABLE " + INSTANCES_TABLE_NAME + " ADD COLUMN " +
InstanceColumns.CAN_EDIT_WHEN_COMPLETE + " text;");
db.execSQL("UPDATE " + INSTANCES_TABLE_NAME + " SET " +
InstanceColumns.CAN_EDIT_WHEN_COMPLETE + " = '" + Boolean.toString(true) + "' WHERE " +
InstanceColumns.STATUS + " IS NOT NULL AND " +
InstanceColumns.STATUS + " != '" + InstanceProviderAPI.STATUS_INCOMPLETE + "'");
oldVersion = 2;
}
if ( oldVersion == 2 ) {
db.execSQL("ALTER TABLE " + INSTANCES_TABLE_NAME + " ADD COLUMN " +
InstanceColumns.JR_VERSION + " text;");
}
Log.w(t, "Successfully upgraded database from version " + initialVersion + " to " + newVersion
+ ", without destroying all the old data");
}
}
private DatabaseHelper mDbHelper;
private DatabaseHelper getDbHelper() {
// wrapper to test and reset/set the dbHelper based upon the attachment state of the device.
try {
Collect.createODKDirs();
} catch (RuntimeException e) {
mDbHelper = null;
return null;
}
if (mDbHelper != null) {
return mDbHelper;
}
mDbHelper = new DatabaseHelper(DATABASE_NAME);
return mDbHelper;
}
@Override
public boolean onCreate() {
// must be at the beginning of any activity that can be called from an external intent
DatabaseHelper h = getDbHelper();
if ( h == null ) {
return false;
}
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(INSTANCES_TABLE_NAME);
switch (sUriMatcher.match(uri)) {
case INSTANCES:
qb.setProjectionMap(sInstancesProjectionMap);
break;
case INSTANCE_ID:
qb.setProjectionMap(sInstancesProjectionMap);
qb.appendWhere(InstanceColumns._ID + "=" + uri.getPathSegments().get(1));
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
// Get the database and run the query
SQLiteDatabase db = getDbHelper().getReadableDatabase();
Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
// Tell the cursor what uri to watch, so it knows when its source data changes
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
@Override
public String getType(Uri uri) {
switch (sUriMatcher.match(uri)) {
case INSTANCES:
return InstanceColumns.CONTENT_TYPE;
case INSTANCE_ID:
return InstanceColumns.CONTENT_ITEM_TYPE;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
}
@Override
public Uri insert(Uri uri, ContentValues initialValues) {
// Validate the requested uri
if (sUriMatcher.match(uri) != INSTANCES) {
throw new IllegalArgumentException("Unknown URI " + uri);
}
ContentValues values;
if (initialValues != null) {
values = new ContentValues(initialValues);
} else {
values = new ContentValues();
}
Long now = Long.valueOf(System.currentTimeMillis());
// Make sure that the fields are all set
if (values.containsKey(InstanceColumns.LAST_STATUS_CHANGE_DATE) == false) {
values.put(InstanceColumns.LAST_STATUS_CHANGE_DATE, now);
}
if (values.containsKey(InstanceColumns.DISPLAY_SUBTEXT) == false) {
Date today = new Date();
String text = getDisplaySubtext(InstanceProviderAPI.STATUS_INCOMPLETE, today);
values.put(InstanceColumns.DISPLAY_SUBTEXT, text);
}
if (values.containsKey(InstanceColumns.STATUS) == false) {
values.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_INCOMPLETE);
}
SQLiteDatabase db = getDbHelper().getWritableDatabase();
long rowId = db.insert(INSTANCES_TABLE_NAME, null, values);
if (rowId > 0) {
Uri instanceUri = ContentUris.withAppendedId(InstanceColumns.CONTENT_URI, rowId);
getContext().getContentResolver().notifyChange(instanceUri, null);
Collect.getInstance().getActivityLogger().logActionParam(this, "insert",
instanceUri.toString(), values.getAsString(InstanceColumns.INSTANCE_FILE_PATH));
return instanceUri;
}
throw new SQLException("Failed to insert row into " + uri);
}
private String getDisplaySubtext(String state, Date date) {
if (state == null) {
return new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time), Locale.getDefault()).format(date);
} else if (InstanceProviderAPI.STATUS_INCOMPLETE.equalsIgnoreCase(state)) {
return new SimpleDateFormat(getContext().getString(R.string.saved_on_date_at_time), Locale.getDefault()).format(date);
} else if (InstanceProviderAPI.STATUS_COMPLETE.equalsIgnoreCase(state)) {
return new SimpleDateFormat(getContext().getString(R.string.finalized_on_date_at_time), Locale.getDefault()).format(date);
} else if (InstanceProviderAPI.STATUS_SUBMITTED.equalsIgnoreCase(state)) {
return new SimpleDateFormat(getContext().getString(R.string.sent_on_date_at_time), Locale.getDefault()).format(date);
} else if (InstanceProviderAPI.STATUS_SUBMISSION_FAILED.equalsIgnoreCase(state)) {
return new SimpleDateFormat(getContext().getString(R.string.sending_failed_on_date_at_time), Locale.getDefault()).format(date);
} else {
return new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time), Locale.getDefault()).format(date);
}
}
private void deleteAllFilesInDirectory(File directory) {
if (directory.exists()) {
// do not delete the directory if it might be an
// ODK Tables instance data directory. Let ODK Tables
// manage the lifetimes of its filled-in form data
// media attachments.
if (directory.isDirectory() && !Collect.isODKTablesInstanceDataDirectory(directory)) {
// delete any media entries for files in this directory...
int images = MediaUtils.deleteImagesInFolderFromMediaProvider(directory);
int audio = MediaUtils.deleteAudioInFolderFromMediaProvider(directory);
int video = MediaUtils.deleteVideoInFolderFromMediaProvider(directory);
Log.i(t, "removed from content providers: " + images
+ " image files, " + audio + " audio files,"
+ " and " + video + " video files.");
// delete all the files in the directory
File[] files = directory.listFiles();
for (File f : files) {
// should make this recursive if we get worried about
// the media directory containing directories
f.delete();
}
}
directory.delete();
}
}
/**
* This method removes the entry from the content provider, and also removes any associated files.
* files: form.xml, [formmd5].formdef, formname-media {directory}
*/
@Override
public int delete(Uri uri, String where, String[] whereArgs) {
SQLiteDatabase db = getDbHelper().getWritableDatabase();
int count;
switch (sUriMatcher.match(uri)) {
case INSTANCES:
Cursor del = null;
try {
del = this.query(uri, null, where, whereArgs, null);
if (del.getCount() > 0) {
del.moveToFirst();
do {
String instanceFile = del.getString(del.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
Collect.getInstance().getActivityLogger().logAction(this, "delete", instanceFile);
File instanceDir = (new File(instanceFile)).getParentFile();
deleteAllFilesInDirectory(instanceDir);
} while (del.moveToNext());
}
} finally {
if ( del != null ) {
del.close();
}
}
count = db.delete(INSTANCES_TABLE_NAME, where, whereArgs);
break;
case INSTANCE_ID:
String instanceId = uri.getPathSegments().get(1);
Cursor c = null;
try {
c = this.query(uri, null, where, whereArgs, null);
if (c.getCount() > 0) {
c.moveToFirst();
do {
String instanceFile = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
Collect.getInstance().getActivityLogger().logAction(this, "delete", instanceFile);
File instanceDir = (new File(instanceFile)).getParentFile();
deleteAllFilesInDirectory(instanceDir);
} while (c.moveToNext());
}
} finally {
if ( c != null ) {
c.close();
}
}
count =
db.delete(INSTANCES_TABLE_NAME,
InstanceColumns._ID + "=" + instanceId
+ (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""),
whereArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
SQLiteDatabase db = getDbHelper().getWritableDatabase();
Long now = Long.valueOf(System.currentTimeMillis());
// Make sure that the fields are all set
if (values.containsKey(InstanceColumns.LAST_STATUS_CHANGE_DATE) == false) {
values.put(InstanceColumns.LAST_STATUS_CHANGE_DATE, now);
}
int count;
String status = null;
switch (sUriMatcher.match(uri)) {
case INSTANCES:
if (values.containsKey(InstanceColumns.STATUS)) {
status = values.getAsString(InstanceColumns.STATUS);
if (values.containsKey(InstanceColumns.DISPLAY_SUBTEXT) == false) {
Date today = new Date();
String text = getDisplaySubtext(status, today);
values.put(InstanceColumns.DISPLAY_SUBTEXT, text);
}
}
count = db.update(INSTANCES_TABLE_NAME, values, where, whereArgs);
break;
case INSTANCE_ID:
String instanceId = uri.getPathSegments().get(1);
if (values.containsKey(InstanceColumns.STATUS)) {
status = values.getAsString(InstanceColumns.STATUS);
if (values.containsKey(InstanceColumns.DISPLAY_SUBTEXT) == false) {
Date today = new Date();
String text = getDisplaySubtext(status, today);
values.put(InstanceColumns.DISPLAY_SUBTEXT, text);
}
}
count =
db.update(INSTANCES_TABLE_NAME, values, InstanceColumns._ID + "=" + instanceId
+ (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
static {
sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
sUriMatcher.addURI(InstanceProviderAPI.AUTHORITY, "instances", INSTANCES);
sUriMatcher.addURI(InstanceProviderAPI.AUTHORITY, "instances/#", INSTANCE_ID);
sInstancesProjectionMap = new HashMap<String, String>();
sInstancesProjectionMap.put(InstanceColumns._ID, InstanceColumns._ID);
sInstancesProjectionMap.put(InstanceColumns.DISPLAY_NAME, InstanceColumns.DISPLAY_NAME);
sInstancesProjectionMap.put(InstanceColumns.SUBMISSION_URI, InstanceColumns.SUBMISSION_URI);
sInstancesProjectionMap.put(InstanceColumns.CAN_EDIT_WHEN_COMPLETE, InstanceColumns.CAN_EDIT_WHEN_COMPLETE);
sInstancesProjectionMap.put(InstanceColumns.INSTANCE_FILE_PATH, InstanceColumns.INSTANCE_FILE_PATH);
sInstancesProjectionMap.put(InstanceColumns.JR_FORM_ID, InstanceColumns.JR_FORM_ID);
sInstancesProjectionMap.put(InstanceColumns.JR_VERSION, InstanceColumns.JR_VERSION);
sInstancesProjectionMap.put(InstanceColumns.STATUS, InstanceColumns.STATUS);
sInstancesProjectionMap.put(InstanceColumns.LAST_STATUS_CHANGE_DATE, InstanceColumns.LAST_STATUS_CHANGE_DATE);
sInstancesProjectionMap.put(InstanceColumns.DISPLAY_SUBTEXT, InstanceColumns.DISPLAY_SUBTEXT);
}
}
|
0nima0-f
|
src/org/odk/collect/android/provider/InstanceProvider.java
|
Java
|
asf20
| 16,896
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.odk.collect.android.provider;
import android.net.Uri;
import android.provider.BaseColumns;
/**
* Convenience definitions for NotePadProvider
*/
public final class FormsProviderAPI {
public static final String AUTHORITY = "org.odk.collect.android.provider.odk.forms";
// This class cannot be instantiated
private FormsProviderAPI() {}
/**
* Notes table
*/
public static final class FormsColumns implements BaseColumns {
// This class cannot be instantiated
private FormsColumns() {}
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/forms");
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.odk.form";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.odk.form";
// These are the only things needed for an insert
public static final String DISPLAY_NAME = "displayName";
public static final String DESCRIPTION = "description"; // can be null
public static final String JR_FORM_ID = "jrFormId";
public static final String JR_VERSION = "jrVersion"; // can be null
public static final String FORM_FILE_PATH = "formFilePath";
public static final String SUBMISSION_URI = "submissionUri"; // can be null
public static final String BASE64_RSA_PUBLIC_KEY = "base64RsaPublicKey"; // can be null
// these are generated for you (but you can insert something else if you want)
public static final String DISPLAY_SUBTEXT = "displaySubtext";
public static final String MD5_HASH = "md5Hash";
public static final String DATE = "date";
public static final String JRCACHE_FILE_PATH = "jrcacheFilePath";
public static final String FORM_MEDIA_PATH = "formMediaPath";
// this is null on create, and can only be set on an update.
public static final String LANGUAGE = "language";
}
}
|
0nima0-f
|
src/org/odk/collect/android/provider/FormsProviderAPI.java
|
Java
|
asf20
| 2,634
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.provider;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.database.ItemsetDbAdapter;
import org.odk.collect.android.database.ODKSQLiteOpenHelper;
import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.utilities.MediaUtils;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
/**
*
*/
public class FormsProvider extends ContentProvider {
private static final String t = "FormsProvider";
private static final String DATABASE_NAME = "forms.db";
private static final int DATABASE_VERSION = 4;
private static final String FORMS_TABLE_NAME = "forms";
private static HashMap<String, String> sFormsProjectionMap;
private static final int FORMS = 1;
private static final int FORM_ID = 2;
private static final UriMatcher sUriMatcher;
/**
* This class helps open, create, and upgrade the database file.
*/
private static class DatabaseHelper extends ODKSQLiteOpenHelper {
// These exist in database versions 2 and 3, but not in 4...
private static final String TEMP_FORMS_TABLE_NAME = "forms_v4";
private static final String MODEL_VERSION = "modelVersion";
DatabaseHelper(String databaseName) {
super(Collect.METADATA_PATH, databaseName, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
onCreateNamed(db, FORMS_TABLE_NAME);
}
private void onCreateNamed(SQLiteDatabase db, String tableName) {
db.execSQL("CREATE TABLE " + tableName + " (" + FormsColumns._ID
+ " integer primary key, " + FormsColumns.DISPLAY_NAME
+ " text not null, " + FormsColumns.DISPLAY_SUBTEXT
+ " text not null, " + FormsColumns.DESCRIPTION
+ " text, "
+ FormsColumns.JR_FORM_ID
+ " text not null, "
+ FormsColumns.JR_VERSION
+ " text, "
+ FormsColumns.MD5_HASH
+ " text not null, "
+ FormsColumns.DATE
+ " integer not null, " // milliseconds
+ FormsColumns.FORM_MEDIA_PATH + " text not null, "
+ FormsColumns.FORM_FILE_PATH + " text not null, "
+ FormsColumns.LANGUAGE + " text, "
+ FormsColumns.SUBMISSION_URI + " text, "
+ FormsColumns.BASE64_RSA_PUBLIC_KEY + " text, "
+ FormsColumns.JRCACHE_FILE_PATH + " text not null );");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
int initialVersion = oldVersion;
if (oldVersion < 2) {
Log.w(t, "Upgrading database from version " + oldVersion
+ " to " + newVersion
+ ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + FORMS_TABLE_NAME);
onCreate(db);
return;
} else {
// adding BASE64_RSA_PUBLIC_KEY and changing type and name of
// integer MODEL_VERSION to text VERSION
db.execSQL("DROP TABLE IF EXISTS " + TEMP_FORMS_TABLE_NAME);
onCreateNamed(db, TEMP_FORMS_TABLE_NAME);
db.execSQL("INSERT INTO "
+ TEMP_FORMS_TABLE_NAME
+ " ("
+ FormsColumns._ID
+ ", "
+ FormsColumns.DISPLAY_NAME
+ ", "
+ FormsColumns.DISPLAY_SUBTEXT
+ ", "
+ FormsColumns.DESCRIPTION
+ ", "
+ FormsColumns.JR_FORM_ID
+ ", "
+ FormsColumns.MD5_HASH
+ ", "
+ FormsColumns.DATE
+ ", " // milliseconds
+ FormsColumns.FORM_MEDIA_PATH
+ ", "
+ FormsColumns.FORM_FILE_PATH
+ ", "
+ FormsColumns.LANGUAGE
+ ", "
+ FormsColumns.SUBMISSION_URI
+ ", "
+ FormsColumns.JR_VERSION
+ ", "
+ ((oldVersion != 3) ? ""
: (FormsColumns.BASE64_RSA_PUBLIC_KEY + ", "))
+ FormsColumns.JRCACHE_FILE_PATH
+ ") SELECT "
+ FormsColumns._ID
+ ", "
+ FormsColumns.DISPLAY_NAME
+ ", "
+ FormsColumns.DISPLAY_SUBTEXT
+ ", "
+ FormsColumns.DESCRIPTION
+ ", "
+ FormsColumns.JR_FORM_ID
+ ", "
+ FormsColumns.MD5_HASH
+ ", "
+ FormsColumns.DATE
+ ", " // milliseconds
+ FormsColumns.FORM_MEDIA_PATH
+ ", "
+ FormsColumns.FORM_FILE_PATH
+ ", "
+ FormsColumns.LANGUAGE
+ ", "
+ FormsColumns.SUBMISSION_URI
+ ", "
+ "CASE WHEN "
+ MODEL_VERSION
+ " IS NOT NULL THEN "
+ "CAST("
+ MODEL_VERSION
+ " AS TEXT) ELSE NULL END, "
+ ((oldVersion != 3) ? ""
: (FormsColumns.BASE64_RSA_PUBLIC_KEY + ", "))
+ FormsColumns.JRCACHE_FILE_PATH + " FROM "
+ FORMS_TABLE_NAME);
// risky failures here...
db.execSQL("DROP TABLE IF EXISTS " + FORMS_TABLE_NAME);
onCreateNamed(db, FORMS_TABLE_NAME);
db.execSQL("INSERT INTO "
+ FORMS_TABLE_NAME
+ " ("
+ FormsColumns._ID
+ ", "
+ FormsColumns.DISPLAY_NAME
+ ", "
+ FormsColumns.DISPLAY_SUBTEXT
+ ", "
+ FormsColumns.DESCRIPTION
+ ", "
+ FormsColumns.JR_FORM_ID
+ ", "
+ FormsColumns.MD5_HASH
+ ", "
+ FormsColumns.DATE
+ ", " // milliseconds
+ FormsColumns.FORM_MEDIA_PATH + ", "
+ FormsColumns.FORM_FILE_PATH + ", "
+ FormsColumns.LANGUAGE + ", "
+ FormsColumns.SUBMISSION_URI + ", "
+ FormsColumns.JR_VERSION + ", "
+ FormsColumns.BASE64_RSA_PUBLIC_KEY + ", "
+ FormsColumns.JRCACHE_FILE_PATH + ") SELECT "
+ FormsColumns._ID + ", "
+ FormsColumns.DISPLAY_NAME
+ ", "
+ FormsColumns.DISPLAY_SUBTEXT
+ ", "
+ FormsColumns.DESCRIPTION
+ ", "
+ FormsColumns.JR_FORM_ID
+ ", "
+ FormsColumns.MD5_HASH
+ ", "
+ FormsColumns.DATE
+ ", " // milliseconds
+ FormsColumns.FORM_MEDIA_PATH + ", "
+ FormsColumns.FORM_FILE_PATH + ", "
+ FormsColumns.LANGUAGE + ", "
+ FormsColumns.SUBMISSION_URI + ", "
+ FormsColumns.JR_VERSION + ", "
+ FormsColumns.BASE64_RSA_PUBLIC_KEY + ", "
+ FormsColumns.JRCACHE_FILE_PATH + " FROM "
+ TEMP_FORMS_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + TEMP_FORMS_TABLE_NAME);
Log.w(t, "Successfully upgraded database from version "
+ initialVersion + " to " + newVersion
+ ", without destroying all the old data");
}
}
}
private DatabaseHelper mDbHelper;
private DatabaseHelper getDbHelper() {
// wrapper to test and reset/set the dbHelper based upon the attachment state of the device.
try {
Collect.createODKDirs();
} catch (RuntimeException e) {
mDbHelper = null;
return null;
}
if (mDbHelper != null) {
return mDbHelper;
}
mDbHelper = new DatabaseHelper(DATABASE_NAME);
return mDbHelper;
}
@Override
public boolean onCreate() {
// must be at the beginning of any activity that can be called from an external intent
DatabaseHelper h = getDbHelper();
if ( h == null ) {
return false;
}
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(FORMS_TABLE_NAME);
switch (sUriMatcher.match(uri)) {
case FORMS:
qb.setProjectionMap(sFormsProjectionMap);
break;
case FORM_ID:
qb.setProjectionMap(sFormsProjectionMap);
qb.appendWhere(FormsColumns._ID + "="
+ uri.getPathSegments().get(1));
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
// Get the database and run the query
SQLiteDatabase db = getDbHelper().getReadableDatabase();
Cursor c = qb.query(db, projection, selection, selectionArgs, null,
null, sortOrder);
// Tell the cursor what uri to watch, so it knows when its source data
// changes
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
@Override
public String getType(Uri uri) {
switch (sUriMatcher.match(uri)) {
case FORMS:
return FormsColumns.CONTENT_TYPE;
case FORM_ID:
return FormsColumns.CONTENT_ITEM_TYPE;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
}
@Override
public synchronized Uri insert(Uri uri, ContentValues initialValues) {
// Validate the requested uri
if (sUriMatcher.match(uri) != FORMS) {
throw new IllegalArgumentException("Unknown URI " + uri);
}
ContentValues values;
if (initialValues != null) {
values = new ContentValues(initialValues);
} else {
values = new ContentValues();
}
if (!values.containsKey(FormsColumns.FORM_FILE_PATH)) {
throw new IllegalArgumentException(FormsColumns.FORM_FILE_PATH
+ " must be specified.");
}
// Normalize the file path.
// (don't trust the requester).
String filePath = values.getAsString(FormsColumns.FORM_FILE_PATH);
File form = new File(filePath);
filePath = form.getAbsolutePath(); // normalized
values.put(FormsColumns.FORM_FILE_PATH, filePath);
Long now = Long.valueOf(System.currentTimeMillis());
// Make sure that the necessary fields are all set
if (values.containsKey(FormsColumns.DATE) == false) {
values.put(FormsColumns.DATE, now);
}
if (values.containsKey(FormsColumns.DISPLAY_SUBTEXT) == false) {
Date today = new Date();
String ts = new SimpleDateFormat(getContext().getString(
R.string.added_on_date_at_time), Locale.getDefault())
.format(today);
values.put(FormsColumns.DISPLAY_SUBTEXT, ts);
}
if (values.containsKey(FormsColumns.DISPLAY_NAME) == false) {
values.put(FormsColumns.DISPLAY_NAME, form.getName());
}
// don't let users put in a manual md5 hash
if (values.containsKey(FormsColumns.MD5_HASH)) {
values.remove(FormsColumns.MD5_HASH);
}
String md5 = FileUtils.getMd5Hash(form);
values.put(FormsColumns.MD5_HASH, md5);
if (values.containsKey(FormsColumns.JRCACHE_FILE_PATH) == false) {
String cachePath = Collect.CACHE_PATH + File.separator + md5
+ ".formdef";
values.put(FormsColumns.JRCACHE_FILE_PATH, cachePath);
}
if (values.containsKey(FormsColumns.FORM_MEDIA_PATH) == false) {
String pathNoExtension = filePath.substring(0,
filePath.lastIndexOf("."));
String mediaPath = pathNoExtension + "-media";
values.put(FormsColumns.FORM_MEDIA_PATH, mediaPath);
}
SQLiteDatabase db = getDbHelper().getWritableDatabase();
// first try to see if a record with this filename already exists...
String[] projection = { FormsColumns._ID, FormsColumns.FORM_FILE_PATH };
String[] selectionArgs = { filePath };
String selection = FormsColumns.FORM_FILE_PATH + "=?";
Cursor c = null;
try {
c = db.query(FORMS_TABLE_NAME, projection, selection,
selectionArgs, null, null, null);
if (c.getCount() > 0) {
// already exists
throw new SQLException("FAILED Insert into " + uri
+ " -- row already exists for form definition file: "
+ filePath);
}
} finally {
if (c != null) {
c.close();
}
}
long rowId = db.insert(FORMS_TABLE_NAME, null, values);
if (rowId > 0) {
Uri formUri = ContentUris.withAppendedId(FormsColumns.CONTENT_URI,
rowId);
getContext().getContentResolver().notifyChange(formUri, null);
Collect.getInstance()
.getActivityLogger()
.logActionParam(this, "insert", formUri.toString(),
values.getAsString(FormsColumns.FORM_FILE_PATH));
return formUri;
}
throw new SQLException("Failed to insert row into " + uri);
}
private void deleteFileOrDir(String fileName) {
File file = new File(fileName);
if (file.exists()) {
if (file.isDirectory()) {
// delete any media entries for files in this directory...
int images = MediaUtils
.deleteImagesInFolderFromMediaProvider(file);
int audio = MediaUtils
.deleteAudioInFolderFromMediaProvider(file);
int video = MediaUtils
.deleteVideoInFolderFromMediaProvider(file);
Log.i(t, "removed from content providers: " + images
+ " image files, " + audio + " audio files," + " and "
+ video + " video files.");
// delete all the containing files
File[] files = file.listFiles();
for (File f : files) {
// should make this recursive if we get worried about
// the media directory containing directories
Log.i(t,
"attempting to delete file: " + f.getAbsolutePath());
f.delete();
}
}
file.delete();
Log.i(t, "attempting to delete file: " + file.getAbsolutePath());
}
}
/**
* This method removes the entry from the content provider, and also removes
* any associated files. files: form.xml, [formmd5].formdef, formname-media
* {directory}
*/
@Override
public int delete(Uri uri, String where, String[] whereArgs) {
SQLiteDatabase db = getDbHelper().getWritableDatabase();
int count;
switch (sUriMatcher.match(uri)) {
case FORMS:
Cursor del = null;
try {
del = this.query(uri, null, where, whereArgs, null);
if (del.getCount() > 0) {
del.moveToFirst();
do {
deleteFileOrDir(del
.getString(del
.getColumnIndex(FormsColumns.JRCACHE_FILE_PATH)));
String formFilePath = del.getString(del
.getColumnIndex(FormsColumns.FORM_FILE_PATH));
Collect.getInstance().getActivityLogger()
.logAction(this, "delete", formFilePath);
deleteFileOrDir(formFilePath);
deleteFileOrDir(del.getString(del
.getColumnIndex(FormsColumns.FORM_MEDIA_PATH)));
} while (del.moveToNext());
}
} finally {
if (del != null) {
del.close();
}
}
count = db.delete(FORMS_TABLE_NAME, where, whereArgs);
break;
case FORM_ID:
String formId = uri.getPathSegments().get(1);
Cursor c = null;
try {
c = this.query(uri, null, where, whereArgs, null);
// This should only ever return 1 record.
if (c.getCount() > 0) {
c.moveToFirst();
do {
deleteFileOrDir(c.getString(c
.getColumnIndex(FormsColumns.JRCACHE_FILE_PATH)));
String formFilePath = c.getString(c
.getColumnIndex(FormsColumns.FORM_FILE_PATH));
Collect.getInstance().getActivityLogger()
.logAction(this, "delete", formFilePath);
deleteFileOrDir(formFilePath);
deleteFileOrDir(c.getString(c
.getColumnIndex(FormsColumns.FORM_MEDIA_PATH)));
try {
// get rid of the old tables
ItemsetDbAdapter ida = new ItemsetDbAdapter();
ida.open();
ida.delete(c.getString(c
.getColumnIndex(FormsColumns.FORM_MEDIA_PATH))
+ "/itemsets.csv");
ida.close();
} catch (Exception e) {
// if something else is accessing the provider this may not exist
// so catch it and move on.
}
} while (c.moveToNext());
}
} finally {
if (c != null) {
c.close();
}
}
count = db.delete(
FORMS_TABLE_NAME,
FormsColumns._ID
+ "="
+ formId
+ (!TextUtils.isEmpty(where) ? " AND (" + where
+ ')' : ""), whereArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
public int update(Uri uri, ContentValues values, String where,
String[] whereArgs) {
SQLiteDatabase db = getDbHelper().getWritableDatabase();
int count = 0;
switch (sUriMatcher.match(uri)) {
case FORMS:
// don't let users manually update md5
if (values.containsKey(FormsColumns.MD5_HASH)) {
values.remove(FormsColumns.MD5_HASH);
}
// if values contains path, then all filepaths and md5s will get
// updated
// this probably isn't a great thing to do.
if (values.containsKey(FormsColumns.FORM_FILE_PATH)) {
String formFile = values
.getAsString(FormsColumns.FORM_FILE_PATH);
values.put(FormsColumns.MD5_HASH,
FileUtils.getMd5Hash(new File(formFile)));
}
Cursor c = null;
try {
c = this.query(uri, null, where, whereArgs, null);
if (c.getCount() > 0) {
c.moveToPosition(-1);
while (c.moveToNext()) {
// before updating the paths, delete all the files
if (values.containsKey(FormsColumns.FORM_FILE_PATH)) {
String newFile = values
.getAsString(FormsColumns.FORM_FILE_PATH);
String delFile = c
.getString(c
.getColumnIndex(FormsColumns.FORM_FILE_PATH));
if (newFile.equalsIgnoreCase(delFile)) {
// same file, so don't delete anything
} else {
// different files, delete the old one
deleteFileOrDir(delFile);
}
// either way, delete the old cache because we'll
// calculate a new one.
deleteFileOrDir(c
.getString(c
.getColumnIndex(FormsColumns.JRCACHE_FILE_PATH)));
}
}
}
} finally {
if (c != null) {
c.close();
}
}
// Make sure that the necessary fields are all set
if (values.containsKey(FormsColumns.DATE) == true) {
Date today = new Date();
String ts = new SimpleDateFormat(getContext().getString(
R.string.added_on_date_at_time), Locale.getDefault())
.format(today);
values.put(FormsColumns.DISPLAY_SUBTEXT, ts);
}
count = db.update(FORMS_TABLE_NAME, values, where, whereArgs);
break;
case FORM_ID:
String formId = uri.getPathSegments().get(1);
// Whenever file paths are updated, delete the old files.
Cursor update = null;
try {
update = this.query(uri, null, where, whereArgs, null);
// This should only ever return 1 record.
if (update.getCount() > 0) {
update.moveToFirst();
// don't let users manually update md5
if (values.containsKey(FormsColumns.MD5_HASH)) {
values.remove(FormsColumns.MD5_HASH);
}
// the order here is important (jrcache needs to be before
// form file)
// because we update the jrcache file if there's a new form
// file
if (values.containsKey(FormsColumns.JRCACHE_FILE_PATH)) {
deleteFileOrDir(update
.getString(update
.getColumnIndex(FormsColumns.JRCACHE_FILE_PATH)));
}
if (values.containsKey(FormsColumns.FORM_FILE_PATH)) {
String formFile = values
.getAsString(FormsColumns.FORM_FILE_PATH);
String oldFile = update.getString(update
.getColumnIndex(FormsColumns.FORM_FILE_PATH));
if (formFile != null
&& formFile.equalsIgnoreCase(oldFile)) {
// Files are the same, so we may have just copied
// over something we had
// already
} else {
// New file name. This probably won't ever happen,
// though.
deleteFileOrDir(oldFile);
}
// we're updating our file, so update the md5
// and get rid of the cache (doesn't harm anything)
deleteFileOrDir(update
.getString(update
.getColumnIndex(FormsColumns.JRCACHE_FILE_PATH)));
String newMd5 = FileUtils
.getMd5Hash(new File(formFile));
values.put(FormsColumns.MD5_HASH, newMd5);
values.put(FormsColumns.JRCACHE_FILE_PATH,
Collect.CACHE_PATH + File.separator + newMd5
+ ".formdef");
}
// Make sure that the necessary fields are all set
if (values.containsKey(FormsColumns.DATE) == true) {
Date today = new Date();
String ts = new SimpleDateFormat(getContext()
.getString(R.string.added_on_date_at_time),
Locale.getDefault()).format(today);
values.put(FormsColumns.DISPLAY_SUBTEXT, ts);
}
count = db.update(
FORMS_TABLE_NAME,
values,
FormsColumns._ID
+ "="
+ formId
+ (!TextUtils.isEmpty(where) ? " AND ("
+ where + ')' : ""), whereArgs);
} else {
Log.e(t, "Attempting to update row that does not exist");
}
} finally {
if (update != null) {
update.close();
}
}
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
static {
sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
sUriMatcher.addURI(FormsProviderAPI.AUTHORITY, "forms", FORMS);
sUriMatcher.addURI(FormsProviderAPI.AUTHORITY, "forms/#", FORM_ID);
sFormsProjectionMap = new HashMap<String, String>();
sFormsProjectionMap.put(FormsColumns._ID, FormsColumns._ID);
sFormsProjectionMap.put(FormsColumns.DISPLAY_NAME,
FormsColumns.DISPLAY_NAME);
sFormsProjectionMap.put(FormsColumns.DISPLAY_SUBTEXT,
FormsColumns.DISPLAY_SUBTEXT);
sFormsProjectionMap.put(FormsColumns.DESCRIPTION,
FormsColumns.DESCRIPTION);
sFormsProjectionMap.put(FormsColumns.JR_FORM_ID,
FormsColumns.JR_FORM_ID);
sFormsProjectionMap.put(FormsColumns.JR_VERSION,
FormsColumns.JR_VERSION);
sFormsProjectionMap.put(FormsColumns.SUBMISSION_URI,
FormsColumns.SUBMISSION_URI);
sFormsProjectionMap.put(FormsColumns.BASE64_RSA_PUBLIC_KEY,
FormsColumns.BASE64_RSA_PUBLIC_KEY);
sFormsProjectionMap.put(FormsColumns.MD5_HASH, FormsColumns.MD5_HASH);
sFormsProjectionMap.put(FormsColumns.DATE, FormsColumns.DATE);
sFormsProjectionMap.put(FormsColumns.FORM_MEDIA_PATH,
FormsColumns.FORM_MEDIA_PATH);
sFormsProjectionMap.put(FormsColumns.FORM_FILE_PATH,
FormsColumns.FORM_FILE_PATH);
sFormsProjectionMap.put(FormsColumns.JRCACHE_FILE_PATH,
FormsColumns.JRCACHE_FILE_PATH);
sFormsProjectionMap.put(FormsColumns.LANGUAGE, FormsColumns.LANGUAGE);
}
}
|
0nima0-f
|
src/org/odk/collect/android/provider/FormsProvider.java
|
Java
|
asf20
| 22,811
|
/*
* Copyright (C) 2011 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.views;
import java.io.Serializable;
import java.util.*;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.widget.*;
import org.javarosa.core.model.Constants;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.model.IFormElement;
import org.javarosa.core.model.QuestionDef;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.activities.FormEntryActivity;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.exception.ExternalParamsException;
import org.odk.collect.android.exception.JavaRosaException;
import org.odk.collect.android.external.ExternalAppsUtils;
import org.odk.collect.android.logic.FormController;
import org.odk.collect.android.widgets.IBinaryWidget;
import org.odk.collect.android.widgets.QuestionWidget;
import org.odk.collect.android.widgets.WidgetFactory;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
/**
* This class is
*
* @author carlhartung
*/
public class ODKView extends ScrollView implements OnLongClickListener {
// starter random number for view IDs
private final static int VIEW_ID = 12345;
private final static String t = "ODKView";
private LinearLayout mView;
private LinearLayout.LayoutParams mLayout;
private ArrayList<QuestionWidget> widgets;
private Handler h = null;
public final static String FIELD_LIST = "field-list";
public ODKView(Context context, final FormEntryPrompt[] questionPrompts,
FormEntryCaption[] groups, boolean advancingPage) {
super(context);
widgets = new ArrayList<QuestionWidget>();
mView = new LinearLayout(getContext());
mView.setOrientation(LinearLayout.VERTICAL);
mView.setGravity(Gravity.TOP);
mView.setPadding(0, 7, 0, 0);
mLayout =
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
mLayout.setMargins(10, 0, 10, 0);
// display which group you are in as well as the question
addGroupText(groups);
// when the grouped fields are populated by an external app, this will get true.
boolean readOnlyOverride = false;
// get the group we are showing -- it will be the last of the groups in the groups list
if (groups != null && groups.length > 0) {
final FormEntryCaption c = groups[groups.length - 1];
final String intentString = c.getFormElement().getAdditionalAttribute(null, "intent");
if (intentString != null && intentString.length() != 0) {
readOnlyOverride = true;
final String buttonText;
final String errorString;
String v = c.getSpecialFormQuestionText("buttonText");
buttonText = (v != null) ? v : context.getString(R.string.launch_app);
v = c.getSpecialFormQuestionText("noAppErrorString");
errorString = (v != null) ? v : context.getString(R.string.no_app);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
params.setMargins(7, 5, 7, 5);
// set button formatting
Button mLaunchIntentButton = new Button(getContext());
mLaunchIntentButton.setId(QuestionWidget.newUniqueId());
mLaunchIntentButton.setText(buttonText);
mLaunchIntentButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, Collect.getQuestionFontsize() + 2);
mLaunchIntentButton.setPadding(20, 20, 20, 20);
mLaunchIntentButton.setLayoutParams(params);
mLaunchIntentButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String intentName = ExternalAppsUtils.extractIntentName(intentString);
Map<String, String> parameters = ExternalAppsUtils.extractParameters(intentString);
Intent i = new Intent(intentName);
try {
ExternalAppsUtils.populateParameters(i, parameters, c.getIndex().getReference());
for (FormEntryPrompt p : questionPrompts) {
IFormElement formElement = p.getFormElement();
if (formElement instanceof QuestionDef) {
TreeReference reference = (TreeReference) formElement.getBind().getReference();
IAnswerData answerValue = p.getAnswerValue();
Object value = answerValue == null ? null : answerValue.getValue();
switch (p.getDataType()) {
case Constants.DATATYPE_TEXT:
case Constants.DATATYPE_INTEGER:
case Constants.DATATYPE_DECIMAL:
i.putExtra(reference.getNameLast(), (Serializable) value);
break;
}
}
}
((Activity) getContext()).startActivityForResult(i, FormEntryActivity.EX_GROUP_CAPTURE);
} catch (ExternalParamsException e) {
Log.e("ExternalParamsException", e.getMessage(), e);
Toast.makeText(getContext(),
e.getMessage(), Toast.LENGTH_SHORT)
.show();
} catch (ActivityNotFoundException e) {
Log.e("ActivityNotFoundException", e.getMessage(), e);
Toast.makeText(getContext(),
errorString, Toast.LENGTH_SHORT)
.show();
}
}
});
View divider = new View(getContext());
divider.setBackgroundResource(android.R.drawable.divider_horizontal_bright);
divider.setMinimumHeight(3);
mView.addView(divider);
mView.addView(mLaunchIntentButton, mLayout);
}
}
boolean first = true;
int id = 0;
for (FormEntryPrompt p : questionPrompts) {
if (!first) {
View divider = new View(getContext());
divider.setBackgroundResource(android.R.drawable.divider_horizontal_bright);
divider.setMinimumHeight(3);
mView.addView(divider);
} else {
first = false;
}
// if question or answer type is not supported, use text widget
QuestionWidget qw =
WidgetFactory.createWidgetFromPrompt(p, getContext(), readOnlyOverride);
qw.setLongClickable(true);
qw.setOnLongClickListener(this);
qw.setId(VIEW_ID + id++);
widgets.add(qw);
mView.addView(qw, mLayout);
}
addView(mView);
// see if there is an autoplay option.
// Only execute it during forward swipes through the form
if ( advancingPage && widgets.size() == 1 ) {
final String playOption = widgets.get(0).getPrompt().getFormElement().getAdditionalAttribute(null, "autoplay");
if ( playOption != null ) {
h = new Handler();
h.postDelayed(new Runnable() {
@Override
public void run() {
if ( playOption.equalsIgnoreCase("audio") ) {
widgets.get(0).playAudio();
} else if ( playOption.equalsIgnoreCase("video") ) {
widgets.get(0).playVideo();
}
}
}, 150);
}
}
}
/**
* http://code.google.com/p/android/issues/detail?id=8488
*/
public void recycleDrawables() {
this.destroyDrawingCache();
mView.destroyDrawingCache();
for ( QuestionWidget q : widgets ) {
q.recycleDrawables();
}
}
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
Collect.getInstance().getActivityLogger().logScrollAction(this, t - oldt);
}
/**
* @return a HashMap of answers entered by the user for this set of widgets
*/
public LinkedHashMap<FormIndex, IAnswerData> getAnswers() {
LinkedHashMap<FormIndex, IAnswerData> answers = new LinkedHashMap<FormIndex, IAnswerData>();
Iterator<QuestionWidget> i = widgets.iterator();
while (i.hasNext()) {
/*
* The FormEntryPrompt has the FormIndex, which is where the answer gets stored. The
* QuestionWidget has the answer the user has entered.
*/
QuestionWidget q = i.next();
FormEntryPrompt p = q.getPrompt();
answers.put(p.getIndex(), q.getAnswer());
}
return answers;
}
/**
* // * Add a TextView containing the hierarchy of groups to which the question belongs. //
*/
private void addGroupText(FormEntryCaption[] groups) {
StringBuilder s = new StringBuilder("");
String t = "";
int i;
// list all groups in one string
for (FormEntryCaption g : groups) {
i = g.getMultiplicity() + 1;
t = g.getLongText();
if (t != null) {
s.append(t);
if (g.repeats() && i > 0) {
s.append(" (" + i + ")");
}
s.append(" > ");
}
}
// build view
if (s.length() > 0) {
TextView tv = new TextView(getContext());
tv.setText(s.substring(0, s.length() - 3));
int questionFontsize = Collect.getQuestionFontsize();
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, questionFontsize - 4);
tv.setPadding(0, 0, 0, 5);
mView.addView(tv, mLayout);
}
}
public void setFocus(Context context) {
if (widgets.size() > 0) {
widgets.get(0).setFocus(context);
}
}
/**
* Called when another activity returns information to answer this question.
*
* @param answer
*/
public void setBinaryData(Object answer) {
boolean set = false;
for (QuestionWidget q : widgets) {
if (q instanceof IBinaryWidget) {
if (((IBinaryWidget) q).isWaitingForBinaryData()) {
try {
((IBinaryWidget) q).setBinaryData(answer);
} catch (Exception e) {
Log.e(t, e.getMessage(), e);
Toast.makeText(getContext(), getContext().getString(R.string.error_attaching_binary_file, e.getMessage()), Toast.LENGTH_LONG).show();
}
set = true;
break;
}
}
}
if (!set) {
Log.w(t, "Attempting to return data to a widget or set of widgets not looking for data");
}
}
public void setDataForFields(Bundle bundle) throws JavaRosaException {
if (bundle == null) {
return;
}
FormController formController = Collect.getInstance().getFormController();
Set<String> keys = bundle.keySet();
for (String key : keys) {
for (QuestionWidget questionWidget : widgets) {
FormEntryPrompt prompt = questionWidget.getPrompt();
TreeReference treeReference = (TreeReference) prompt.getFormElement().getBind().getReference();
if (treeReference.getNameLast().equals(key)) {
switch (prompt.getDataType()) {
case Constants.DATATYPE_TEXT:
formController.saveAnswer(prompt.getIndex(), ExternalAppsUtils.asStringData(bundle.get(key)));
break;
case Constants.DATATYPE_INTEGER:
formController.saveAnswer(prompt.getIndex(), ExternalAppsUtils.asIntegerData(bundle.get(key)));
break;
case Constants.DATATYPE_DECIMAL:
formController.saveAnswer(prompt.getIndex(), ExternalAppsUtils.asDecimalData(bundle.get(key)));
break;
default:
throw new RuntimeException(getContext().getString(R.string.ext_assign_value_error, treeReference.toString(false)));
}
break;
}
}
}
}
public void cancelWaitingForBinaryData() {
int count = 0;
for (QuestionWidget q : widgets) {
if (q instanceof IBinaryWidget) {
if (((IBinaryWidget) q).isWaitingForBinaryData()) {
((IBinaryWidget) q).cancelWaitingForBinaryData();
++count;
}
}
}
if (count != 1) {
Log.w(t, "Attempting to cancel waiting for binary data to a widget or set of widgets not looking for data");
}
}
public boolean suppressFlingGesture(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
for (QuestionWidget q : widgets) {
if ( q.suppressFlingGesture(e1, e2, velocityX, velocityY) ) {
return true;
}
}
return false;
}
/**
* @return true if the answer was cleared, false otherwise.
*/
public boolean clearAnswer() {
// If there's only one widget, clear the answer.
// If there are more, then force a long-press to clear the answer.
if (widgets.size() == 1 && !widgets.get(0).getPrompt().isReadOnly()) {
widgets.get(0).clearAnswer();
return true;
} else {
return false;
}
}
public ArrayList<QuestionWidget> getWidgets() {
return widgets;
}
@Override
public void setOnFocusChangeListener(OnFocusChangeListener l) {
for (int i = 0; i < widgets.size(); i++) {
QuestionWidget qw = widgets.get(i);
qw.setOnFocusChangeListener(l);
}
}
@Override
public boolean onLongClick(View v) {
return false;
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
for (QuestionWidget qw : widgets) {
qw.cancelLongPress();
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/views/ODKView.java
|
Java
|
asf20
| 15,889
|
/*
* Copyright (C) 2011 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.views;
import java.io.File;
import java.io.IOException;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.Toast;
/**
* @author ctsims
* @author carlhartung
*/
public class AudioButton extends ImageButton implements OnClickListener {
private final static String t = "AudioButton";
/**
* Useful class for handling the playing and stopping of audio prompts.
* This is used here, and also in the GridMultiWidget and GridWidget
* to play prompts as items are selected.
*
* @author mitchellsundt@gmail.com
*
*/
public static class AudioHandler {
private FormIndex index;
private String selectionDesignator;
private String URI;
private MediaPlayer player;
public AudioHandler(FormIndex index, String selectionDesignator, String URI) {
this.index = index;
this.selectionDesignator = selectionDesignator;
this.URI = URI;
player = null;
}
public void playAudio(Context c) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onClick.playAudioPrompt", selectionDesignator, index);
if (URI == null) {
// No audio file specified
Log.e(t, "No audio file was specified");
Toast.makeText(c, c.getString(R.string.audio_file_error),
Toast.LENGTH_LONG).show();
return;
}
String audioFilename = "";
try {
audioFilename = ReferenceManager._().DeriveReference(URI).getLocalURI();
} catch (InvalidReferenceException e) {
Log.e(t, "Invalid reference exception");
e.printStackTrace();
}
File audioFile = new File(audioFilename);
if (!audioFile.exists()) {
// We should have an audio clip, but the file doesn't exist.
String errorMsg = c.getString(R.string.file_missing, audioFile);
Log.e(t, errorMsg);
Toast.makeText(c, errorMsg, Toast.LENGTH_LONG).show();
return;
}
// In case we're currently playing sounds.
stopPlaying();
player = new MediaPlayer();
try {
player.setDataSource(audioFilename);
player.prepare();
player.start();
player.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.release();
}
});
} catch (IOException e) {
String errorMsg = c.getString(R.string.audio_file_invalid);
Log.e(t, errorMsg);
Toast.makeText(c, errorMsg, Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
public void stopPlaying() {
if (player != null) {
player.release();
}
}
}
AudioHandler handler;
public AudioButton(Context context, FormIndex index, String selectionDesignator, String URI) {
super(context);
this.setOnClickListener(this);
handler = new AudioHandler( index, selectionDesignator, URI);
Bitmap b =
BitmapFactory.decodeResource(context.getResources(),
android.R.drawable.ic_lock_silent_mode_off);
this.setImageBitmap(b);
}
public void playAudio() {
handler.playAudio(getContext());
}
@Override
public void onClick(View v) {
playAudio();
}
public void stopPlaying() {
handler.stopPlaying();
}
}
|
0nima0-f
|
src/org/odk/collect/android/views/AudioButton.java
|
Java
|
asf20
| 5,095
|
/*
* Copyright (C) 2011 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.views;
import java.io.File;
import android.widget.*;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.widgets.QuestionWidget;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView.ScaleType;
/**
* This layout is used anywhere we can have image/audio/video/text. TODO: It would probably be nice
* to put this in a layout.xml file of some sort at some point.
*
* @author carlhartung
*/
public class MediaLayout extends RelativeLayout {
private static final String t = "AVTLayout";
private String mSelectionDesignator;
private FormIndex mIndex;
private TextView mView_Text;
private AudioButton mAudioButton;
private ImageButton mVideoButton;
private ImageView mImageView;
private TextView mMissingImage;
private String mVideoURI = null;
public MediaLayout(Context c) {
super(c);
mView_Text = null;
mAudioButton = null;
mImageView = null;
mMissingImage = null;
mVideoButton = null;
mIndex = null;
}
public void playAudio() {
if ( mAudioButton != null ) {
mAudioButton.playAudio();
}
}
public void playVideo() {
if ( mVideoURI != null ) {
String videoFilename = "";
try {
videoFilename =
ReferenceManager._().DeriveReference(mVideoURI).getLocalURI();
} catch (InvalidReferenceException e) {
Log.e(t, "Invalid reference exception");
e.printStackTrace();
}
File videoFile = new File(videoFilename);
if (!videoFile.exists()) {
// We should have a video clip, but the file doesn't exist.
String errorMsg =
getContext().getString(R.string.file_missing, videoFilename);
Log.e(t, errorMsg);
Toast.makeText(getContext(), errorMsg, Toast.LENGTH_LONG).show();
return;
}
Intent i = new Intent("android.intent.action.VIEW");
i.setDataAndType(Uri.fromFile(videoFile), "video/*");
try {
((Activity) getContext()).startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(getContext(),
getContext().getString(R.string.activity_not_found, "view video"),
Toast.LENGTH_SHORT).show();
}
}
}
public void setAVT(FormIndex index, String selectionDesignator, TextView text, String audioURI, String imageURI, String videoURI,
final String bigImageURI) {
mSelectionDesignator = selectionDesignator;
mIndex = index;
mView_Text = text;
mView_Text.setId(QuestionWidget.newUniqueId());
mVideoURI = videoURI;
// Layout configurations for our elements in the relative layout
RelativeLayout.LayoutParams textParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams audioParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams imageParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams videoParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// First set up the audio button
if (audioURI != null) {
// An audio file is specified
mAudioButton = new AudioButton(getContext(), mIndex, mSelectionDesignator, audioURI);
mAudioButton.setId(QuestionWidget.newUniqueId()); // random ID to be used by the
// relative layout.
} else {
// No audio file specified, so ignore.
}
// Then set up the video button
if (videoURI != null) {
// An video file is specified
mVideoButton = new ImageButton(getContext());
Bitmap b =
BitmapFactory.decodeResource(getContext().getResources(),
android.R.drawable.ic_media_play);
mVideoButton.setImageBitmap(b);
mVideoButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onClick", "playVideoPrompt"+mSelectionDesignator, mIndex);
MediaLayout.this.playVideo();
}
});
mVideoButton.setId(QuestionWidget.newUniqueId());
} else {
// No video file specified, so ignore.
}
// Now set up the image view
String errorMsg = null;
final int imageId = QuestionWidget.newUniqueId();
if (imageURI != null) {
try {
String imageFilename = ReferenceManager._().DeriveReference(imageURI).getLocalURI();
final File imageFile = new File(imageFilename);
if (imageFile.exists()) {
Display display =
((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
Bitmap b = FileUtils.getBitmapScaledToDisplay(imageFile, screenHeight, screenWidth);
if (b != null) {
mImageView = new ImageView(getContext());
mImageView.setPadding(2, 2, 2, 2);
mImageView.setBackgroundColor(Color.WHITE);
mImageView.setImageBitmap(b);
mImageView.setId(imageId);
if (bigImageURI != null) {
mImageView.setOnClickListener(new OnClickListener() {
String bigImageFilename = ReferenceManager._()
.DeriveReference(bigImageURI).getLocalURI();
File bigImage = new File(bigImageFilename);
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onClick", "showImagePromptBigImage"+mSelectionDesignator, mIndex);
Intent i = new Intent("android.intent.action.VIEW");
i.setDataAndType(Uri.fromFile(bigImage), "image/*");
try {
getContext().startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(
getContext(),
getContext().getString(R.string.activity_not_found,
"view image"), Toast.LENGTH_SHORT).show();
}
}
});
}
} else {
// Loading the image failed, so it's likely a bad file.
errorMsg = getContext().getString(R.string.file_invalid, imageFile);
}
} else {
// We should have an image, but the file doesn't exist.
errorMsg = getContext().getString(R.string.file_missing, imageFile);
}
if (errorMsg != null) {
// errorMsg is only set when an error has occurred
Log.e(t, errorMsg);
mMissingImage = new TextView(getContext());
mMissingImage.setText(errorMsg);
mMissingImage.setPadding(10, 10, 10, 10);
mMissingImage.setId(imageId);
}
} catch (InvalidReferenceException e) {
Log.e(t, "image invalid reference exception");
e.printStackTrace();
}
} else {
// There's no imageURI listed, so just ignore it.
}
// e.g., for TextView that flag will be true
boolean isNotAMultipleChoiceField = !RadioButton.class.isAssignableFrom(text.getClass()) && !CheckBox.class.isAssignableFrom(text.getClass());
// Determine the layout constraints...
// Assumes LTR, TTB reading bias!
if (mView_Text.getText().length() == 0 && (mImageView != null || mMissingImage != null)) {
// No text; has image. The image is treated as question/choice icon.
// The Text view may just have a radio button or checkbox. It
// needs to remain in the layout even though it is blank.
//
// The image view, as created above, will dynamically resize and
// center itself. We want it to resize but left-align itself
// in the resized area and we want a white background, as otherwise
// it will show a grey bar to the right of the image icon.
if (mImageView != null) {
mImageView.setScaleType(ScaleType.FIT_START);
}
//
// In this case, we have:
// Text upper left; image upper, left edge aligned with text right edge;
// audio upper right; video below audio on right.
textParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
textParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
if (isNotAMultipleChoiceField) {
imageParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
} else {
imageParams.addRule(RelativeLayout.RIGHT_OF, mView_Text.getId());
}
imageParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
if (mAudioButton != null && mVideoButton == null) {
audioParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
audioParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
imageParams.addRule(RelativeLayout.LEFT_OF, mAudioButton.getId());
} else if (mAudioButton == null && mVideoButton != null) {
videoParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
videoParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
imageParams.addRule(RelativeLayout.LEFT_OF, mVideoButton.getId());
} else if (mAudioButton != null && mVideoButton != null) {
audioParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
audioParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
imageParams.addRule(RelativeLayout.LEFT_OF, mAudioButton.getId());
videoParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
videoParams.addRule(RelativeLayout.BELOW, mAudioButton.getId());
imageParams.addRule(RelativeLayout.LEFT_OF, mVideoButton.getId());
} else {
// the image will implicitly scale down to fit within parent...
// no need to bound it by the width of the parent...
if (!isNotAMultipleChoiceField) {
imageParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
}
}
imageParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
} else {
// We have a non-blank text label -- image is below the text.
// In this case, we want the image to be centered...
if (mImageView != null) {
mImageView.setScaleType(ScaleType.FIT_START);
}
//
// Text upper left; audio upper right; video below audio on right.
// image below text, audio and video buttons; left-aligned with text.
textParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
textParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
if (mAudioButton != null && mVideoButton == null) {
audioParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
textParams.addRule(RelativeLayout.LEFT_OF, mAudioButton.getId());
} else if (mAudioButton == null && mVideoButton != null) {
videoParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
textParams.addRule(RelativeLayout.LEFT_OF, mVideoButton.getId());
} else if (mAudioButton != null && mVideoButton != null) {
audioParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
textParams.addRule(RelativeLayout.LEFT_OF, mAudioButton.getId());
videoParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
videoParams.addRule(RelativeLayout.BELOW, mAudioButton.getId());
} else {
textParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
}
if (mImageView != null || mMissingImage != null) {
imageParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
imageParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
imageParams.addRule(RelativeLayout.BELOW, mView_Text.getId());
} else {
textParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
}
}
addView(mView_Text, textParams);
if (mAudioButton != null)
addView(mAudioButton, audioParams);
if (mVideoButton != null)
addView(mVideoButton, videoParams);
if (mImageView != null)
addView(mImageView, imageParams);
else if (mMissingImage != null)
addView(mMissingImage, imageParams);
}
/**
* This adds a divider at the bottom of this layout. Used to separate fields in lists.
*
* @param v
*/
public void addDivider(ImageView v) {
RelativeLayout.LayoutParams dividerParams =
new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
if (mImageView != null) {
dividerParams.addRule(RelativeLayout.BELOW, mImageView.getId());
} else if (mMissingImage != null) {
dividerParams.addRule(RelativeLayout.BELOW, mMissingImage.getId());
} else if (mVideoButton != null) {
dividerParams.addRule(RelativeLayout.BELOW, mVideoButton.getId());
} else if (mAudioButton != null) {
dividerParams.addRule(RelativeLayout.BELOW, mAudioButton.getId());
} else if (mView_Text != null) {
// No picture
dividerParams.addRule(RelativeLayout.BELOW, mView_Text.getId());
} else {
Log.e(t, "Tried to add divider to uninitialized ATVWidget");
return;
}
addView(v, dividerParams);
}
@Override
protected void onWindowVisibilityChanged(int visibility) {
super.onWindowVisibilityChanged(visibility);
if (visibility != View.VISIBLE) {
if (mAudioButton != null) {
mAudioButton.stopPlaying();
}
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/views/MediaLayout.java
|
Java
|
asf20
| 16,629
|
package org.odk.collect.android.views;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.preference.ListPreference;
import android.util.AttributeSet;
public class DynamicListPreference extends ListPreference {
// control whether dialog should show or not
private boolean showDialog = false;
public DynamicListPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public DynamicListPreference(Context context) {
super(context);
}
public DynamicListPreference(Context context, boolean show) {
super(context);
showDialog = show;
}
// This is just to simulate that the user 'clicked' on the preference.
public void show() {
showDialog(null);
}
public boolean shouldShow() {
return showDialog;
}
@Override
protected void showDialog(Bundle state) {
if (showDialog) {
super.showDialog(state);
} else {
// we don't want the dialog to show sometimes
// like immediately after click, so we don't until we've generated
// the
// list choices
return;
}
}
public void setShowDialog(boolean show) {
showDialog = show;
}
@Override
public void onClick(DialogInterface dialog, int which) {
super.onClick(dialog, which);
// causes list to refresh next time dialog is requested
if (which == DialogInterface.BUTTON_NEGATIVE) {
setShowDialog(false);
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/views/DynamicListPreference.java
|
Java
|
asf20
| 1,408
|
/*
* Copyright (C) 2013 University of Washington
*
* http://creativecommons.org/licenses/by-sa/3.0/ -- code is based upon an answer on Stack Overflow:
* http://stackoverflow.com/questions/8481844/gridview-height-gets-cut
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.views;
import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.GridView;
/**
* From Stack Overflow: http://stackoverflow.com/questions/8481844/gridview-height-gets-cut
* Changed to always be expanded, since widgets are always embedded in a scroll view.
*
* @author tacone based on answer by Neil Traft
* @author mitchellsundt@gmail.com
*
*/
public class ExpandedHeightGridView extends GridView
{
public ExpandedHeightGridView(Context context)
{
super(context);
}
public ExpandedHeightGridView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public ExpandedHeightGridView(Context context, AttributeSet attrs,
int defStyle)
{
super(context, attrs, defStyle);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
// HACK! TAKE THAT ANDROID!
// Calculate entire height by providing a very large height hint.
// But do not use the highest 2 bits of this integer; those are
// reserved for the MeasureSpec mode.
int expandSpec = MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
}
}
|
0nima0-f
|
src/org/odk/collect/android/views/ExpandedHeightGridView.java
|
Java
|
asf20
| 2,302
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.views;
import org.odk.collect.android.R;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.CheckBox;
import android.widget.Checkable;
import android.widget.RelativeLayout;
public class TwoItemMultipleChoiceView extends RelativeLayout implements Checkable {
public TwoItemMultipleChoiceView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public TwoItemMultipleChoiceView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TwoItemMultipleChoiceView(Context context) {
super(context);
}
@Override
public boolean isChecked() {
CheckBox c = (CheckBox) findViewById(R.id.checkbox);
return c.isChecked();
}
@Override
public void setChecked(boolean checked) {
CheckBox c = (CheckBox) findViewById(R.id.checkbox);
c.setChecked(checked);
}
@Override
public void toggle() {
CheckBox c = (CheckBox) findViewById(R.id.checkbox);
c.setChecked(!c.isChecked());
}
}
|
0nima0-f
|
src/org/odk/collect/android/views/TwoItemMultipleChoiceView.java
|
Java
|
asf20
| 1,796
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.views;
import org.odk.collect.android.logic.HierarchyElement;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class HierarchyElementView extends RelativeLayout {
private TextView mPrimaryTextView;
private TextView mSecondaryTextView;
private ImageView mIcon;
public HierarchyElementView(Context context, HierarchyElement it) {
super(context);
setColor(it.getColor());
mIcon = new ImageView(context);
mIcon.setImageDrawable(it.getIcon());
mIcon.setId(1);
mIcon.setPadding(0, 0, dipToPx(4), 0);
addView(mIcon, new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
mPrimaryTextView = new TextView(context);
mPrimaryTextView.setTextAppearance(context, android.R.style.TextAppearance_Large);
mPrimaryTextView.setText(it.getPrimaryText());
mPrimaryTextView.setId(2);
mPrimaryTextView.setGravity(Gravity.CENTER_VERTICAL);
LayoutParams l =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
l.addRule(RelativeLayout.RIGHT_OF, mIcon.getId());
addView(mPrimaryTextView, l);
mSecondaryTextView = new TextView(context);
mSecondaryTextView.setText(it.getSecondaryText());
mSecondaryTextView.setTextAppearance(context, android.R.style.TextAppearance_Small);
mSecondaryTextView.setGravity(Gravity.CENTER_VERTICAL);
LayoutParams lp =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.BELOW, mPrimaryTextView.getId());
lp.addRule(RelativeLayout.RIGHT_OF, mIcon.getId());
addView(mSecondaryTextView, lp);
setPadding(dipToPx(8), dipToPx(4), dipToPx(8), dipToPx(8));
}
public void setPrimaryText(String text) {
mPrimaryTextView.setText(text);
}
public void setSecondaryText(String text) {
mSecondaryTextView.setText(text);
}
public void setIcon(Drawable icon) {
mIcon.setImageDrawable(icon);
}
public void setColor(int color) {
setBackgroundColor(color);
}
public void showSecondary(boolean bool) {
if (bool) {
mSecondaryTextView.setVisibility(VISIBLE);
setMinimumHeight(dipToPx(64));
} else {
mSecondaryTextView.setVisibility(GONE);
setMinimumHeight(dipToPx(32));
}
}
public int dipToPx(int dip) {
return (int) (dip * getResources().getDisplayMetrics().density + 0.5f);
}
}
|
0nima0-f
|
src/org/odk/collect/android/views/HierarchyElementView.java
|
Java
|
asf20
| 3,436
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.views;
import org.odk.collect.android.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
/**
* Builds view for arrow animation
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class ArrowAnimationView extends View {
private final static String t = "ArrowAnimationView";
private Animation mAnimation;
private Bitmap mArrow;
private int mImgXOffset;
public ArrowAnimationView(Context context, AttributeSet attrs) {
super(context, attrs);
Log.i(t, "called constructor");
init();
}
public ArrowAnimationView(Context context) {
super(context);
init();
}
private void init() {
mArrow = BitmapFactory.decodeResource(getResources(), R.drawable.left_arrow);
mImgXOffset = mArrow.getWidth() / 2;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mAnimation == null) {
createAnim(canvas);
}
int centerX = canvas.getWidth() / 2;
canvas.drawBitmap(mArrow, centerX - mImgXOffset, (float) mArrow.getHeight() / 4, null);
}
private void createAnim(Canvas canvas) {
mAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.start_arrow);
startAnimation(mAnimation);
}
}
|
0nima0-f
|
src/org/odk/collect/android/views/ArrowAnimationView.java
|
Java
|
asf20
| 2,199
|
/*
* Copyright (C) 2014 University of Washington
*
* Originally developed by Dobility, Inc. (as part of SurveyCTO)
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.utilities;
import android.util.Log;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* Author: Meletis Margaritis
* Date: 2/12/14
* Time: 1:48 PM
*/
public final class ZipUtils {
final static String t = "ZipUtils";
public static void unzip(File[] zipFiles) {
for (File zipFile : zipFiles) {
ZipInputStream zipInputStream = null;
try {
zipInputStream = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
doExtractInTheSameFolder(zipFile, zipInputStream, zipEntry);
}
} catch (Exception e) {
Log.e(t, e.getMessage(), e);
} finally {
IOUtils.closeQuietly(zipInputStream);
}
}
}
public static File extractFirstZipEntry(File zipFile, boolean deleteAfterUnzip) throws IOException {
ZipInputStream zipInputStream = null;
File targetFile = null;
try {
zipInputStream = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry zipEntry = zipInputStream.getNextEntry();
if (zipEntry != null) {
targetFile = doExtractInTheSameFolder(zipFile, zipInputStream, zipEntry);
}
} finally {
IOUtils.closeQuietly(zipInputStream);
}
if (deleteAfterUnzip && targetFile != null && targetFile.exists()) {
FileUtils.deleteAndReport(zipFile);
}
return targetFile;
}
private static File doExtractInTheSameFolder(File zipFile, ZipInputStream zipInputStream, ZipEntry zipEntry) throws IOException {
File targetFile;
String fileName = zipEntry.getName();
Log.w(t, "Found zipEntry with name: " + fileName);
if (fileName.contains("/") || fileName.contains("\\")) {
// that means that this is a directory of a file inside a directory, so ignore it
Log.w(t, "Ignored: " + fileName);
return null;
}
// extract the new file
targetFile = new File(zipFile.getParentFile(), fileName);
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(targetFile);
IOUtils.copy(zipInputStream, fileOutputStream);
} finally {
IOUtils.closeQuietly(fileOutputStream);
}
Log.w(t, "Extracted file \"" + fileName + "\" out of " + zipFile.getName());
return targetFile;
}
}
|
0nima0-f
|
src/org/odk/collect/android/utilities/ZipUtils.java
|
Java
|
asf20
| 3,479
|
/*
* Copyright (C) 2012 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.utilities;
import org.odk.collect.android.R;
import android.content.Context;
import android.database.Cursor;
import android.view.View;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
/**
* Implementation of cursor adapter that displays the version of a form if a form has a version.
*
* @author mitchellsundt@gmail.com
*
*/
public class VersionHidingCursorAdapter extends SimpleCursorAdapter {
private final Context ctxt;
private final String versionColumnName;
private final ViewBinder originalBinder;
public VersionHidingCursorAdapter(String versionColumnName, Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
this.versionColumnName = versionColumnName;
ctxt = context;
originalBinder = getViewBinder();
setViewBinder( new ViewBinder(){
@Override
public boolean setViewValue(View view, Cursor cursor,
int columnIndex) {
String columnName = cursor.getColumnName(columnIndex);
if ( !columnName.equals(VersionHidingCursorAdapter.this.versionColumnName) ) {
if ( originalBinder != null ) {
return originalBinder.setViewValue(view, cursor, columnIndex);
}
return false;
} else {
String version = cursor.getString(columnIndex);
TextView v = (TextView) view;
if ( version != null ) {
v.setText(ctxt.getString(R.string.version) + " " + version);
v.setVisibility(View.VISIBLE);
} else {
v.setText(null);
v.setVisibility(View.GONE);
}
}
return true;
}} );
}
}
|
0nima0-f
|
src/org/odk/collect/android/utilities/VersionHidingCursorAdapter.java
|
Java
|
asf20
| 2,272
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.utilities;
import org.apache.commons.io.IOUtils;
import org.javarosa.xform.parse.XFormParser;
import org.kxml2.kdom.Document;
import org.kxml2.kdom.Element;
import org.kxml2.kdom.Node;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
/**
* Static methods used for common file operations.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class FileUtils {
private final static String t = "FileUtils";
// Used to validate and display valid form names.
public static final String VALID_FILENAME = "[ _\\-A-Za-z0-9]*.x[ht]*ml";
public static final String FORMID = "formid";
public static final String VERSION = "version"; // arbitrary string in OpenRosa 1.0
public static final String TITLE = "title";
public static final String SUBMISSIONURI = "submission";
public static final String BASE64_RSA_PUBLIC_KEY = "base64RsaPublicKey";
public static boolean createFolder(String path) {
boolean made = true;
File dir = new File(path);
if (!dir.exists()) {
made = dir.mkdirs();
}
return made;
}
public static byte[] getFileAsBytes(File file) {
byte[] bytes = null;
InputStream is = null;
try {
is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
Log.e(t, "File " + file.getName() + "is too large");
return null;
}
// Create the byte array to hold the data
bytes = new byte[(int) length];
// Read in the bytes
int offset = 0;
int read = 0;
try {
while (offset < bytes.length && read >= 0) {
read = is.read(bytes, offset, bytes.length - offset);
offset += read;
}
} catch (IOException e) {
Log.e(t, "Cannot read " + file.getName());
e.printStackTrace();
return null;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
try {
throw new IOException("Could not completely read file " + file.getName());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return bytes;
} catch (FileNotFoundException e) {
Log.e(t, "Cannot find " + file.getName());
e.printStackTrace();
return null;
} finally {
// Close the input stream
try {
is.close();
} catch (IOException e) {
Log.e(t, "Cannot close input stream for " + file.getName());
e.printStackTrace();
return null;
}
}
}
public static String getMd5Hash(File file) {
try {
// CTS (6/15/2010) : stream file through digest instead of handing it the byte[]
MessageDigest md = MessageDigest.getInstance("MD5");
int chunkSize = 256;
byte[] chunk = new byte[chunkSize];
// Get the size of the file
long lLength = file.length();
if (lLength > Integer.MAX_VALUE) {
Log.e(t, "File " + file.getName() + "is too large");
return null;
}
int length = (int) lLength;
InputStream is = null;
is = new FileInputStream(file);
int l = 0;
for (l = 0; l + chunkSize < length; l += chunkSize) {
is.read(chunk, 0, chunkSize);
md.update(chunk, 0, chunkSize);
}
int remaining = length - l;
if (remaining > 0) {
is.read(chunk, 0, remaining);
md.update(chunk, 0, remaining);
}
byte[] messageDigest = md.digest();
BigInteger number = new BigInteger(1, messageDigest);
String md5 = number.toString(16);
while (md5.length() < 32)
md5 = "0" + md5;
is.close();
return md5;
} catch (NoSuchAlgorithmException e) {
Log.e("MD5", e.getMessage());
return null;
} catch (FileNotFoundException e) {
Log.e("No Cache File", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Problem reading from file", e.getMessage());
return null;
}
}
public static Bitmap getBitmapScaledToDisplay(File f, int screenHeight, int screenWidth) {
// Determine image size of f
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(f.getAbsolutePath(), o);
int heightScale = o.outHeight / screenHeight;
int widthScale = o.outWidth / screenWidth;
// Powers of 2 work faster, sometimes, according to the doc.
// We're just doing closest size that still fills the screen.
int scale = Math.max(widthScale, heightScale);
// get bitmap with scale ( < 1 is the same as 1)
BitmapFactory.Options options = new BitmapFactory.Options();
options.inInputShareable = true;
options.inPurgeable = true;
options.inSampleSize = scale;
Bitmap b = BitmapFactory.decodeFile(f.getAbsolutePath(), options);
if (b != null) {
Log.i(t,
"Screen is " + screenHeight + "x" + screenWidth + ". Image has been scaled down by "
+ scale + " to " + b.getHeight() + "x" + b.getWidth());
}
return b;
}
public static String copyFile(File sourceFile, File destFile) {
if (sourceFile.exists()) {
String errorMessage = actualCopy(sourceFile, destFile);
if (errorMessage != null) {
try {
Thread.sleep(500);
Log.e(t, "Retrying to copy the file after 500ms: " + sourceFile.getAbsolutePath());
errorMessage = actualCopy(sourceFile, destFile);
} catch (InterruptedException e) {
Log.e(t, e.getMessage(), e);
}
}
return errorMessage;
} else {
String msg = "Source file does not exist: " + sourceFile.getAbsolutePath();
Log.e(t, msg);
return msg;
}
}
private static String actualCopy(File sourceFile, File destFile) {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
FileChannel src = null;
FileChannel dst = null;
try {
fileInputStream = new FileInputStream(sourceFile);
src = fileInputStream.getChannel();
fileOutputStream = new FileOutputStream(destFile);
dst = fileOutputStream.getChannel();
dst.transferFrom(src, 0, src.size());
dst.force(true);
return null;
} catch (FileNotFoundException e) {
Log.e(t, "FileNotFoundException while copying file", e);
return e.getMessage();
} catch (IOException e) {
Log.e(t, "IOException while copying file", e);
return e.getMessage();
} catch (Exception e) {
Log.e(t, "Exception while copying file", e);
return e.getMessage();
} finally {
IOUtils.closeQuietly(fileInputStream);
IOUtils.closeQuietly(fileOutputStream);
IOUtils.closeQuietly(src);
IOUtils.closeQuietly(dst);
}
}
public static HashMap<String, String> parseXML(File xmlFile) {
HashMap<String, String> fields = new HashMap<String, String>();
InputStream is;
try {
is = new FileInputStream(xmlFile);
} catch (FileNotFoundException e1) {
throw new IllegalStateException(e1);
}
InputStreamReader isr;
try {
isr = new InputStreamReader(is, "UTF-8");
} catch (UnsupportedEncodingException uee) {
Log.w(t, "UTF 8 encoding unavailable, trying default encoding");
isr = new InputStreamReader(is);
}
if (isr != null) {
Document doc;
try {
doc = XFormParser.getXMLDocument(isr);
} catch (IOException e) {
e.printStackTrace();
throw new IllegalStateException("Unable to parse XML document", e);
} finally {
try {
isr.close();
} catch (IOException e) {
Log.w(t, xmlFile.getAbsolutePath() + " Error closing form reader");
e.printStackTrace();
}
}
String xforms = "http://www.w3.org/2002/xforms";
String html = doc.getRootElement().getNamespace();
Element head = doc.getRootElement().getElement(html, "head");
Element title = head.getElement(html, "title");
if (title != null) {
fields.put(TITLE, XFormParser.getXMLText(title, true));
}
Element model = getChildElement(head, "model");
Element cur = getChildElement(model,"instance");
int idx = cur.getChildCount();
int i;
for (i = 0; i < idx; ++i) {
if (cur.isText(i))
continue;
if (cur.getType(i) == Node.ELEMENT) {
break;
}
}
if (i < idx) {
cur = cur.getElement(i); // this is the first data element
String id = cur.getAttributeValue(null, "id");
String xmlns = cur.getNamespace();
String version = cur.getAttributeValue(null, "version");
String uiVersion = cur.getAttributeValue(null, "uiVersion");
if ( uiVersion != null ) {
// pre-OpenRosa 1.0 variant of spec
Log.e(t, "Obsolete use of uiVersion -- IGNORED -- only using version: " + version);
}
fields.put(FORMID, (id == null) ? xmlns : id);
fields.put(VERSION, (version == null) ? null : version);
} else {
throw new IllegalStateException(xmlFile.getAbsolutePath() + " could not be parsed");
}
try {
Element submission = model.getElement(xforms, "submission");
String submissionUri = submission.getAttributeValue(null, "action");
fields.put(SUBMISSIONURI, (submissionUri == null) ? null : submissionUri);
String base64RsaPublicKey = submission.getAttributeValue(null, "base64RsaPublicKey");
fields.put(BASE64_RSA_PUBLIC_KEY,
(base64RsaPublicKey == null || base64RsaPublicKey.trim().length() == 0)
? null : base64RsaPublicKey.trim());
} catch (Exception e) {
Log.i(t, xmlFile.getAbsolutePath() + " does not have a submission element");
// and that's totally fine.
}
}
return fields;
}
// needed because element.getelement fails when there are attributes
private static Element getChildElement(Element parent, String childName) {
Element e = null;
int c = parent.getChildCount();
int i = 0;
for (i = 0; i < c; i++) {
if (parent.getType(i) == Node.ELEMENT) {
if (parent.getElement(i).getName().equalsIgnoreCase(childName)) {
return parent.getElement(i);
}
}
}
return e;
}
public static void deleteAndReport(File file) {
if (file != null && file.exists()) {
// remove garbage
if (!file.delete()) {
Log.w(t, file.getAbsolutePath() + " will be deleted upon exit.");
file.deleteOnExit();
} else {
Log.w(t, file.getAbsolutePath() + " has been deleted.");
}
}
}
public static String constructMediaPath(String formFilePath) {
String pathNoExtension = formFilePath.substring(0, formFilePath.lastIndexOf("."));
return pathNoExtension + "-media";
}
/**
* @param mediaDir the media folder
*/
public static void checkMediaPath(File mediaDir) {
if (mediaDir.exists() && mediaDir.isFile()) {
Log.e(t, "The media folder is already there and it is a FILE!! We will need to delete it and create a folder instead");
boolean deleted = mediaDir.delete();
if (!deleted) {
throw new RuntimeException(Collect.getInstance().getString(R.string.fs_delete_media_path_if_file_error, mediaDir.getAbsolutePath()));
}
}
// the directory case
boolean createdOrExisted = createFolder(mediaDir.getAbsolutePath());
if (!createdOrExisted) {
throw new RuntimeException(Collect.getInstance().getString(R.string.fs_create_media_folder_error, mediaDir.getAbsolutePath()));
}
}
public static void purgeMediaPath(String mediaPath) {
File tempMediaFolder = new File(mediaPath);
File[] tempMediaFiles = tempMediaFolder.listFiles();
if (tempMediaFiles == null || tempMediaFiles.length == 0) {
deleteAndReport(tempMediaFolder);
} else {
for (File tempMediaFile : tempMediaFiles) {
deleteAndReport(tempMediaFile);
}
}
}
public static void moveMediaFiles(String tempMediaPath, File formMediaPath) throws IOException {
File tempMediaFolder = new File(tempMediaPath);
File[] mediaFiles = tempMediaFolder.listFiles();
if (mediaFiles == null || mediaFiles.length == 0) {
deleteAndReport(tempMediaFolder);
} else {
for (File mediaFile : mediaFiles) {
org.apache.commons.io.FileUtils.moveFileToDirectory(mediaFile, formMediaPath, true);
}
deleteAndReport(tempMediaFolder);
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/utilities/FileUtils.java
|
Java
|
asf20
| 15,556
|
/*
* Copyright (C) 2011 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.utilities;
import java.io.*;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.List;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.io.IOUtils;
import org.kxml2.io.KXmlSerializer;
import org.kxml2.kdom.Document;
import org.kxml2.kdom.Element;
import org.kxml2.kdom.Node;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.exception.EncryptionException;
import org.odk.collect.android.logic.FormController.InstanceMetadata;
import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
/**
* Utility class for encrypting submissions during the SaveToDiskTask.
*
* @author mitchellsundt@gmail.com
*
*/
public class EncryptionUtils {
private static final String t = "EncryptionUtils";
public static final String RSA_ALGORITHM = "RSA";
// the symmetric key we are encrypting with RSA is only 256 bits... use SHA-256
public static final String ASYMMETRIC_ALGORITHM = "RSA/NONE/OAEPWithSHA256AndMGF1Padding";
public static final String SYMMETRIC_ALGORITHM = "AES/CFB/PKCS5Padding";
public static final String UTF_8 = "UTF-8";
public static final int SYMMETRIC_KEY_LENGTH = 256;
public static final int IV_BYTE_LENGTH = 16;
// tags in the submission manifest
private static final String XML_ENCRYPTED_TAG_NAMESPACE = "http://www.opendatakit.org/xforms/encrypted";
private static final String XML_OPENROSA_NAMESPACE = "http://openrosa.org/xforms";
private static final String DATA = "data";
private static final String ID = "id";
private static final String VERSION = "version";
private static final String ENCRYPTED = "encrypted";
private static final String BASE64_ENCRYPTED_KEY = "base64EncryptedKey";
private static final String ENCRYPTED_XML_FILE = "encryptedXmlFile";
private static final String META = "meta";
private static final String INSTANCE_ID = "instanceID";
private static final String MEDIA = "media";
private static final String FILE = "file";
private static final String BASE64_ENCRYPTED_ELEMENT_SIGNATURE = "base64EncryptedElementSignature";
private static final String NEW_LINE = "\n";
private static final String ENCRYPTION_PROVIDER = "BC";
private EncryptionUtils() {
}
public static final class EncryptedFormInformation {
public final String formId;
public final String formVersion;
public final InstanceMetadata instanceMetadata;
public final PublicKey rsaPublicKey;
public final String base64RsaEncryptedSymmetricKey;
public final SecretKeySpec symmetricKey;
public final byte[] ivSeedArray;
private int ivCounter = 0;
public final StringBuilder elementSignatureSource = new StringBuilder();
public final Base64Wrapper wrapper;
private boolean isNotBouncyCastle = false;
EncryptedFormInformation(String formId, String formVersion,
InstanceMetadata instanceMetadata, PublicKey rsaPublicKey, Base64Wrapper wrapper) {
this.formId = formId;
this.formVersion = formVersion;
this.instanceMetadata = instanceMetadata;
this.rsaPublicKey = rsaPublicKey;
this.wrapper = wrapper;
// generate the symmetric key from random bits...
SecureRandom r = new SecureRandom();
byte[] key = new byte[SYMMETRIC_KEY_LENGTH/8];
r.nextBytes(key);
SecretKeySpec sk = new SecretKeySpec(key, SYMMETRIC_ALGORITHM);
symmetricKey = sk;
// construct the fixed portion of the iv -- the ivSeedArray
// this is the md5 hash of the instanceID and the symmetric key
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(instanceMetadata.instanceId.getBytes(UTF_8));
md.update(key);
byte[] messageDigest = md.digest();
ivSeedArray = new byte[IV_BYTE_LENGTH];
for ( int i = 0 ; i < IV_BYTE_LENGTH ; ++i ) {
ivSeedArray[i] = messageDigest[(i % messageDigest.length)];
}
} catch (NoSuchAlgorithmException e) {
Log.e(t, e.toString());
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (UnsupportedEncodingException e) {
Log.e(t, e.toString());
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
}
// construct the base64-encoded RSA-encrypted symmetric key
try {
Cipher pkCipher;
pkCipher = Cipher.getInstance(ASYMMETRIC_ALGORITHM);
// write AES key
pkCipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);
byte[] pkEncryptedKey = pkCipher.doFinal(key);
String alg = pkCipher.getAlgorithm();
Log.i(t, "AlgorithmUsed: " + alg);
base64RsaEncryptedSymmetricKey = wrapper
.encodeToString(pkEncryptedKey);
} catch (NoSuchAlgorithmException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (NoSuchPaddingException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (InvalidKeyException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (IllegalBlockSizeException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (BadPaddingException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
}
// start building elementSignatureSource...
appendElementSignatureSource(formId);
if ( formVersion != null ) {
appendElementSignatureSource(formVersion.toString());
}
appendElementSignatureSource(base64RsaEncryptedSymmetricKey);
appendElementSignatureSource( instanceMetadata.instanceId );
}
public void appendElementSignatureSource(String value) {
elementSignatureSource.append(value).append("\n");
}
public void appendFileSignatureSource(File file) {
String md5Hash = FileUtils.getMd5Hash(file);
appendElementSignatureSource(file.getName()+"::"+md5Hash);
}
public String getBase64EncryptedElementSignature() {
// Step 0: construct the text of the elements in elementSignatureSource (done)
// Where...
// * Elements are separated by newline characters.
// * Filename is the unencrypted filename (no .enc suffix).
// * Md5 hashes of the unencrypted files' contents are converted
// to zero-padded 32-character strings before concatenation.
// Assumes this is in the order:
// formId
// version (omitted if null)
// base64RsaEncryptedSymmetricKey
// instanceId
// for each media file { filename "::" md5Hash }
// submission.xml "::" md5Hash
// Step 1: construct the (raw) md5 hash of Step 0.
byte[] messageDigest;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(elementSignatureSource.toString().getBytes(UTF_8));
messageDigest = md.digest();
} catch (NoSuchAlgorithmException e) {
Log.e(t, e.toString());
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (UnsupportedEncodingException e) {
Log.e(t, e.toString());
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
}
// Step 2: construct the base64-encoded RSA-encrypted md5
try {
Cipher pkCipher;
pkCipher = Cipher.getInstance(ASYMMETRIC_ALGORITHM);
// write AES key
pkCipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);
byte[] pkEncryptedKey = pkCipher.doFinal(messageDigest);
return wrapper.encodeToString(pkEncryptedKey);
} catch (NoSuchAlgorithmException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (NoSuchPaddingException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (InvalidKeyException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (IllegalBlockSizeException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (BadPaddingException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
}
}
public Cipher getCipher() throws InvalidKeyException,
InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException {
++ivSeedArray[ivCounter % ivSeedArray.length];
++ivCounter;
IvParameterSpec baseIv = new IvParameterSpec(ivSeedArray);
Cipher c = null;
try {
c = Cipher.getInstance(EncryptionUtils.SYMMETRIC_ALGORITHM, "BC");
isNotBouncyCastle = false;
} catch (NoSuchProviderException e) {
Log.w(t, "Unable to obtain BouncyCastle provider! Decryption may fail!");
e.printStackTrace();
isNotBouncyCastle = true;
c = Cipher.getInstance(EncryptionUtils.SYMMETRIC_ALGORITHM);
}
c.init(Cipher.ENCRYPT_MODE, symmetricKey, baseIv);
return c;
}
public boolean isNotBouncyCastle() {
return isNotBouncyCastle;
}
}
/**
* Retrieve the encryption information for this uri.
*
* @param mUri either an instance URI (if previously saved) or a form URI
* @param instanceMetadata
* @return
*/
public static EncryptedFormInformation getEncryptedFormInformation(Uri mUri, InstanceMetadata instanceMetadata) {
ContentResolver cr = Collect.getInstance().getContentResolver();
// fetch the form information
String formId;
String formVersion;
PublicKey pk;
Base64Wrapper wrapper;
Cursor formCursor = null;
try {
if (cr.getType(mUri) == InstanceColumns.CONTENT_ITEM_TYPE) {
// chain back to the Form record...
String[] selectionArgs = null;
String selection = null;
Cursor instanceCursor = null;
try {
instanceCursor = cr.query(mUri, null, null, null, null);
if ( instanceCursor.getCount() != 1 ) {
Log.e(t, "Not exactly one record for this instance!");
return null; // save unencrypted.
}
instanceCursor.moveToFirst();
String jrFormId = instanceCursor.getString(instanceCursor.getColumnIndex(InstanceColumns.JR_FORM_ID));
int idxJrVersion = instanceCursor.getColumnIndex(InstanceColumns.JR_VERSION);
if ( !instanceCursor.isNull(idxJrVersion) ) {
selectionArgs = new String[] {jrFormId, instanceCursor.getString(idxJrVersion)};
selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + "=?";
} else {
selectionArgs = new String[] {jrFormId};
selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + " IS NULL";
}
} finally {
if ( instanceCursor != null ) {
instanceCursor.close();
}
}
formCursor = cr.query(FormsColumns.CONTENT_URI, null, selection, selectionArgs,
null);
if (formCursor.getCount() != 1) {
Log.e(t, "Not exactly one blank form matches this jr_form_id");
return null; // save unencrypted
}
formCursor.moveToFirst();
} else if (cr.getType(mUri) == FormsColumns.CONTENT_ITEM_TYPE) {
formCursor = cr.query(mUri, null, null, null, null);
if ( formCursor.getCount() != 1 ) {
Log.e(t, "Not exactly one blank form!");
return null; // save unencrypted.
}
formCursor.moveToFirst();
}
formId = formCursor.getString(formCursor.getColumnIndex(FormsColumns.JR_FORM_ID));
if (formId == null || formId.length() == 0) {
Log.e(t, "No FormId specified???");
return null;
}
int idxVersion = formCursor.getColumnIndex(FormsColumns.JR_VERSION);
int idxBase64RsaPublicKey = formCursor.getColumnIndex(FormsColumns.BASE64_RSA_PUBLIC_KEY);
formVersion = formCursor.isNull(idxVersion) ? null : formCursor.getString(idxVersion);
String base64RsaPublicKey = formCursor.isNull(idxBase64RsaPublicKey)
? null : formCursor.getString(idxBase64RsaPublicKey);
if (base64RsaPublicKey == null || base64RsaPublicKey.length() == 0) {
return null; // this is legitimately not an encrypted form
}
int version = android.os.Build.VERSION.SDK_INT;
if (version < 8) {
Log.e(t, "Phone does not support encryption.");
return null; // save unencrypted
}
// this constructor will throw an exception if we are not
// running on version 8 or above (if Base64 is not found).
try {
wrapper = new Base64Wrapper();
} catch (ClassNotFoundException e) {
Log.e(t, "Phone does not have Base64 class but API level is "
+ version);
e.printStackTrace();
return null; // save unencrypted
}
// OK -- Base64 decode (requires API Version 8 or higher)
byte[] publicKey = wrapper.decode(base64RsaPublicKey);
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKey);
KeyFactory kf;
try {
kf = KeyFactory.getInstance(RSA_ALGORITHM);
} catch (NoSuchAlgorithmException e) {
Log.e(t, "Phone does not support RSA encryption.");
e.printStackTrace();
return null;
}
try {
pk = kf.generatePublic(publicKeySpec);
} catch (InvalidKeySpecException e) {
e.printStackTrace();
Log.e(t, "Invalid RSA public key.");
return null;
}
} finally {
if (formCursor != null) {
formCursor.close();
}
}
// submission must have an OpenRosa metadata block with a non-null
// instanceID value.
if (instanceMetadata.instanceId == null) {
Log.e(t, "No OpenRosa metadata block or no instanceId defined in that block");
return null;
}
// For now, prevent encryption if the BouncyCastle implementation is not present.
// https://code.google.com/p/opendatakit/issues/detail?id=918
try {
Cipher.getInstance(EncryptionUtils.SYMMETRIC_ALGORITHM, ENCRYPTION_PROVIDER);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
Log.e(t, "No BouncyCastle implementation of symmetric algorithm!");
return null;
} catch (NoSuchProviderException e) {
e.printStackTrace();
Log.e(t, "No BouncyCastle provider for implementation of symmetric algorithm!");
return null;
} catch (NoSuchPaddingException e) {
e.printStackTrace();
Log.e(t, "No BouncyCastle provider for padding implementation of symmetric algorithm!");
return null;
}
return new EncryptedFormInformation(formId, formVersion, instanceMetadata,
pk, wrapper);
}
private static void encryptFile(File file, EncryptedFormInformation formInfo)
throws IOException, EncryptionException {
File encryptedFile = new File(file.getParentFile(), file.getName()
+ ".enc");
if (encryptedFile.exists() && !encryptedFile.delete()) {
throw new IOException("Cannot overwrite " + encryptedFile.getAbsolutePath() + ". Perhaps the file is locked?");
}
// add elementSignatureSource for this file...
formInfo.appendFileSignatureSource(file);
RandomAccessFile randomAccessFile = null;
CipherOutputStream cipherOutputStream = null;
try {
Cipher c = formInfo.getCipher();
randomAccessFile = new RandomAccessFile(encryptedFile, "rws");
ByteArrayOutputStream encryptedData = new ByteArrayOutputStream();
cipherOutputStream = new CipherOutputStream(encryptedData, c);
InputStream fin = new FileInputStream(file);
byte[] buffer = new byte[2048];
int len = fin.read(buffer);
while (len != -1) {
cipherOutputStream.write(buffer, 0, len);
len = fin.read(buffer);
}
fin.close();
cipherOutputStream.flush();
cipherOutputStream.close();
randomAccessFile.write(encryptedData.toByteArray());
Log.i(t,
"Encrpyted:" + file.getName() + " -> "
+ encryptedFile.getName());
} catch (Exception e) {
String msg = "Error encrypting: " + file.getName() + " -> "
+ encryptedFile.getName();
Log.e(t, msg, e);
e.printStackTrace();
throw new EncryptionException(msg, e);
} finally {
IOUtils.closeQuietly(cipherOutputStream);
if (randomAccessFile != null) {
randomAccessFile.close();
}
}
}
public static boolean deletePlaintextFiles(File instanceXml) {
// NOTE: assume the directory containing the instanceXml contains ONLY
// files related to this one instance.
File instanceDir = instanceXml.getParentFile();
boolean allSuccessful = true;
// encrypt files that do not end with ".enc", and do not start with ".";
// ignore directories
File[] allFiles = instanceDir.listFiles();
for (File f : allFiles) {
if (f.equals(instanceXml))
continue; // don't touch instance file
if (f.isDirectory())
continue; // don't handle directories
if (!f.getName().endsWith(".enc")) {
// not an encrypted file -- delete it!
allSuccessful = allSuccessful & f.delete(); // DO NOT
// short-circuit
}
}
return allSuccessful;
}
private static List<File> encryptSubmissionFiles(File instanceXml,
File submissionXml, EncryptedFormInformation formInfo) throws IOException, EncryptionException {
// NOTE: assume the directory containing the instanceXml contains ONLY
// files related to this one instance.
File instanceDir = instanceXml.getParentFile();
// encrypt files that do not end with ".enc", and do not start with ".";
// ignore directories
File[] allFiles = instanceDir.listFiles();
List<File> filesToProcess = new ArrayList<File>();
for (File f : allFiles) {
if (f.equals(instanceXml))
continue; // don't touch restore file
if (f.equals(submissionXml))
continue; // handled last
if (f.isDirectory())
continue; // don't handle directories
if (f.getName().startsWith("."))
continue; // MacOSX garbage
if (f.getName().endsWith(".enc")) {
f.delete(); // try to delete this (leftover junk)
} else {
filesToProcess.add(f);
}
}
// encrypt here...
for (File f : filesToProcess) {
encryptFile(f, formInfo);
}
// encrypt the submission.xml as the last file...
encryptFile(submissionXml, formInfo);
return filesToProcess;
}
/**
* Constructs the encrypted attachments, encrypted form xml, and the
* plaintext submission manifest (with signature) for the form submission.
*
* Does not delete any of the original files.
*
* @param instanceXml
* @param submissionXml
* @param formInfo
* @return
*/
public static void generateEncryptedSubmission(File instanceXml,
File submissionXml, EncryptedFormInformation formInfo) throws IOException, EncryptionException {
// submissionXml is the submission data to be published to Aggregate
if (!submissionXml.exists() || !submissionXml.isFile()) {
throw new IOException("No submission.xml found");
}
// TODO: confirm that this xml is not already encrypted...
// Step 1: encrypt the submission and all the media files...
List<File> mediaFiles = encryptSubmissionFiles(instanceXml,
submissionXml, formInfo);
// Step 2: build the encrypted-submission manifest (overwrites
// submission.xml)...
writeSubmissionManifest(formInfo, submissionXml, mediaFiles);
}
private static void writeSubmissionManifest(
EncryptedFormInformation formInfo,
File submissionXml, List<File> mediaFiles) throws EncryptionException {
Document d = new Document();
d.setStandalone(true);
d.setEncoding(UTF_8);
Element e = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, DATA);
e.setPrefix(null, XML_ENCRYPTED_TAG_NAMESPACE);
e.setAttribute(null, ID, formInfo.formId);
if ( formInfo.formVersion != null ) {
e.setAttribute(null, VERSION, formInfo.formVersion);
}
e.setAttribute(null, ENCRYPTED, "yes");
d.addChild(0, Node.ELEMENT, e);
int idx = 0;
Element c;
c = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, BASE64_ENCRYPTED_KEY);
c.addChild(0, Node.TEXT, formInfo.base64RsaEncryptedSymmetricKey);
e.addChild(idx++, Node.ELEMENT, c);
c = d.createElement(XML_OPENROSA_NAMESPACE, META);
c.setPrefix("orx", XML_OPENROSA_NAMESPACE);
{
Element instanceTag = d.createElement(XML_OPENROSA_NAMESPACE, INSTANCE_ID);
instanceTag.addChild(0, Node.TEXT, formInfo.instanceMetadata.instanceId);
c.addChild(0, Node.ELEMENT, instanceTag);
}
e.addChild(idx++, Node.ELEMENT, c);
e.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);
if (mediaFiles != null) {
for (File file : mediaFiles) {
c = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, MEDIA);
Element fileTag = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, FILE);
fileTag.addChild(0, Node.TEXT, file.getName() + ".enc");
c.addChild(0, Node.ELEMENT, fileTag);
e.addChild(idx++, Node.ELEMENT, c);
e.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);
}
}
c = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, ENCRYPTED_XML_FILE);
c.addChild(0, Node.TEXT, submissionXml.getName() + ".enc");
e.addChild(idx++, Node.ELEMENT, c);
c = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, BASE64_ENCRYPTED_ELEMENT_SIGNATURE);
c.addChild(0, Node.TEXT, formInfo.getBase64EncryptedElementSignature());
e.addChild(idx++, Node.ELEMENT, c);
FileOutputStream fout = null;
OutputStreamWriter writer = null;
try {
fout = new FileOutputStream(submissionXml);
writer = new OutputStreamWriter(fout, UTF_8);
KXmlSerializer serializer = new KXmlSerializer();
serializer.setOutput(writer);
// setting the response content type emits the xml header.
// just write the body here...
d.writeChildren(serializer);
serializer.flush();
writer.flush();
fout.getChannel().force(true);
writer.close();
} catch (Exception ex) {
ex.printStackTrace();
String msg = "Error writing submission.xml for encrypted submission: "
+ submissionXml.getParentFile().getName();
Log.e(t, msg);
throw new EncryptionException(msg, ex);
} finally {
IOUtils.closeQuietly(writer);
IOUtils.closeQuietly(fout);
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/utilities/EncryptionUtils.java
|
Java
|
asf20
| 24,660
|
/*
* Copyright (C) 2012 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.utilities;
import org.odk.collect.android.R;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.HorizontalScrollView;
import android.widget.ScrollView;
/**
* Based heavily upon:
* http://www.yougli.net/android/a-photoshop-like-color-picker
* -for-your-android-application/
*
* @author BehrAtherton@gmail.com
* @author yougli@yougli.net
*
*/
public class ColorPickerDialog extends Dialog {
public interface OnColorChangedListener {
void colorChanged(String key, int color);
}
private OnColorChangedListener mListener;
private int mInitialColor, mDefaultColor;
private String mKey;
/**
* Modified HorizontalScrollView that communicates scroll
* actions to interior Vertical scroll view.
* From: http://stackoverflow.com/questions/3866499/two-directional-scroll-view
*
*/
public class WScrollView extends HorizontalScrollView
{
public ScrollView sv;
public WScrollView(Context context)
{
super(context);
}
public WScrollView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public WScrollView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
@Override public boolean onTouchEvent(MotionEvent event)
{
boolean ret = super.onTouchEvent(event);
ret = ret | sv.onTouchEvent(event);
return ret;
}
@Override public boolean onInterceptTouchEvent(MotionEvent event)
{
boolean ret = super.onInterceptTouchEvent(event);
ret = ret | sv.onInterceptTouchEvent(event);
return ret;
}
}
private static class ColorPickerView extends View {
private Paint mPaint;
private float mCurrentHue = 0;
private int mCurrentX = 0, mCurrentY = 0;
private int mCurrentColor, mDefaultColor;
private final int[] mHueBarColors = new int[258];
private int[] mMainColors = new int[65536];
private OnColorChangedListener mListener;
ColorPickerView(Context c, OnColorChangedListener l, int color,
int defaultColor) {
super(c);
mListener = l;
mDefaultColor = defaultColor;
// Get the current hue from the current color and update the main
// color field
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
mCurrentHue = hsv[0];
updateMainColors();
mCurrentColor = color;
// Initialize the colors of the hue slider bar
int index = 0;
for (float i = 0; i < 256; i += 256 / 42) // Red (#f00) to pink
// (#f0f)
{
mHueBarColors[index] = Color.rgb(255, 0, (int) i);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) // Pink (#f0f) to blue
// (#00f)
{
mHueBarColors[index] = Color.rgb(255 - (int) i, 0, 255);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) // Blue (#00f) to light
// blue (#0ff)
{
mHueBarColors[index] = Color.rgb(0, (int) i, 255);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) // Light blue (#0ff) to
// green (#0f0)
{
mHueBarColors[index] = Color.rgb(0, 255, 255 - (int) i);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) // Green (#0f0) to yellow
// (#ff0)
{
mHueBarColors[index] = Color.rgb((int) i, 255, 0);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) // Yellow (#ff0) to red
// (#f00)
{
mHueBarColors[index] = Color.rgb(255, 255 - (int) i, 0);
index++;
}
// Initializes the Paint that will draw the View
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setTextAlign(Paint.Align.CENTER);
mPaint.setTextSize(12);
}
// Get the current selected color from the hue bar
private int getCurrentMainColor() {
int translatedHue = 255 - (int) (mCurrentHue * 255 / 360);
int index = 0;
for (float i = 0; i < 256; i += 256 / 42) {
if (index == translatedHue)
return Color.rgb(255, 0, (int) i);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) {
if (index == translatedHue)
return Color.rgb(255 - (int) i, 0, 255);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) {
if (index == translatedHue)
return Color.rgb(0, (int) i, 255);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) {
if (index == translatedHue)
return Color.rgb(0, 255, 255 - (int) i);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) {
if (index == translatedHue)
return Color.rgb((int) i, 255, 0);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) {
if (index == translatedHue)
return Color.rgb(255, 255 - (int) i, 0);
index++;
}
return Color.RED;
}
// Update the main field colors depending on the current selected hue
private void updateMainColors() {
int mainColor = getCurrentMainColor();
int index = 0;
int[] topColors = new int[256];
for (int y = 0; y < 256; y++) {
for (int x = 0; x < 256; x++) {
if (y == 0) {
mMainColors[index] = Color.rgb(
255 - (255 - Color.red(mainColor)) * x / 255,
255 - (255 - Color.green(mainColor)) * x / 255,
255 - (255 - Color.blue(mainColor)) * x / 255);
topColors[x] = mMainColors[index];
} else
mMainColors[index] = Color.rgb(
(255 - y) * Color.red(topColors[x]) / 255,
(255 - y) * Color.green(topColors[x]) / 255,
(255 - y) * Color.blue(topColors[x]) / 255);
index++;
}
}
}
@Override
protected void onDraw(Canvas canvas) {
int translatedHue = 255 - (int) (mCurrentHue * 255 / 360);
// Display all the colors of the hue bar with lines
for (int x = 0; x < 256; x++) {
// If this is not the current selected hue, display the actual
// color
if (translatedHue != x) {
mPaint.setColor(mHueBarColors[x]);
mPaint.setStrokeWidth(1);
} else // else display a slightly larger black line
{
mPaint.setColor(Color.BLACK);
mPaint.setStrokeWidth(3);
}
canvas.drawLine(x + 10, 0, x + 10, 40, mPaint);
}
// Display the main field colors using LinearGradient
for (int x = 0; x < 256; x++) {
int[] colors = new int[2];
colors[0] = mMainColors[x];
colors[1] = Color.BLACK;
Shader shader = new LinearGradient(0, 50, 0, 306, colors, null,
Shader.TileMode.REPEAT);
mPaint.setShader(shader);
canvas.drawLine(x + 10, 50, x + 10, 306, mPaint);
}
mPaint.setShader(null);
// Display the circle around the currently selected color in the
// main field
if (mCurrentX != 0 && mCurrentY != 0) {
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(Color.BLACK);
canvas.drawCircle(mCurrentX, mCurrentY, 10, mPaint);
}
// Draw a 'button' with the currently selected color
mPaint.setStyle(Paint.Style.FILL);
mPaint.setColor(mCurrentColor);
canvas.drawRect(10, 316, 138, 356, mPaint);
// Set the text color according to the brightness of the color
mPaint.setColor(getInverseColor(mCurrentColor));
canvas.drawText(getContext().getString(R.string.ok), 74, 340,
mPaint);
// Draw a 'button' with the default color
mPaint.setStyle(Paint.Style.FILL);
mPaint.setColor(mDefaultColor);
canvas.drawRect(138, 316, 266, 356, mPaint);
// Set the text color according to the brightness of the color
mPaint.setColor(getInverseColor(mDefaultColor));
canvas.drawText(getContext().getString(R.string.cancel), 202, 340,
mPaint);
}
private int getInverseColor(int color) {
int red = Color.red(color);
int green = Color.green(color);
int blue = Color.blue(color);
int alpha = Color.alpha(color);
return Color.argb(alpha, 255 - red, 255 - green, 255 - blue);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(276, 366);
}
private boolean afterFirstDown = false;
private float startX;
private float startY;
@Override
public boolean onTouchEvent(MotionEvent event) {
// allow scrolling...
boolean ret = super.onTouchEvent(event);
int action = event.getAction();
int pointerCount = event.getPointerCount();
if ( action == MotionEvent.ACTION_CANCEL ) {
afterFirstDown = false;
} else if ( pointerCount == 1 && action == MotionEvent.ACTION_DOWN ) {
afterFirstDown = true;
startX = event.getX();
startY = event.getY();
} else if ( pointerCount == 1 && action == MotionEvent.ACTION_MOVE && !afterFirstDown ) {
afterFirstDown = true;
startX = event.getX();
startY = event.getY();
}
if ( !afterFirstDown || pointerCount != 1 || action != MotionEvent.ACTION_UP ) {
return true;
}
// on an ACTION_UP, we reset the afterFirstDown flag.
// processing uses the lifting of the finger to choose
// the color...
afterFirstDown = false;
float x = event.getX();
float y = event.getY();
if ( Math.abs(x - startX) > 10 && Math.abs(y - startY) > 10 ) {
// the color location drifted, so it must just be a scrolling action
// ignore it...
return ret;
}
// If the touch event is located in the hue bar
if (x > 10 && x < 266 && y > 0 && y < 40) {
// Update the main field colors
mCurrentHue = (255 - x) * 360 / 255;
updateMainColors();
// Update the current selected color
int transX = mCurrentX - 10;
int transY = mCurrentY - 60;
int index = 256 * (transY - 1) + transX;
if (index > 0 && index < mMainColors.length)
mCurrentColor = mMainColors[256 * (transY - 1) + transX];
// Force the redraw of the dialog
invalidate();
}
// If the touch event is located in the main field
if (x > 10 && x < 266 && y > 50 && y < 306) {
mCurrentX = (int) x;
mCurrentY = (int) y;
int transX = mCurrentX - 10;
int transY = mCurrentY - 60;
int index = 256 * (transY - 1) + transX;
if (index > 0 && index < mMainColors.length) {
// Update the current color
mCurrentColor = mMainColors[index];
// Force the redraw of the dialog
invalidate();
}
}
// If the touch event is located in the left button, notify the
// listener with the current color
if (x > 10 && x < 138 && y > 316 && y < 356)
mListener.colorChanged("", mCurrentColor);
// If the touch event is located in the right button, notify the
// listener with the default color
if (x > 138 && x < 266 && y > 316 && y < 356)
mListener.colorChanged("", mDefaultColor);
return true;
}
}
public ColorPickerDialog(Context context, OnColorChangedListener listener,
String key, int initialColor, int defaultColor, String title) {
super(context);
mListener = listener;
mKey = key;
mInitialColor = initialColor;
mDefaultColor = defaultColor;
setTitle(title);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
OnColorChangedListener l = new OnColorChangedListener() {
public void colorChanged(String key, int color) {
mListener.colorChanged(mKey, color);
dismiss();
}
};
/*BIDIRECTIONAL SCROLLVIEW*/
ScrollView sv = new ScrollView(this.getContext());
WScrollView hsv = new WScrollView(this.getContext());
hsv.sv = sv;
/*END OF BIDIRECTIONAL SCROLLVIEW*/
sv.addView(new ColorPickerView(getContext(), l, mInitialColor,
mDefaultColor), new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
hsv.addView(sv, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT));
setContentView(hsv, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
setCanceledOnTouchOutside(true);
}
}
|
0nima0-f
|
src/org/odk/collect/android/utilities/ColorPickerDialog.java
|
Java
|
asf20
| 13,047
|
/*
* Copyright (C) 2011 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.utilities;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Wrapper class for accessing Base64 functionality.
* This allows API Level 7 deployment of ODK Collect while
* enabling API Level 8 and higher phone to support encryption.
*
* @author mitchellsundt@gmail.com
*
*/
public class Base64Wrapper {
private static final int FLAGS = 2;// NO_WRAP
private Class<?> base64 = null;
public Base64Wrapper() throws ClassNotFoundException {
base64 = this.getClass().getClassLoader()
.loadClass("android.util.Base64");
}
public String encodeToString(byte[] ba) {
Class<?>[] argClassList = new Class[]{byte[].class, int.class};
try {
Method m = base64.getDeclaredMethod("encode", argClassList);
Object[] argList = new Object[]{ ba, FLAGS };
Object o = m.invoke(null, argList);
byte[] outArray = (byte[]) o;
String s = new String(outArray, "UTF-8");
return s;
} catch (SecurityException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.toString());
} catch (NoSuchMethodException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.toString());
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.toString());
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.toString());
}
}
public byte[] decode(String base64String) {
Class<?>[] argClassList = new Class[]{String.class, int.class};
Object o;
try {
Method m = base64.getDeclaredMethod("decode", argClassList);
Object[] argList = new Object[]{ base64String, FLAGS };
o = m.invoke(null, argList);
} catch (SecurityException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.toString());
} catch (NoSuchMethodException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.toString());
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.toString());
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.toString());
}
return (byte[]) o;
}
}
|
0nima0-f
|
src/org/odk/collect/android/utilities/Base64Wrapper.java
|
Java
|
asf20
| 3,079
|
/*
* Copyright (C) 2011 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
* Original License from BasicCredentialsProvider:
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.odk.collect.android.utilities;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.opendatakit.httpclientandroidlib.annotation.ThreadSafe;
import org.opendatakit.httpclientandroidlib.auth.AuthScope;
import org.opendatakit.httpclientandroidlib.auth.Credentials;
import org.opendatakit.httpclientandroidlib.client.CredentialsProvider;
/**
* Modified BasicCredentialsProvider that will clear the provider
* after 'expiryInterval' milliseconds of inactivity. Use the WebUtils
* methods to manipulate the credentials in the local context. You should
* first check that the credentials exist (which will reset the expiration
* date), then set them if they are missing.
*
* Largely a cut-and-paste of BasicCredentialsProvider.
*
* @author mitchellsundt@gmail.com
*
*/
@ThreadSafe
public class AgingCredentialsProvider implements CredentialsProvider {
private final ConcurrentHashMap<AuthScope, Credentials> credMap;
private final long expiryInterval;
private long nextClearTimestamp;
/**
* Default constructor.
*/
public AgingCredentialsProvider(int expiryInterval) {
super();
this.credMap = new ConcurrentHashMap<AuthScope, Credentials>();
this.expiryInterval = expiryInterval;
nextClearTimestamp = System.currentTimeMillis() + expiryInterval;
}
public void setCredentials(
final AuthScope authscope,
final Credentials credentials) {
if (authscope == null) {
throw new IllegalArgumentException("Authentication scope may not be null");
}
if (nextClearTimestamp < System.currentTimeMillis()) {
clear();
}
nextClearTimestamp = System.currentTimeMillis() + expiryInterval;
if ( credentials == null ) {
credMap.remove(authscope);
} else {
credMap.put(authscope, credentials);
}
}
/**
* Find matching {@link Credentials credentials} for the given authentication scope.
*
* @param map the credentials hash map
* @param authscope the {@link AuthScope authentication scope}
* @return the credentials
*
*/
private static Credentials matchCredentials(
final Map<AuthScope, Credentials> map,
final AuthScope authscope) {
// see if we get a direct hit
Credentials creds = map.get(authscope);
if (creds == null) {
// Nope.
// Do a full scan
int bestMatchFactor = -1;
AuthScope bestMatch = null;
for (AuthScope current: map.keySet()) {
int factor = authscope.match(current);
if (factor > bestMatchFactor) {
bestMatchFactor = factor;
bestMatch = current;
}
}
if (bestMatch != null) {
creds = map.get(bestMatch);
}
}
return creds;
}
public Credentials getCredentials(final AuthScope authscope) {
if (authscope == null) {
throw new IllegalArgumentException("Authentication scope may not be null");
}
if (nextClearTimestamp < System.currentTimeMillis()) {
clear();
}
nextClearTimestamp = System.currentTimeMillis() + expiryInterval;
Credentials c = matchCredentials(this.credMap, authscope);
return c;
}
public void clear() {
this.credMap.clear();
}
@Override
public String toString() {
return credMap.toString();
}
}
|
0nima0-f
|
src/org/odk/collect/android/utilities/AgingCredentialsProvider.java
|
Java
|
asf20
| 5,598
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.utilities;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.odk.collect.android.application.Collect;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Video;
import android.util.Log;
/**
* Consolidate all interactions with media providers here.
*
* The functionality of getPath() was provided by paulburke as described here:
* See
* http://stackoverflow.com/questions/20067508/get-real-path-from-uri-android
* -kitkat-new-storage-access-framework for details
*
* @author mitchellsundt@gmail.com
* @author paulburke
*
*
*/
public class MediaUtils {
private static final String t = "MediaUtils";
private MediaUtils() {
// static methods only
}
private static String escapePath(String path) {
String ep = path;
ep = ep.replaceAll("\\!", "!!");
ep = ep.replaceAll("_", "!_");
ep = ep.replaceAll("%", "!%");
return ep;
}
public static final Uri getImageUriFromMediaProvider(String imageFile) {
String selection = Images.ImageColumns.DATA + "=?";
String[] selectArgs = { imageFile };
String[] projection = { Images.ImageColumns._ID };
Cursor c = null;
try {
c = Collect
.getInstance()
.getContentResolver()
.query(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, selection, selectArgs, null);
if (c.getCount() > 0) {
c.moveToFirst();
String id = c.getString(c
.getColumnIndex(Images.ImageColumns._ID));
return Uri
.withAppendedPath(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
id);
}
return null;
} finally {
if (c != null) {
c.close();
}
}
}
public static final int deleteImageFileFromMediaProvider(String imageFile) {
ContentResolver cr = Collect.getInstance().getContentResolver();
// images
int count = 0;
Cursor imageCursor = null;
try {
String select = Images.Media.DATA + "=?";
String[] selectArgs = { imageFile };
String[] projection = { Images.ImageColumns._ID };
imageCursor = cr
.query(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, select, selectArgs, null);
if (imageCursor.getCount() > 0) {
imageCursor.moveToFirst();
List<Uri> imagesToDelete = new ArrayList<Uri>();
do {
String id = imageCursor.getString(imageCursor
.getColumnIndex(Images.ImageColumns._ID));
imagesToDelete
.add(Uri.withAppendedPath(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
id));
} while (imageCursor.moveToNext());
for (Uri uri : imagesToDelete) {
Log.i(t, "attempting to delete: " + uri);
count += cr.delete(uri, null, null);
}
}
} catch (Exception e) {
Log.e(t, e.toString());
} finally {
if (imageCursor != null) {
imageCursor.close();
}
}
File f = new File(imageFile);
if (f.exists()) {
f.delete();
}
return count;
}
public static final int deleteImagesInFolderFromMediaProvider(File folder) {
ContentResolver cr = Collect.getInstance().getContentResolver();
// images
int count = 0;
Cursor imageCursor = null;
try {
String select = Images.Media.DATA + " like ? escape '!'";
String[] selectArgs = { escapePath(folder.getAbsolutePath()) };
String[] projection = { Images.ImageColumns._ID };
imageCursor = cr
.query(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, select, selectArgs, null);
if (imageCursor.getCount() > 0) {
imageCursor.moveToFirst();
List<Uri> imagesToDelete = new ArrayList<Uri>();
do {
String id = imageCursor.getString(imageCursor
.getColumnIndex(Images.ImageColumns._ID));
imagesToDelete
.add(Uri.withAppendedPath(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
id));
} while (imageCursor.moveToNext());
for (Uri uri : imagesToDelete) {
Log.i(t, "attempting to delete: " + uri);
count += cr.delete(uri, null, null);
}
}
} catch (Exception e) {
Log.e(t, e.toString());
} finally {
if (imageCursor != null) {
imageCursor.close();
}
}
return count;
}
public static final Uri getAudioUriFromMediaProvider(String audioFile) {
String selection = Audio.AudioColumns.DATA + "=?";
String[] selectArgs = { audioFile };
String[] projection = { Audio.AudioColumns._ID };
Cursor c = null;
try {
c = Collect
.getInstance()
.getContentResolver()
.query(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection, selection, selectArgs, null);
if (c.getCount() > 0) {
c.moveToFirst();
String id = c.getString(c
.getColumnIndex(Audio.AudioColumns._ID));
return Uri
.withAppendedPath(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
id);
}
return null;
} finally {
if (c != null) {
c.close();
}
}
}
public static final int deleteAudioFileFromMediaProvider(String audioFile) {
ContentResolver cr = Collect.getInstance().getContentResolver();
// audio
int count = 0;
Cursor audioCursor = null;
try {
String select = Audio.Media.DATA + "=?";
String[] selectArgs = { audioFile };
String[] projection = { Audio.AudioColumns._ID };
audioCursor = cr
.query(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection, select, selectArgs, null);
if (audioCursor.getCount() > 0) {
audioCursor.moveToFirst();
List<Uri> audioToDelete = new ArrayList<Uri>();
do {
String id = audioCursor.getString(audioCursor
.getColumnIndex(Audio.AudioColumns._ID));
audioToDelete
.add(Uri.withAppendedPath(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
id));
} while (audioCursor.moveToNext());
for (Uri uri : audioToDelete) {
Log.i(t, "attempting to delete: " + uri);
count += cr.delete(uri, null, null);
}
}
} catch (Exception e) {
Log.e(t, e.toString());
} finally {
if (audioCursor != null) {
audioCursor.close();
}
}
File f = new File(audioFile);
if (f.exists()) {
f.delete();
}
return count;
}
public static final int deleteAudioInFolderFromMediaProvider(File folder) {
ContentResolver cr = Collect.getInstance().getContentResolver();
// audio
int count = 0;
Cursor audioCursor = null;
try {
String select = Audio.Media.DATA + " like ? escape '!'";
String[] selectArgs = { escapePath(folder.getAbsolutePath()) };
String[] projection = { Audio.AudioColumns._ID };
audioCursor = cr
.query(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection, select, selectArgs, null);
if (audioCursor.getCount() > 0) {
audioCursor.moveToFirst();
List<Uri> audioToDelete = new ArrayList<Uri>();
do {
String id = audioCursor.getString(audioCursor
.getColumnIndex(Audio.AudioColumns._ID));
audioToDelete
.add(Uri.withAppendedPath(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
id));
} while (audioCursor.moveToNext());
for (Uri uri : audioToDelete) {
Log.i(t, "attempting to delete: " + uri);
count += cr.delete(uri, null, null);
}
}
} catch (Exception e) {
Log.e(t, e.toString());
} finally {
if (audioCursor != null) {
audioCursor.close();
}
}
return count;
}
public static final Uri getVideoUriFromMediaProvider(String videoFile) {
String selection = Video.VideoColumns.DATA + "=?";
String[] selectArgs = { videoFile };
String[] projection = { Video.VideoColumns._ID };
Cursor c = null;
try {
c = Collect
.getInstance()
.getContentResolver()
.query(android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection, selection, selectArgs, null);
if (c.getCount() > 0) {
c.moveToFirst();
String id = c.getString(c
.getColumnIndex(Video.VideoColumns._ID));
return Uri
.withAppendedPath(
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
id);
}
return null;
} finally {
if (c != null) {
c.close();
}
}
}
public static final int deleteVideoFileFromMediaProvider(String videoFile) {
ContentResolver cr = Collect.getInstance().getContentResolver();
// video
int count = 0;
Cursor videoCursor = null;
try {
String select = Video.Media.DATA + "=?";
String[] selectArgs = { videoFile };
String[] projection = { Video.VideoColumns._ID };
videoCursor = cr
.query(android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection, select, selectArgs, null);
if (videoCursor.getCount() > 0) {
videoCursor.moveToFirst();
List<Uri> videoToDelete = new ArrayList<Uri>();
do {
String id = videoCursor.getString(videoCursor
.getColumnIndex(Video.VideoColumns._ID));
videoToDelete
.add(Uri.withAppendedPath(
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
id));
} while (videoCursor.moveToNext());
for (Uri uri : videoToDelete) {
Log.i(t, "attempting to delete: " + uri);
count += cr.delete(uri, null, null);
}
}
} catch (Exception e) {
Log.e(t, e.toString());
} finally {
if (videoCursor != null) {
videoCursor.close();
}
}
File f = new File(videoFile);
if (f.exists()) {
f.delete();
}
return count;
}
public static final int deleteVideoInFolderFromMediaProvider(File folder) {
ContentResolver cr = Collect.getInstance().getContentResolver();
// video
int count = 0;
Cursor videoCursor = null;
try {
String select = Video.Media.DATA + " like ? escape '!'";
String[] selectArgs = { escapePath(folder.getAbsolutePath()) };
String[] projection = { Video.VideoColumns._ID };
videoCursor = cr
.query(android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection, select, selectArgs, null);
if (videoCursor.getCount() > 0) {
videoCursor.moveToFirst();
List<Uri> videoToDelete = new ArrayList<Uri>();
do {
String id = videoCursor.getString(videoCursor
.getColumnIndex(Video.VideoColumns._ID));
videoToDelete
.add(Uri.withAppendedPath(
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
id));
} while (videoCursor.moveToNext());
for (Uri uri : videoToDelete) {
Log.i(t, "attempting to delete: " + uri);
count += cr.delete(uri, null, null);
}
}
} catch (Exception e) {
Log.e(t, e.toString());
} finally {
if (videoCursor != null) {
videoCursor.close();
}
}
return count;
}
/**
* Consolidates the file path determination functionality of the various
* media prompts. Beginning with KitKat, the responses use a different
* mechanism and needs a lot of special handling.
*
* @param ctxt
* @param uri
* @param pathKey
* @return
*/
@SuppressLint("NewApi")
public static String getPathFromUri(Context ctxt, Uri uri, String pathKey) {
if (Build.VERSION.SDK_INT >= 19) {
return getPath(ctxt, uri);
} else {
if (uri.toString().startsWith("file")) {
return uri.toString().substring(7);
} else {
String[] projection = { pathKey };
Cursor c = null;
try {
c = ctxt.getContentResolver().query(uri, projection, null,
null, null);
int column_index = c.getColumnIndexOrThrow(pathKey);
String path = null;
if (c.getCount() > 0) {
c.moveToFirst();
path = c.getString(column_index);
}
return path;
} finally {
if (c != null) {
c.close();
}
}
}
}
}
@SuppressLint("NewApi")
/**
* Get a file path from a Uri. This will get the the path for Storage Access
* Framework Documents, as well as the _data field for the MediaStore and
* other file-based ContentProviders.<br>
* <br>
* Callers should check whether the path is local before assuming it
* represents a local file.
*
* @param context The context.
* @param uri The Uri to query.
* @see #isLocal(String)
* @see #getFile(Context, Uri)
* @author paulburke
*/
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= 19;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/"
+ split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"),
Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] { split[1] };
return getDataColumn(context, contentUri, selection,
selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
* @author paulburke
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri
.getAuthority());
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
* @author paulburke
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri
.getAuthority());
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is MediaProvider.
* @author paulburke
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri
.getAuthority());
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri
.getAuthority());
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context
* The context.
* @param uri
* The Uri to query.
* @param selection
* (Optional) Filter used in the query.
* @param selectionArgs
* (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
* @author paulburke
*/
public static String getDataColumn(Context context, Uri uri,
String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = { column };
try {
cursor = context.getContentResolver().query(uri, projection,
selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
}
|
0nima0-f
|
src/org/odk/collect/android/utilities/MediaUtils.java
|
Java
|
asf20
| 17,960
|
/*
* Copyright (C) 2013 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.utilities;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ConfigurationInfo;
import android.os.Build;
import android.view.MenuItem;
/**
* Compatibility utilities for backward-compatible support of Android APIs above SDK 8
*
* @author mitchellsundt@gmail.com
*
*/
@SuppressLint("NewApi")
public class CompatibilityUtils {
public static void setShowAsAction(MenuItem item, int action) {
if ( Build.VERSION.SDK_INT >= 11 ) {
item.setShowAsAction(action);
}
}
public static void invalidateOptionsMenu(final Activity a) {
if ( Build.VERSION.SDK_INT >= 11 ) {
a.runOnUiThread(
new Runnable() {
@Override
public void run() {
a.invalidateOptionsMenu();
}
});
}
}
public static boolean useMapsV2(final Context context) {
if ( Build.VERSION.SDK_INT >= 8 ) {
final ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
boolean supportsEs2 = configurationInfo.reqGlEsVersion >= 0x20000;
return supportsEs2;
}
return false;
}
}
|
0nima0-f
|
src/org/odk/collect/android/utilities/CompatibilityUtils.java
|
Java
|
asf20
| 1,942
|
/*
* Copyright (C) 2011 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.utilities;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.zip.GZIPInputStream;
import org.apache.http.HttpStatus;
import org.kxml2.io.KXmlParser;
import org.kxml2.kdom.Document;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.opendatakit.httpclientandroidlib.Header;
import org.opendatakit.httpclientandroidlib.HttpEntity;
import org.opendatakit.httpclientandroidlib.HttpHost;
import org.opendatakit.httpclientandroidlib.HttpRequest;
import org.opendatakit.httpclientandroidlib.HttpResponse;
import org.opendatakit.httpclientandroidlib.auth.AuthScope;
import org.opendatakit.httpclientandroidlib.auth.Credentials;
import org.opendatakit.httpclientandroidlib.auth.UsernamePasswordCredentials;
import org.opendatakit.httpclientandroidlib.auth.params.AuthPNames;
import org.opendatakit.httpclientandroidlib.client.AuthCache;
import org.opendatakit.httpclientandroidlib.client.CredentialsProvider;
import org.opendatakit.httpclientandroidlib.client.HttpClient;
import org.opendatakit.httpclientandroidlib.client.methods.HttpGet;
import org.opendatakit.httpclientandroidlib.client.methods.HttpHead;
import org.opendatakit.httpclientandroidlib.client.methods.HttpPost;
import org.opendatakit.httpclientandroidlib.client.params.AuthPolicy;
import org.opendatakit.httpclientandroidlib.client.params.ClientPNames;
import org.opendatakit.httpclientandroidlib.client.params.CookiePolicy;
import org.opendatakit.httpclientandroidlib.client.params.HttpClientParams;
import org.opendatakit.httpclientandroidlib.client.protocol.ClientContext;
import org.opendatakit.httpclientandroidlib.conn.ClientConnectionManager;
import org.opendatakit.httpclientandroidlib.impl.auth.BasicScheme;
import org.opendatakit.httpclientandroidlib.impl.client.BasicAuthCache;
import org.opendatakit.httpclientandroidlib.impl.client.DefaultHttpClient;
import org.opendatakit.httpclientandroidlib.params.BasicHttpParams;
import org.opendatakit.httpclientandroidlib.params.HttpConnectionParams;
import org.opendatakit.httpclientandroidlib.params.HttpParams;
import org.opendatakit.httpclientandroidlib.protocol.HttpContext;
import org.xmlpull.v1.XmlPullParser;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.text.format.DateFormat;
import android.util.Log;
/**
* Common utility methods for managing the credentials associated with the
* request context and constructing http context, client and request with the
* proper parameters and OpenRosa headers.
*
* @author mitchellsundt@gmail.com
*/
public final class WebUtils {
public static final String t = "WebUtils";
public static final String OPEN_ROSA_VERSION_HEADER = "X-OpenRosa-Version";
public static final String OPEN_ROSA_VERSION = "1.0";
private static final String DATE_HEADER = "Date";
public static final String HTTP_CONTENT_TYPE_TEXT_XML = "text/xml";
public static final int CONNECTION_TIMEOUT = 30000;
public static final String ACCEPT_ENCODING_HEADER = "Accept-Encoding";
public static final String GZIP_CONTENT_ENCODING = "gzip";
private static ClientConnectionManager httpConnectionManager = null;
public static final List<AuthScope> buildAuthScopes(String host) {
List<AuthScope> asList = new ArrayList<AuthScope>();
AuthScope a;
// allow digest auth on any port...
a = new AuthScope(host, -1, null, AuthPolicy.DIGEST);
asList.add(a);
// and allow basic auth on the standard TLS/SSL ports...
a = new AuthScope(host, 443, null, AuthPolicy.BASIC);
asList.add(a);
a = new AuthScope(host, 8443, null, AuthPolicy.BASIC);
asList.add(a);
return asList;
}
public static final void clearAllCredentials() {
CredentialsProvider credsProvider = Collect.getInstance()
.getCredentialsProvider();
Log.i(t, "clearAllCredentials");
credsProvider.clear();
}
public static final boolean hasCredentials(String userEmail, String host) {
CredentialsProvider credsProvider = Collect.getInstance()
.getCredentialsProvider();
List<AuthScope> asList = buildAuthScopes(host);
boolean hasCreds = true;
for (AuthScope a : asList) {
Credentials c = credsProvider.getCredentials(a);
if (c == null) {
hasCreds = false;
continue;
}
}
return hasCreds;
}
/**
* Remove all credentials for accessing the specified host.
*
* @param host
*/
public static final void clearHostCredentials(String host) {
CredentialsProvider credsProvider = Collect.getInstance()
.getCredentialsProvider();
Log.i(t, "clearHostCredentials: " + host);
List<AuthScope> asList = buildAuthScopes(host);
for (AuthScope a : asList) {
credsProvider.setCredentials(a, null);
}
}
/**
* Remove all credentials for accessing the specified host and, if the
* username is not null or blank then add a (username, password) credential
* for accessing this host.
*
* @param username
* @param password
* @param host
*/
public static final void addCredentials(String username, String password,
String host) {
// to ensure that this is the only authentication available for this
// host...
clearHostCredentials(host);
if (username != null && username.trim().length() != 0) {
Log.i(t, "adding credential for host: " + host + " username:"
+ username);
Credentials c = new UsernamePasswordCredentials(username, password);
addCredentials(c, host);
}
}
private static final void addCredentials(Credentials c, String host) {
CredentialsProvider credsProvider = Collect.getInstance()
.getCredentialsProvider();
List<AuthScope> asList = buildAuthScopes(host);
for (AuthScope a : asList) {
credsProvider.setCredentials(a, c);
}
}
public static final void enablePreemptiveBasicAuth(
HttpContext localContext, String host) {
AuthCache ac = (AuthCache) localContext
.getAttribute(ClientContext.AUTH_CACHE);
HttpHost h = new HttpHost(host);
if (ac == null) {
ac = new BasicAuthCache();
localContext.setAttribute(ClientContext.AUTH_CACHE, ac);
}
List<AuthScope> asList = buildAuthScopes(host);
for (AuthScope a : asList) {
if (a.getScheme() == AuthPolicy.BASIC) {
ac.put(h, new BasicScheme());
}
}
}
private static final void setOpenRosaHeaders(HttpRequest req) {
req.setHeader(OPEN_ROSA_VERSION_HEADER, OPEN_ROSA_VERSION);
GregorianCalendar g = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
g.setTime(new Date());
req.setHeader(DATE_HEADER,
DateFormat.format("E, dd MMM yyyy hh:mm:ss zz", g).toString());
}
public static final HttpHead createOpenRosaHttpHead(Uri u) {
HttpHead req = new HttpHead(URI.create(u.toString()));
setOpenRosaHeaders(req);
return req;
}
public static final HttpGet createOpenRosaHttpGet(URI uri) {
HttpGet req = new HttpGet();
setOpenRosaHeaders(req);
setGoogleHeaders(req);
req.setURI(uri);
return req;
}
public static final void setGoogleHeaders(HttpRequest req) {
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(Collect.getInstance().getApplicationContext());
String protocol = settings.getString(PreferencesActivity.KEY_PROTOCOL,
Collect.getInstance().getString(R.string.protocol_odk_default));
// TODO: this doesn't exist....
// if ( protocol.equals(PreferencesActivity.PROTOCOL_GOOGLE) ) {
// String auth = settings.getString(PreferencesActivity.KEY_AUTH, "");
// if ((auth != null) && (auth.length() > 0)) {
// req.setHeader("Authorization", "GoogleLogin auth=" + auth);
// }
// }
}
public static final HttpPost createOpenRosaHttpPost(Uri u) {
HttpPost req = new HttpPost(URI.create(u.toString()));
setOpenRosaHeaders(req);
setGoogleHeaders(req);
return req;
}
/**
* Create an httpClient with connection timeouts and other parameters set.
* Save and reuse the connection manager across invocations (this is what
* requires synchronized access).
*
* @param timeout
* @return HttpClient properly configured.
*/
public static final synchronized HttpClient createHttpClient(int timeout) {
// configure connection
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, timeout);
HttpConnectionParams.setSoTimeout(params, 2 * timeout);
// support redirecting to handle http: => https: transition
HttpClientParams.setRedirecting(params, true);
// support authenticating
HttpClientParams.setAuthenticating(params, true);
HttpClientParams.setCookiePolicy(params,
CookiePolicy.BROWSER_COMPATIBILITY);
// if possible, bias toward digest auth (may not be in 4.0 beta 2)
List<String> authPref = new ArrayList<String>();
authPref.add(AuthPolicy.DIGEST);
authPref.add(AuthPolicy.BASIC);
// does this work in Google's 4.0 beta 2 snapshot?
params.setParameter(AuthPNames.TARGET_AUTH_PREF, authPref);
params.setParameter(ClientPNames.MAX_REDIRECTS, 1);
params.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
// setup client
DefaultHttpClient httpclient;
// reuse the connection manager across all clients this ODK Collect
// creates.
if (httpConnectionManager == null) {
// let Apache stack create a connection manager.
httpclient = new DefaultHttpClient(params);
httpConnectionManager = httpclient.getConnectionManager();
} else {
// reuse the connection manager we already got.
httpclient = new DefaultHttpClient(httpConnectionManager, params);
}
return httpclient;
}
/**
* Utility to ensure that the entity stream of a response is drained of
* bytes.
*
* @param response
*/
public static final void discardEntityBytes(HttpResponse response) {
// may be a server that does not handle
HttpEntity entity = response.getEntity();
if (entity != null) {
try {
// have to read the stream in order to reuse the connection
InputStream is = response.getEntity().getContent();
// read to end of stream...
final long count = 1024L;
while (is.skip(count) == count)
;
is.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Common method for returning a parsed xml document given a url and the
* http context and client objects involved in the web connection.
*
* @param urlString
* @param localContext
* @param httpclient
* @return
*/
public static DocumentFetchResult getXmlDocument(String urlString,
HttpContext localContext, HttpClient httpclient) {
URI u = null;
try {
URL url = new URL(urlString);
u = url.toURI();
} catch (Exception e) {
e.printStackTrace();
return new DocumentFetchResult(e.getLocalizedMessage()
// + app.getString(R.string.while_accessing) + urlString);
+ ("while accessing") + urlString, 0);
}
if (u.getHost() == null ) {
return new DocumentFetchResult("Invalid server URL (no hostname): " + urlString, 0);
}
// if https then enable preemptive basic auth...
if (u.getScheme().equals("https")) {
enablePreemptiveBasicAuth(localContext, u.getHost());
}
// set up request...
HttpGet req = WebUtils.createOpenRosaHttpGet(u);
req.addHeader(WebUtils.ACCEPT_ENCODING_HEADER, WebUtils.GZIP_CONTENT_ENCODING);
HttpResponse response = null;
try {
response = httpclient.execute(req, localContext);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
if (statusCode != HttpStatus.SC_OK) {
WebUtils.discardEntityBytes(response);
if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
// clear the cookies -- should not be necessary?
Collect.getInstance().getCookieStore().clear();
}
String webError = response.getStatusLine().getReasonPhrase()
+ " (" + statusCode + ")";
return new DocumentFetchResult(u.toString()
+ " responded with: " + webError, statusCode);
}
if (entity == null) {
String error = "No entity body returned from: " + u.toString();
Log.e(t, error);
return new DocumentFetchResult(error, 0);
}
if (!entity.getContentType().getValue().toLowerCase(Locale.ENGLISH)
.contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML)) {
WebUtils.discardEntityBytes(response);
String error = "ContentType: "
+ entity.getContentType().getValue()
+ " returned from: "
+ u.toString()
+ " is not text/xml. This is often caused a network proxy. Do you need to login to your network?";
Log.e(t, error);
return new DocumentFetchResult(error, 0);
}
// parse response
Document doc = null;
try {
InputStream is = null;
InputStreamReader isr = null;
try {
is = entity.getContent();
Header contentEncoding = entity.getContentEncoding();
if ( contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase(WebUtils.GZIP_CONTENT_ENCODING) ) {
is = new GZIPInputStream(is);
}
isr = new InputStreamReader(is, "UTF-8");
doc = new Document();
KXmlParser parser = new KXmlParser();
parser.setInput(isr);
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES,
true);
doc.parse(parser);
isr.close();
isr = null;
} finally {
if (isr != null) {
try {
// ensure stream is consumed...
final long count = 1024L;
while (isr.skip(count) == count)
;
} catch (Exception e) {
// no-op
}
try {
isr.close();
} catch (Exception e) {
// no-op
}
}
if (is != null) {
try {
is.close();
} catch (Exception e) {
// no-op
}
}
}
} catch (Exception e) {
e.printStackTrace();
String error = "Parsing failed with " + e.getMessage()
+ "while accessing " + u.toString();
Log.e(t, error);
return new DocumentFetchResult(error, 0);
}
boolean isOR = false;
Header[] fields = response
.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER);
if (fields != null && fields.length >= 1) {
isOR = true;
boolean versionMatch = false;
boolean first = true;
StringBuilder b = new StringBuilder();
for (Header h : fields) {
if (WebUtils.OPEN_ROSA_VERSION.equals(h.getValue())) {
versionMatch = true;
break;
}
if (!first) {
b.append("; ");
}
first = false;
b.append(h.getValue());
}
if (!versionMatch) {
Log.w(t, WebUtils.OPEN_ROSA_VERSION_HEADER
+ " unrecognized version(s): " + b.toString());
}
}
return new DocumentFetchResult(doc, isOR);
} catch (Exception e) {
clearHttpConnectionManager();
e.printStackTrace();
String cause;
Throwable c = e;
while (c.getCause() != null) {
c = c.getCause();
}
cause = c.toString();
String error = "Error: " + cause + " while accessing "
+ u.toString();
Log.w(t, error);
return new DocumentFetchResult(error, 0);
}
}
public static void clearHttpConnectionManager() {
// If we get an unexpected exception, the safest thing is to close
// all connections
// so that if there is garbage on the connection we ensure it is
// removed. This
// is especially important if the connection times out.
if ( httpConnectionManager != null ) {
httpConnectionManager.shutdown();
httpConnectionManager = null;
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/utilities/WebUtils.java
|
Java
|
asf20
| 16,339
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.utilities;
import java.net.MalformedURLException;
import java.net.URL;
public class UrlUtils {
public static boolean isValidUrl(String url) {
try {
new URL(url);
return true;
} catch (MalformedURLException e) {
return false;
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/utilities/UrlUtils.java
|
Java
|
asf20
| 943
|
/*
* Copyright (C) 2011 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.utilities;
import org.kxml2.kdom.Document;
public class DocumentFetchResult {
public final String errorMessage;
public final int responseCode;
public final Document doc;
public final boolean isOpenRosaResponse;
public DocumentFetchResult(String msg, int response) {
responseCode = response;
errorMessage = msg;
doc = null;
isOpenRosaResponse = false;
}
public DocumentFetchResult(Document doc, boolean isOpenRosaResponse) {
responseCode = 0;
errorMessage = null;
this.doc = doc;
this.isOpenRosaResponse = isOpenRosaResponse;
}
}
|
0nima0-f
|
src/org/odk/collect/android/utilities/DocumentFetchResult.java
|
Java
|
asf20
| 1,337
|
/*
* Copyright (C) 2013 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.utilities;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.odk.collect.android.application.Collect;
import android.util.Log;
/**
* Used for logging data to log files that could be retrieved after a field deployment.
* The initial use for this is to assist in diagnosing a report of a cached geopoints
* being reported, causing stale GPS coordinates to be recorded (issue 780).
*
* @author mitchellsundt@gmail.com
*
*/
public class InfoLogger {
private static final String t = "InfoLogger";
private static final String LOG_DIRECTORY = "logging";
private static final String LOG_FILE = "geotrace.log";
public static final void geolog(String msg) {
geologToLogcat(msg);
}
private static final void geologToLogcat(String msg) {
Log.i(t, msg);
}
@SuppressWarnings("unused")
private static final void geologToFile(String msg) {
File dir = new File( Collect.ODK_ROOT + File.separator + LOG_DIRECTORY );
if ( !dir.exists() ) {
dir.mkdirs();
}
File log = new File(dir, LOG_FILE);
FileOutputStream fo = null;
try {
fo = new FileOutputStream(log, true);
msg = msg + "\n";
fo.write( msg.getBytes("UTF-8") );
fo.flush();
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.e(t, "exception: " + e.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.e(t, "exception: " + e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.e(t, "exception: " + e.toString());
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/utilities/InfoLogger.java
|
Java
|
asf20
| 2,338
|
/*
* Copyright (C) 2012 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.database;
import java.io.File;
import java.util.Calendar;
import java.util.LinkedList;
import org.javarosa.core.model.FormIndex;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.logic.FormController;
import android.app.Activity;
import android.content.ContentValues;
import android.database.SQLException;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
/**
* Log all user interface activity into a SQLite database. Logging is disabled by default.
*
* The logging database will be "/sdcard/odk/log/activityLog.db"
*
* Logging is enabled if the file "/sdcard/odk/log/enabled" exists.
*
* @author mitchellsundt@gmail.com
* @author Carl Hartung (carlhartung@gmail.com)
*
*/
public final class ActivityLogger {
private static class DatabaseHelper extends ODKSQLiteOpenHelper {
DatabaseHelper() {
super(Collect.LOG_PATH, DATABASE_NAME, null, DATABASE_VERSION);
new File(Collect.LOG_PATH).mkdirs();
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
/**
* The minimum delay, in milliseconds, for a scroll action to be considered new.
*/
private static final long MIN_SCROLL_DELAY = 400L;
/**
* The maximum size of the scroll action buffer. After it reaches this size,
* it will be flushed.
*/
private static final int MAX_SCROLL_ACTION_BUFFER_SIZE = 8;
private static final String DATABASE_TABLE = "log";
private static final String ENABLE_LOGGING = "enabled";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "activityLog.db";
// Database columns
private static final String ID = "_id";
private static final String TIMESTAMP = "timestamp";
private static final String DEVICEID = "device_id";
private static final String CLASS = "class";
private static final String CONTEXT = "context";
private static final String ACTION = "action";
private static final String INSTANCE_PATH = "instance_path";
private static final String QUESTION = "question";
private static final String PARAM1 = "param1";
private static final String PARAM2 = "param2";
private static final String DATABASE_CREATE =
"create table " + DATABASE_TABLE + " (" +
ID + " integer primary key autoincrement, " +
TIMESTAMP + " integer not null, " +
DEVICEID + " text not null, " +
CLASS + " text not null, " +
CONTEXT + " text not null, " +
ACTION + " text, " +
INSTANCE_PATH + " text, " +
QUESTION + " text, " +
PARAM1 + " text, " +
PARAM2 + " text);";
private final boolean mLoggingEnabled;
private final String mDeviceId;
private DatabaseHelper mDbHelper = null;
private SQLiteDatabase mDb = null;
private boolean mIsOpen = false;
// We buffer scroll actions to make sure there aren't too many pauses
// during scrolling. This list is flushed every time any other type of
// action is logged.
private LinkedList<ContentValues> mScrollActions = new LinkedList<ContentValues>();
public ActivityLogger(String deviceId) {
this.mDeviceId = deviceId;
mLoggingEnabled = new File(Collect.LOG_PATH, ENABLE_LOGGING).exists();
open();
}
public boolean isOpen() {
return mLoggingEnabled && mIsOpen;
}
public void open() throws SQLException {
if (!mLoggingEnabled || mIsOpen) return;
try {
mDbHelper = new DatabaseHelper();
mDb = mDbHelper.getWritableDatabase();
mIsOpen = true;
} catch (SQLiteException e) {
System.err.println("Error: " + e.getMessage());
mIsOpen = false;
}
}
// cached to improve logging performance...
// only access these through getXPath(FormIndex index);
private FormIndex cachedXPathIndex = null;
private String cachedXPathValue = null;
// DO NOT CALL THIS OUTSIDE OF synchronized(mScrollActions) !!!!
// DO NOT CALL THIS OUTSIDE OF synchronized(mScrollActions) !!!!
// DO NOT CALL THIS OUTSIDE OF synchronized(mScrollActions) !!!!
// DO NOT CALL THIS OUTSIDE OF synchronized(mScrollActions) !!!!
private String getXPath(FormIndex index) {
if ( index == cachedXPathIndex ) return cachedXPathValue;
cachedXPathIndex = index;
cachedXPathValue = Collect.getInstance().getFormController().getXPath(index);
return cachedXPathValue;
}
private void log(String object, String context, String action, String instancePath, FormIndex index, String param1, String param2) {
if (!isOpen()) return;
ContentValues cv = new ContentValues();
cv.put(DEVICEID, mDeviceId);
cv.put(CLASS, object);
cv.put(CONTEXT, context);
cv.put(ACTION, action);
cv.put(INSTANCE_PATH, instancePath);
cv.put(PARAM1, param1);
cv.put(PARAM2, param2);
cv.put(TIMESTAMP, Calendar.getInstance().getTimeInMillis());
insertContentValues(cv, index);
}
public void logScrollAction(Object t, int distance) {
if (!isOpen()) return;
synchronized(mScrollActions) {
long timeStamp = Calendar.getInstance().getTimeInMillis();
// Check to see if we can add this scroll action to the previous action.
if (!mScrollActions.isEmpty()) {
ContentValues lastCv = mScrollActions.get(mScrollActions.size() - 1);
long oldTimeStamp = lastCv.getAsLong(TIMESTAMP);
int oldDistance = Integer.parseInt(lastCv.getAsString(PARAM1));
if (Integer.signum(distance) == Integer.signum(oldDistance) &&
timeStamp - oldTimeStamp < MIN_SCROLL_DELAY) {
lastCv.put(PARAM1, oldDistance + distance);
lastCv.put(TIMESTAMP, timeStamp);
return;
}
}
if (mScrollActions.size() >= MAX_SCROLL_ACTION_BUFFER_SIZE) {
insertContentValues(null, null); // flush scroll list...
}
String idx = "";
String instancePath = "";
FormController formController = Collect.getInstance().getFormController();
if ( formController != null ) {
idx = getXPath(formController.getFormIndex());
instancePath = formController.getInstancePath().getAbsolutePath();
}
// Add a new scroll action to the buffer.
ContentValues cv = new ContentValues();
cv.put(DEVICEID, mDeviceId);
cv.put(CLASS, t.getClass().getName());
cv.put(CONTEXT, "scroll");
cv.put(ACTION, "");
cv.put(PARAM1, distance);
cv.put(QUESTION, idx);
cv.put(INSTANCE_PATH, instancePath);
cv.put(TIMESTAMP, timeStamp);
cv.put(PARAM2, timeStamp);
mScrollActions.add(cv);
}
}
private void insertContentValues(ContentValues cv, FormIndex index) {
synchronized(mScrollActions) {
try {
while ( !mScrollActions.isEmpty() ) {
ContentValues scv = mScrollActions.removeFirst();
mDb.insert(DATABASE_TABLE, null, scv);
}
if ( cv != null ) {
String idx = "";
if ( index != null ) {
idx = getXPath(index);
}
cv.put(QUESTION,idx);
mDb.insert(DATABASE_TABLE, null, cv);
}
} catch (SQLiteConstraintException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
// Convenience methods
public void logOnStart(Activity a) {
log( a.getClass().getName(), "onStart", null, null, null, null, null);
}
public void logOnStop(Activity a) {
log( a.getClass().getName(), "onStop", null, null, null, null, null);
}
public void logAction(Object t, String context, String action) {
log( t.getClass().getName(), context, action, null, null, null, null);
}
public void logActionParam(Object t, String context, String action, String param1) {
log( t.getClass().getName(), context, action, null, null, param1, null);
}
public void logInstanceAction(Object t, String context, String action) {
FormIndex index = null;
String instancePath = null;
FormController formController = Collect.getInstance().getFormController();
if ( formController != null ) {
index = formController.getFormIndex();
File instanceFile = formController.getInstancePath();
if ( instanceFile != null ) {
instancePath = instanceFile.getAbsolutePath();
}
}
log( t.getClass().getName(), context, action, instancePath, index, null, null);
}
public void logInstanceAction(Object t, String context, String action, FormIndex index) {
String instancePath = null;
FormController formController = Collect.getInstance().getFormController();
if ( formController != null ) {
index = formController.getFormIndex();
instancePath = formController.getInstancePath().getAbsolutePath();
}
log( t.getClass().getName(), context, action, instancePath, index, null, null);
}
}
|
0nima0-f
|
src/org/odk/collect/android/database/ActivityLogger.java
|
Java
|
asf20
| 9,728
|
package org.odk.collect.android.database;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.odk.collect.android.application.Collect;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class ItemsetDbAdapter {
public static final String KEY_ID = "_id";
private static final String TAG = "ItemsetDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "itemsets.db";
private static final String DATABASE_TABLE = "itemset_";
private static final int DATABASE_VERSION = 2;
private static final String ITEMSET_TABLE = "itemsets";
private static final String KEY_ITEMSET_HASH = "hash";
private static final String KEY_PATH = "path";
private static final String CREATE_ITEMSET_TABLE =
"create table " + ITEMSET_TABLE + " (_id integer primary key autoincrement, "
+ KEY_ITEMSET_HASH + " text, "
+ KEY_PATH + " text "
+ ");";
/**
* This class helps open, create, and upgrade the database file.
*/
private static class DatabaseHelper extends ODKSQLiteOpenHelper {
DatabaseHelper() {
super(Collect.METADATA_PATH, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// create table to keep track of the itemsets
db.execSQL(CREATE_ITEMSET_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
// first drop all of our generated itemset tables
Cursor c = db.query(ITEMSET_TABLE, null, null, null, null, null, null);
if (c != null) {
c.move(-1);
while (c.moveToNext()) {
String table = c.getString(c.getColumnIndex(KEY_ITEMSET_HASH));
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE + table);
}
c.close();
}
// then drop the table tracking itemsets itself
db.execSQL("DROP TABLE IF EXISTS " + ITEMSET_TABLE);
onCreate(db);
}
}
public ItemsetDbAdapter() {
}
/**
* Open the database. If it cannot be opened, try to create a new instance
* of the database. If it cannot be created, throw an exception to signal
* the failure
*
* @return this (self reference, allowing this to be chained in an
* initialization call)
* @throws SQLException if the database could be neither opened or created
*/
public ItemsetDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper();
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public boolean createTable(String formHash, String pathHash, String[] columns, String path) {
StringBuilder sb = new StringBuilder();
// get md5 of the path to itemset.csv, which is unique per form
// the md5 is easier to use because it doesn't have chars like '/'
sb.append("create table " + DATABASE_TABLE + pathHash
+ " (_id integer primary key autoincrement ");
for (int j = 0; j < columns.length; j++) {
// add double quotes in case the column is of label:lang
sb.append(" , \"" + columns[j] + "\" text ");
// create database with first line
}
sb.append(");");
String tableCreate = sb.toString();
Log.i(TAG, "create string: " + tableCreate);
mDb.execSQL(tableCreate);
ContentValues cv = new ContentValues();
cv.put(KEY_ITEMSET_HASH, formHash);
cv.put(KEY_PATH, path);
mDb.insert(ITEMSET_TABLE, null, cv);
return true;
}
public boolean addRow(String tableName, String[] columns, String[] newRow) {
ContentValues cv = new ContentValues();
// rows don't necessarily use all the columns
// but a column is guaranteed to exist for a row (or else blow up)
for (int i = 0; i < newRow.length; i++) {
cv.put("\"" + columns[i] + "\"", newRow[i]);
}
mDb.insert(DATABASE_TABLE + tableName, null, cv);
return true;
}
public boolean tableExists(String tableName) {
// select name from sqlite_master where type = 'table'
String selection = "type=? and name=?";
String selectionArgs[] = {
"table", DATABASE_TABLE + tableName
};
Cursor c = mDb.query("sqlite_master", null, selection, selectionArgs,
null, null, null);
boolean exists = false;
if (c.getCount() == 1) {
exists = true;
}
c.close();
return exists;
}
public void beginTransaction() {
mDb.execSQL("BEGIN");
}
public void commit() {
mDb.execSQL("COMMIT");
}
public Cursor query(String hash, String selection, String[] selectionArgs) throws SQLException {
Cursor mCursor = mDb.query(true, DATABASE_TABLE + hash, null, selection, selectionArgs,
null, null, null, null);
return mCursor;
}
public void dropTable(String pathHash, String path) {
// drop the table
mDb.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE + pathHash);
// and remove the entry from the itemsets table
String where = KEY_PATH + "=?";
String[] whereArgs = {
path
};
mDb.delete(ITEMSET_TABLE, where, whereArgs);
}
public Cursor getItemsets(String path) {
String selection = KEY_PATH + "=?";
String[] selectionArgs = {
path
};
Cursor c = mDb.query(ITEMSET_TABLE, null, selection, selectionArgs, null, null, null);
return c;
}
public void delete(String path) {
Cursor c = getItemsets(path);
if (c != null) {
if (c.getCount() == 1) {
c.moveToFirst();
String table = getMd5FromString(c.getString(c.getColumnIndex(KEY_PATH)));
mDb.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE + table);
}
c.close();
}
String where = KEY_PATH + "=?";
String[] whereArgs = {
path
};
mDb.delete(ITEMSET_TABLE, where, whereArgs);
}
public static String getMd5FromString(String toEncode) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
Log.e("MD5", e.getMessage());
}
md.update(toEncode.getBytes());
byte[] digest = md.digest();
BigInteger bigInt = new BigInteger(1,digest);
String hashtext = bigInt.toString(16);
return hashtext;
}
}
|
0nima0-f
|
src/org/odk/collect/android/database/ItemsetDbAdapter.java
|
Java
|
asf20
| 7,354
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.database;
import java.io.File;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.os.Environment;
import android.util.Log;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
/**
* We've taken this from Android's SQLiteOpenHelper. However, we can't appropriately lock the
* database so there may be issues if a thread opens the database read-only and another thread tries
* to open the database read/write. I don't think this will ever happen in ODK, though. (fingers
* crossed).
*/
/**
* A helper class to manage database creation and version management. You create a subclass
* implementing {@link #onCreate}, {@link #onUpgrade} and optionally {@link #onOpen}, and this class
* takes care of opening the database if it exists, creating it if it does not, and upgrading it as
* necessary. Transactions are used to make sure the database is always in a sensible state.
* <p>
* For an example, see the NotePadProvider class in the NotePad sample application, in the
* <em>samples/</em> directory of the SDK.
* </p>
*/
public abstract class ODKSQLiteOpenHelper {
private static final String t = ODKSQLiteOpenHelper.class.getSimpleName();
private final String mPath;
private final String mName;
private final CursorFactory mFactory;
private final int mNewVersion;
private SQLiteDatabase mDatabase = null;
private boolean mIsInitializing = false;
/**
* Create a helper object to create, open, and/or manage a database. The database is not
* actually created or opened until one of {@link #getWritableDatabase} or
* {@link #getReadableDatabase} is called.
*
* @param path to the file
* @param name of the database file, or null for an in-memory database
* @param factory to use for creating cursor objects, or null for the default
* @param version number of the database (starting at 1); if the database is older,
* {@link #onUpgrade} will be used to upgrade the database
*/
public ODKSQLiteOpenHelper(String path, String name, CursorFactory factory, int version) {
if (version < 1)
throw new IllegalArgumentException("Version must be >= 1, was " + version);
mPath = path;
mName = name;
mFactory = factory;
mNewVersion = version;
}
/**
* Create and/or open a database that will be used for reading and writing. Once opened
* successfully, the database is cached, so you can call this method every time you need to
* write to the database. Make sure to call {@link #close} when you no longer need it.
* <p>
* Errors such as bad permissions or a full disk may cause this operation to fail, but future
* attempts may succeed if the problem is fixed.
* </p>
*
* @throws SQLiteException if the database cannot be opened for writing
* @return a read/write database object valid until {@link #close} is called
*/
public synchronized SQLiteDatabase getWritableDatabase() {
if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly()) {
return mDatabase; // The database is already open for business
}
if (mIsInitializing) {
throw new IllegalStateException("getWritableDatabase called recursively");
}
// If we have a read-only database open, someone could be using it
// (though they shouldn't), which would cause a lock to be held on
// the file, and our attempts to open the database read-write would
// fail waiting for the file lock. To prevent that, we acquire the
// lock on the read-only database, which shuts out other users.
boolean success = false;
SQLiteDatabase db = null;
// if (mDatabase != null) mDatabase.lock();
try {
mIsInitializing = true;
if (mName == null) {
db = SQLiteDatabase.create(null);
} else {
db = SQLiteDatabase.openOrCreateDatabase(mPath + File.separator + mName, mFactory);
// db = mContext.openOrCreateDatabase(mName, 0, mFactory);
}
int version = db.getVersion();
if (version != mNewVersion) {
db.beginTransaction();
try {
if (version == 0) {
onCreate(db);
} else {
onUpgrade(db, version, mNewVersion);
}
db.setVersion(mNewVersion);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
onOpen(db);
success = true;
return db;
} finally {
mIsInitializing = false;
if (success) {
if (mDatabase != null) {
try {
mDatabase.close();
} catch (Exception e) {
}
// mDatabase.unlock();
}
mDatabase = db;
} else {
// if (mDatabase != null) mDatabase.unlock();
if (db != null)
db.close();
}
}
}
/**
* Create and/or open a database. This will be the same object returned by
* {@link #getWritableDatabase} unless some problem, such as a full disk, requires the database
* to be opened read-only. In that case, a read-only database object will be returned. If the
* problem is fixed, a future call to {@link #getWritableDatabase} may succeed, in which case
* the read-only database object will be closed and the read/write object will be returned in
* the future.
*
* @throws SQLiteException if the database cannot be opened
* @return a database object valid until {@link #getWritableDatabase} or {@link #close} is
* called.
*/
public synchronized SQLiteDatabase getReadableDatabase() {
if (mDatabase != null && mDatabase.isOpen()) {
return mDatabase; // The database is already open for business
}
if (mIsInitializing) {
throw new IllegalStateException("getReadableDatabase called recursively");
}
try {
return getWritableDatabase();
} catch (SQLiteException e) {
if (mName == null)
throw e; // Can't open a temp database read-only!
Log.e(t, "Couldn't open " + mName + " for writing (will try read-only):", e);
}
SQLiteDatabase db = null;
try {
mIsInitializing = true;
String path = mPath + File.separator + mName;
// mContext.getDatabasePath(mName).getPath();
try {
db = SQLiteDatabase.openDatabase(path, mFactory, SQLiteDatabase.OPEN_READONLY);
} catch (RuntimeException e) {
Log.e(t, e.getMessage(), e);
String cardstatus = Environment.getExternalStorageState();
if (!cardstatus.equals(Environment.MEDIA_MOUNTED)) {
throw new RuntimeException(Collect.getInstance().getString(R.string.sdcard_unmounted, cardstatus));
} else {
throw e;
}
}
if (db.getVersion() != mNewVersion) {
throw new SQLiteException("Can't upgrade read-only database from version "
+ db.getVersion() + " to " + mNewVersion + ": " + path);
}
onOpen(db);
Log.w(t, "Opened " + mName + " in read-only mode");
mDatabase = db;
return mDatabase;
} finally {
mIsInitializing = false;
if (db != null && db != mDatabase)
db.close();
}
}
/**
* Close any open database object.
*/
public synchronized void close() {
if (mIsInitializing)
throw new IllegalStateException("Closed during initialization");
if (mDatabase != null && mDatabase.isOpen()) {
mDatabase.close();
mDatabase = null;
}
}
/**
* Called when the database is created for the first time. This is where the creation of tables
* and the initial population of the tables should happen.
*
* @param db The database.
*/
public abstract void onCreate(SQLiteDatabase db);
/**
* Called when the database needs to be upgraded. The implementation should use this method to
* drop tables, add tables, or do anything else it needs to upgrade to the new schema version.
* <p>
* The SQLite ALTER TABLE documentation can be found <a
* href="http://sqlite.org/lang_altertable.html">here</a>. If you add new columns you can use
* ALTER TABLE to insert them into a live table. If you rename or remove columns you can use
* ALTER TABLE to rename the old table, then create the new table and then populate the new
* table with the contents of the old table.
*
* @param db The database.
* @param oldVersion The old database version.
* @param newVersion The new database version.
*/
public abstract void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion);
/**
* Called when the database has been opened. Override method should check
* {@link SQLiteDatabase#isReadOnly} before updating the database.
*
* @param db The database.
*/
public void onOpen(SQLiteDatabase db) {
}
}
|
0nima0-f
|
src/org/odk/collect/android/database/ODKSQLiteOpenHelper.java
|
Java
|
asf20
| 10,410
|
/*
* Copyright (C) 2011 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.widgets;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.javarosa.core.model.SelectChoice;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.SelectMultiData;
import org.javarosa.core.model.data.helper.Selection;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryPrompt;
import org.javarosa.xpath.expr.XPathFuncExpr;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.external.ExternalDataUtil;
import org.odk.collect.android.external.ExternalSelectChoice;
import org.odk.collect.android.utilities.FileUtils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* ListMultiWidget handles multiple selection fields using check boxes. The check boxes are aligned
* horizontally. They are typically meant to be used in a field list, where multiple questions with
* the same multiple choice answers can sit on top of each other and make a grid of buttons that is
* easy to navigate quickly. Optionally, you can turn off the labels. This would be done if a label
* widget was at the top of your field list to provide the labels. If audio or video are specified
* in the select answers they are ignored. This class is almost identical to ListWidget, except it
* uses checkboxes. It also did not require a custom clickListener class.
*
* @author Jeff Beorse (jeff@beorse.net)
*/
public class ListMultiWidget extends QuestionWidget {
private static final String t = "ListMultiWidget";
// Holds the entire question and answers. It is a horizontally aligned linear layout
// needed because it is created in the super() constructor via addQuestionText() call.
LinearLayout questionLayout;
private boolean mCheckboxInit = true;
private List<SelectChoice> mItems; // may take a while to compute...
private ArrayList<CheckBox> mCheckboxes;
@SuppressWarnings("unchecked")
public ListMultiWidget(Context context, FormEntryPrompt prompt, boolean displayLabel) {
super(context, prompt);
// SurveyCTO-added support for dynamic select content (from .csv files)
XPathFuncExpr xPathFuncExpr = ExternalDataUtil.getSearchXPathExpression(prompt.getAppearanceHint());
if (xPathFuncExpr != null) {
mItems = ExternalDataUtil.populateExternalChoices(prompt, xPathFuncExpr);
} else {
mItems = prompt.getSelectChoices();
}
mCheckboxes = new ArrayList<CheckBox>();
mPrompt = prompt;
// Layout holds the horizontal list of buttons
LinearLayout buttonLayout = new LinearLayout(context);
List<Selection> ve = new ArrayList<Selection>();
if (prompt.getAnswerValue() != null) {
ve = (List<Selection>) prompt.getAnswerValue().getValue();
}
if (mItems != null) {
for (int i = 0; i < mItems.size(); i++) {
CheckBox c = new CheckBox(getContext());
c.setTag(Integer.valueOf(i));
c.setId(QuestionWidget.newUniqueId());
c.setFocusable(!prompt.isReadOnly());
c.setEnabled(!prompt.isReadOnly());
for (int vi = 0; vi < ve.size(); vi++) {
// match based on value, not key
if (mItems.get(i).getValue().equals(ve.get(vi).getValue())) {
c.setChecked(true);
break;
}
}
mCheckboxes.add(c);
// when clicked, check for readonly before toggling
c.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!mCheckboxInit && mPrompt.isReadOnly()) {
if (buttonView.isChecked()) {
buttonView.setChecked(false);
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onItemClick.deselect",
mItems.get((Integer)buttonView.getTag()).getValue(), mPrompt.getIndex());
} else {
buttonView.setChecked(true);
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onItemClick.select",
mItems.get((Integer)buttonView.getTag()).getValue(), mPrompt.getIndex());
}
}
}
});
String imageURI;
if (mItems.get(i) instanceof ExternalSelectChoice) {
imageURI = ((ExternalSelectChoice) mItems.get(i)).getImage();
} else {
imageURI = prompt.getSpecialFormSelectChoiceText(mItems.get(i), FormEntryCaption.TEXT_FORM_IMAGE);
}
// build image view (if an image is provided)
ImageView mImageView = null;
TextView mMissingImage = null;
final int labelId = QuestionWidget.newUniqueId();
// Now set up the image view
String errorMsg = null;
if (imageURI != null) {
try {
String imageFilename =
ReferenceManager._().DeriveReference(imageURI).getLocalURI();
final File imageFile = new File(imageFilename);
if (imageFile.exists()) {
Bitmap b = null;
try {
Display display =
((WindowManager) getContext().getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
b =
FileUtils.getBitmapScaledToDisplay(imageFile, screenHeight,
screenWidth);
} catch (OutOfMemoryError e) {
errorMsg = "ERROR: " + e.getMessage();
}
if (b != null) {
mImageView = new ImageView(getContext());
mImageView.setPadding(2, 2, 2, 2);
mImageView.setAdjustViewBounds(true);
mImageView.setImageBitmap(b);
mImageView.setId(labelId);
} else if (errorMsg == null) {
// An error hasn't been logged and loading the image failed, so it's
// likely
// a bad file.
errorMsg = getContext().getString(R.string.file_invalid, imageFile);
}
} else if (errorMsg == null) {
// An error hasn't been logged. We should have an image, but the file
// doesn't
// exist.
errorMsg = getContext().getString(R.string.file_missing, imageFile);
}
if (errorMsg != null) {
// errorMsg is only set when an error has occured
Log.e(t, errorMsg);
mMissingImage = new TextView(getContext());
mMissingImage.setText(errorMsg);
mMissingImage.setPadding(2, 2, 2, 2);
mMissingImage.setId(labelId);
}
} catch (InvalidReferenceException e) {
Log.e(t, "image invalid reference exception");
e.printStackTrace();
}
} else {
// There's no imageURI listed, so just ignore it.
}
// build text label. Don't assign the text to the built in label to he
// button because it aligns horizontally, and we want the label on top
TextView label = new TextView(getContext());
label.setText(prompt.getSelectChoiceText(mItems.get(i)));
label.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
label.setGravity(Gravity.CENTER_HORIZONTAL);
if (!displayLabel) {
label.setVisibility(View.GONE);
}
// answer layout holds the label text/image on top and the radio button on bottom
RelativeLayout answer = new RelativeLayout(getContext());
RelativeLayout.LayoutParams headerParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
headerParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
headerParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
RelativeLayout.LayoutParams buttonParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
buttonParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
if (mImageView != null) {
mImageView.setScaleType(ScaleType.CENTER);
if (!displayLabel) {
mImageView.setVisibility(View.GONE);
}
answer.addView(mImageView, headerParams);
} else if (mMissingImage != null) {
answer.addView(mMissingImage, headerParams);
} else {
if (displayLabel) {
label.setId(labelId);
answer.addView(label, headerParams);
}
}
if (displayLabel) {
buttonParams.addRule(RelativeLayout.BELOW, labelId);
}
answer.addView(c, buttonParams);
answer.setPadding(4, 0, 4, 0);
// /Each button gets equal weight
LinearLayout.LayoutParams answerParams =
new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
answerParams.weight = 1;
buttonLayout.addView(answer, answerParams);
}
}
// Align the buttons so that they appear horizonally and are right justified
// buttonLayout.setGravity(Gravity.RIGHT);
buttonLayout.setOrientation(LinearLayout.HORIZONTAL);
// LinearLayout.LayoutParams params = new
// LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// buttonLayout.setLayoutParams(params);
// The buttons take up the right half of the screen
LinearLayout.LayoutParams buttonParams =
new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
buttonParams.weight = 1;
questionLayout.addView(buttonLayout, buttonParams);
addView(questionLayout);
}
@Override
public void clearAnswer() {
for (int i = 0; i < mCheckboxes.size(); i++) {
CheckBox c = mCheckboxes.get(i);
if (c.isChecked()) {
c.setChecked(false);
}
}
}
@Override
public IAnswerData getAnswer() {
List<Selection> vc = new ArrayList<Selection>();
for (int i = 0; i < mCheckboxes.size(); i++) {
CheckBox c = mCheckboxes.get(i);
if (c.isChecked()) {
vc.add(new Selection(mItems.get(i)));
}
}
if (vc.size() == 0) {
return null;
} else {
return new SelectMultiData(vc);
}
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
// Override QuestionWidget's add question text. Build it the same
// but add it to the questionLayout
protected void addQuestionText(FormEntryPrompt p) {
// Add the text view. Textview always exists, regardless of whether there's text.
TextView questionText = new TextView(getContext());
questionText.setText(p.getLongText());
questionText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize);
questionText.setTypeface(null, Typeface.BOLD);
questionText.setPadding(0, 0, 0, 7);
questionText.setId(QuestionWidget.newUniqueId()); // assign random id
// Wrap to the size of the parent view
questionText.setHorizontallyScrolling(false);
if (p.getLongText() == null) {
questionText.setVisibility(GONE);
}
// Put the question text on the left half of the screen
LinearLayout.LayoutParams labelParams =
new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
labelParams.weight = 1;
questionLayout = new LinearLayout(getContext());
questionLayout.setOrientation(LinearLayout.HORIZONTAL);
questionLayout.addView(questionText, labelParams);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
for (CheckBox c : mCheckboxes) {
c.setOnLongClickListener(l);
}
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
for (CheckBox c : mCheckboxes) {
c.cancelLongPress();
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/ListMultiWidget.java
|
Java
|
asf20
| 15,487
|
/*
* Copyright (C) 2012 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.widgets;
import java.io.File;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.activities.DrawActivity;
import org.odk.collect.android.activities.FormEntryActivity;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.utilities.MediaUtils;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
* Signature widget.
*
* @author BehrAtherton@gmail.com
*
*/
public class SignatureWidget extends QuestionWidget implements IBinaryWidget {
private final static String t = "SignatureWidget";
private Button mSignButton;
private String mBinaryName;
private String mInstanceFolder;
private ImageView mImageView;
private TextView mErrorTextView;
public SignatureWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mInstanceFolder =
Collect.getInstance().getFormController().getInstancePath().getParent();
setOrientation(LinearLayout.VERTICAL);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
params.setMargins(7, 5, 7, 5);
mErrorTextView = new TextView(context);
mErrorTextView.setId(QuestionWidget.newUniqueId());
mErrorTextView.setText("Selected file is not a valid image");
// setup Blank Image Button
mSignButton = new Button(getContext());
mSignButton.setId(QuestionWidget.newUniqueId());
mSignButton.setText(getContext().getString(R.string.sign_button));
mSignButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mSignButton.setPadding(20, 20, 20, 20);
mSignButton.setEnabled(!prompt.isReadOnly());
mSignButton.setLayoutParams(params);
// launch capture intent on click
mSignButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "signButton", "click",
mPrompt.getIndex());
launchSignatureActivity();
}
});
// finish complex layout
addView(mSignButton);
addView(mErrorTextView);
// and hide the sign button if read-only
if ( prompt.isReadOnly() ) {
mSignButton.setVisibility(View.GONE);
}
mErrorTextView.setVisibility(View.GONE);
// retrieve answer from data model and update ui
mBinaryName = prompt.getAnswerText();
// Only add the imageView if the user has signed
if (mBinaryName != null) {
mImageView = new ImageView(getContext());
mImageView.setId(QuestionWidget.newUniqueId());
Display display =
((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
File f = new File(mInstanceFolder + File.separator + mBinaryName);
if (f.exists()) {
Bitmap bmp = FileUtils.getBitmapScaledToDisplay(f, screenHeight, screenWidth);
if (bmp == null) {
mErrorTextView.setVisibility(View.VISIBLE);
}
mImageView.setImageBitmap(bmp);
} else {
mImageView.setImageBitmap(null);
}
mImageView.setPadding(10, 10, 10, 10);
mImageView.setAdjustViewBounds(true);
mImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "viewImage",
"click", mPrompt.getIndex());
launchSignatureActivity();
}
});
addView(mImageView);
}
}
private void launchSignatureActivity() {
mErrorTextView.setVisibility(View.GONE);
Intent i = new Intent(getContext(), DrawActivity.class);
i.putExtra(DrawActivity.OPTION, DrawActivity.OPTION_SIGNATURE);
// copy...
if ( mBinaryName != null ) {
File f = new File(mInstanceFolder + File.separator + mBinaryName);
i.putExtra(DrawActivity.REF_IMAGE, Uri.fromFile(f));
}
i.putExtra(DrawActivity.EXTRA_OUTPUT,
Uri.fromFile(new File(Collect.TMPFILE_PATH)));
try {
Collect.getInstance().getFormController().setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i, FormEntryActivity.SIGNATURE_CAPTURE);
}
catch (ActivityNotFoundException e) {
Toast.makeText(getContext(),
getContext().getString(R.string.activity_not_found, "signature capture"),
Toast.LENGTH_SHORT).show();
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
}
private void deleteMedia() {
// get the file path and delete the file
String name = mBinaryName;
// clean up variables
mBinaryName = null;
// delete from media provider
int del = MediaUtils.deleteImageFileFromMediaProvider(mInstanceFolder + File.separator + name);
Log.i(t, "Deleted " + del + " rows from media content provider");
}
@Override
public void clearAnswer() {
// remove the file
deleteMedia();
mImageView.setImageBitmap(null);
mErrorTextView.setVisibility(View.GONE);
// reset buttons
mSignButton.setText(getContext().getString(R.string.sign_button));
}
@Override
public IAnswerData getAnswer() {
if (mBinaryName != null) {
return new StringData(mBinaryName.toString());
} else {
return null;
}
}
@Override
public void setBinaryData(Object answer) {
// you are replacing an answer. delete the previous image using the
// content provider.
if (mBinaryName != null) {
deleteMedia();
}
File newImage = (File) answer;
if (newImage.exists()) {
// Add the new image to the Media content provider so that the
// viewing is fast in Android 2.0+
ContentValues values = new ContentValues(6);
values.put(Images.Media.TITLE, newImage.getName());
values.put(Images.Media.DISPLAY_NAME, newImage.getName());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.Media.DATA, newImage.getAbsolutePath());
Uri imageURI = getContext().getContentResolver().insert(
Images.Media.EXTERNAL_CONTENT_URI, values);
Log.i(t, "Inserting image returned uri = " + imageURI.toString());
mBinaryName = newImage.getName();
Log.i(t, "Setting current answer to " + newImage.getName());
} else {
Log.e(t, "NO IMAGE EXISTS at: " + newImage.getAbsolutePath());
}
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
@Override
public boolean isWaitingForBinaryData() {
return mPrompt.getIndex().equals(Collect.getInstance().getFormController().getIndexWaitingForData());
}
@Override
public void cancelWaitingForBinaryData() {
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mSignButton.setOnLongClickListener(l);
if (mImageView != null) {
mImageView.setOnLongClickListener(l);
}
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mSignButton.cancelLongPress();
if (mImageView != null) {
mImageView.cancelLongPress();
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/SignatureWidget.java
|
Java
|
asf20
| 9,951
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.widgets;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.application.Collect;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.TextKeyListener;
import android.text.method.TextKeyListener.Capitalize;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TableLayout;
/**
* The most basic widget that allows for entry of any text.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class StringWidget extends QuestionWidget {
private static final String ROWS = "rows";
boolean mReadOnly = false;
protected EditText mAnswer;
public StringWidget(Context context, FormEntryPrompt prompt, boolean readOnlyOverride) {
this(context, prompt, readOnlyOverride, true);
setupChangeListener();
}
protected StringWidget(Context context, FormEntryPrompt prompt, boolean readOnlyOverride, boolean derived) {
super(context, prompt);
mAnswer = new EditText(context);
mAnswer.setId(QuestionWidget.newUniqueId());
mReadOnly = prompt.isReadOnly() || readOnlyOverride;
mAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
/**
* If a 'rows' attribute is on the input tag, set the minimum number of lines
* to display in the field to that value.
*
* I.e.,
* <input ref="foo" rows="5">
* ...
* </input>
*
* will set the height of the EditText box to 5 rows high.
*/
String height = prompt.getQuestion().getAdditionalAttribute(null, ROWS);
if ( height != null && height.length() != 0 ) {
try {
int rows = Integer.valueOf(height);
mAnswer.setMinLines(rows);
mAnswer.setGravity(Gravity.TOP); // to write test starting at the top of the edit area
} catch (Exception e) {
Log.e(this.getClass().getName(), "Unable to process the rows setting for the answer field: " + e.toString());
}
}
params.setMargins(7, 5, 7, 5);
mAnswer.setLayoutParams(params);
// capitalize the first letter of the sentence
mAnswer.setKeyListener(new TextKeyListener(Capitalize.SENTENCES, false));
// needed to make long read only text scroll
mAnswer.setHorizontallyScrolling(false);
mAnswer.setSingleLine(false);
String s = prompt.getAnswerText();
if (s != null) {
mAnswer.setText(s);
}
if (mReadOnly) {
mAnswer.setBackgroundDrawable(null);
mAnswer.setFocusable(false);
mAnswer.setClickable(false);
}
addView(mAnswer);
}
protected void setupChangeListener() {
mAnswer.addTextChangedListener(new TextWatcher() {
private String oldText = "";
@Override
public void afterTextChanged(Editable s) {
if (!s.toString().equals(oldText)) {
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "answerTextChanged", s.toString(), getPrompt().getIndex());
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
oldText = s.toString();
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) { }
});
}
@Override
public void clearAnswer() {
mAnswer.setText(null);
}
@Override
public IAnswerData getAnswer() {
clearFocus();
String s = mAnswer.getText().toString();
if (s == null || s.equals("")) {
return null;
} else {
return new StringData(s);
}
}
@Override
public void setFocus(Context context) {
// Put focus on text input field and display soft keyboard if appropriate.
mAnswer.requestFocus();
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (!mReadOnly) {
inputManager.showSoftInput(mAnswer, 0);
/*
* If you do a multi-question screen after a "add another group" dialog, this won't
* automatically pop up. It's an Android issue.
*
* That is, if I have an edit text in an activity, and pop a dialog, and in that
* dialog's button's OnClick() I call edittext.requestFocus() and
* showSoftInput(edittext, 0), showSoftinput() returns false. However, if the edittext
* is focused before the dialog pops up, everything works fine. great.
*/
} else {
inputManager.hideSoftInputFromWindow(mAnswer.getWindowToken(), 0);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.isAltPressed() == true) {
return false;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mAnswer.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mAnswer.cancelLongPress();
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/StringWidget.java
|
Java
|
asf20
| 6,247
|
/*
* Copyright (C) 2012 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.widgets;
import java.io.File;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.activities.DrawActivity;
import org.odk.collect.android.activities.FormEntryActivity;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.utilities.MediaUtils;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
* Free drawing widget.
*
* @author BehrAtherton@gmail.com
*
*/
public class DrawWidget extends QuestionWidget implements IBinaryWidget {
private final static String t = "DrawWidget";
private Button mDrawButton;
private String mBinaryName;
private String mInstanceFolder;
private ImageView mImageView;
private TextView mErrorTextView;
public DrawWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mErrorTextView = new TextView(context);
mErrorTextView.setId(QuestionWidget.newUniqueId());
mErrorTextView.setText("Selected file is not a valid image");
mInstanceFolder = Collect.getInstance().getFormController()
.getInstancePath().getParent();
setOrientation(LinearLayout.VERTICAL);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
params.setMargins(7, 5, 7, 5);
// setup Blank Image Button
mDrawButton = new Button(getContext());
mDrawButton.setId(QuestionWidget.newUniqueId());
mDrawButton.setText(getContext().getString(R.string.draw_image));
mDrawButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mDrawButton.setPadding(20, 20, 20, 20);
mDrawButton.setEnabled(!prompt.isReadOnly());
mDrawButton.setLayoutParams(params);
// launch capture intent on click
mDrawButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "drawButton", "click",
mPrompt.getIndex());
launchDrawActivity();
}
});
// finish complex layout
addView(mDrawButton);
addView(mErrorTextView);
if (mPrompt.isReadOnly()) {
mDrawButton.setVisibility(View.GONE);
}
mErrorTextView.setVisibility(View.GONE);
// retrieve answer from data model and update ui
mBinaryName = prompt.getAnswerText();
// Only add the imageView if the user has signed
if (mBinaryName != null) {
mImageView = new ImageView(getContext());
mImageView.setId(QuestionWidget.newUniqueId());
Display display = ((WindowManager) getContext().getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
File f = new File(mInstanceFolder + File.separator + mBinaryName);
if (f.exists()) {
Bitmap bmp = FileUtils.getBitmapScaledToDisplay(f,
screenHeight, screenWidth);
if (bmp == null) {
mErrorTextView.setVisibility(View.VISIBLE);
}
mImageView.setImageBitmap(bmp);
} else {
mImageView.setImageBitmap(null);
}
mImageView.setPadding(10, 10, 10, 10);
mImageView.setAdjustViewBounds(true);
mImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "viewImage", "click",
mPrompt.getIndex());
launchDrawActivity();
}
});
addView(mImageView);
}
}
private void launchDrawActivity() {
mErrorTextView.setVisibility(View.GONE);
Intent i = new Intent(getContext(), DrawActivity.class);
i.putExtra(DrawActivity.OPTION, DrawActivity.OPTION_DRAW);
// copy...
if (mBinaryName != null) {
File f = new File(mInstanceFolder + File.separator + mBinaryName);
i.putExtra(DrawActivity.REF_IMAGE, Uri.fromFile(f));
}
i.putExtra(DrawActivity.EXTRA_OUTPUT,
Uri.fromFile(new File(Collect.TMPFILE_PATH)));
try {
Collect.getInstance().getFormController()
.setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.DRAW_IMAGE);
} catch (ActivityNotFoundException e) {
Toast.makeText(
getContext(),
getContext().getString(R.string.activity_not_found,
"draw image"), Toast.LENGTH_SHORT).show();
Collect.getInstance().getFormController()
.setIndexWaitingForData(null);
}
}
private void deleteMedia() {
// get the file path and delete the file
String name = mBinaryName;
// clean up variables
mBinaryName = null;
// delete from media provider
int del = MediaUtils.deleteImageFileFromMediaProvider(mInstanceFolder
+ File.separator + name);
Log.i(t, "Deleted " + del + " rows from media content provider");
}
@Override
public void clearAnswer() {
// remove the file
deleteMedia();
mImageView.setImageBitmap(null);
mErrorTextView.setVisibility(View.GONE);
// reset buttons
mDrawButton.setText(getContext().getString(R.string.draw_image));
}
@Override
public IAnswerData getAnswer() {
if (mBinaryName != null) {
return new StringData(mBinaryName.toString());
} else {
return null;
}
}
@Override
public void setBinaryData(Object answer) {
// you are replacing an answer. delete the previous image using the
// content provider.
if (mBinaryName != null) {
deleteMedia();
}
File newImage = (File) answer;
if (newImage.exists()) {
// Add the new image to the Media content provider so that the
// viewing is fast in Android 2.0+
ContentValues values = new ContentValues(6);
values.put(Images.Media.TITLE, newImage.getName());
values.put(Images.Media.DISPLAY_NAME, newImage.getName());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.Media.DATA, newImage.getAbsolutePath());
Uri imageURI = getContext().getContentResolver().insert(
Images.Media.EXTERNAL_CONTENT_URI, values);
Log.i(t, "Inserting image returned uri = " + imageURI.toString());
mBinaryName = newImage.getName();
Log.i(t, "Setting current answer to " + newImage.getName());
} else {
Log.e(t, "NO IMAGE EXISTS at: " + newImage.getAbsolutePath());
}
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
@Override
public boolean isWaitingForBinaryData() {
return mPrompt.getIndex().equals(
Collect.getInstance().getFormController()
.getIndexWaitingForData());
}
@Override
public void cancelWaitingForBinaryData() {
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mDrawButton.setOnLongClickListener(l);
if (mImageView != null) {
mImageView.setOnLongClickListener(l);
}
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mDrawButton.cancelLongPress();
if (mImageView != null) {
mImageView.cancelLongPress();
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/DrawWidget.java
|
Java
|
asf20
| 8,861
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.widgets;
import java.util.Locale;
import org.javarosa.core.model.Constants;
import org.javarosa.form.api.FormEntryPrompt;
import android.content.Context;
import android.util.Log;
/**
* Convenience class that handles creation of widgets.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class WidgetFactory {
/**
* Returns the appropriate QuestionWidget for the given FormEntryPrompt.
*
* @param fep prompt element to be rendered
* @param context Android context
* @param readOnlyOverride a flag to be ORed with JR readonly attribute.
*/
static public QuestionWidget createWidgetFromPrompt(FormEntryPrompt fep, Context context, boolean readOnlyOverride) {
// get appearance hint and clean it up so it is lower case and never null...
String appearance = fep.getAppearanceHint();
if ( appearance == null ) appearance = "";
// for now, all appearance tags are in english...
appearance = appearance.toLowerCase(Locale.ENGLISH);
QuestionWidget questionWidget;
switch (fep.getControlType()) {
case Constants.CONTROL_INPUT:
switch (fep.getDataType()) {
case Constants.DATATYPE_DATE_TIME:
questionWidget = new DateTimeWidget(context, fep);
break;
case Constants.DATATYPE_DATE:
questionWidget = new DateWidget(context, fep);
break;
case Constants.DATATYPE_TIME:
questionWidget = new TimeWidget(context, fep);
break;
case Constants.DATATYPE_DECIMAL:
if ( appearance.startsWith("ex:") ) {
questionWidget = new ExDecimalWidget(context, fep);
} else if (appearance.equals("bearing")) {
questionWidget = new BearingWidget(context, fep);
} else {
questionWidget = new DecimalWidget(context, fep, readOnlyOverride);
}
break;
case Constants.DATATYPE_INTEGER:
if ( appearance.startsWith("ex:") ) {
questionWidget = new ExIntegerWidget(context, fep);
} else {
questionWidget = new IntegerWidget(context, fep, readOnlyOverride);
}
break;
case Constants.DATATYPE_GEOPOINT:
questionWidget = new GeoPointWidget(context, fep);
break;
case Constants.DATATYPE_BARCODE:
questionWidget = new BarcodeWidget(context, fep);
break;
case Constants.DATATYPE_TEXT:
String query = fep.getQuestion().getAdditionalAttribute(null, "query");
if (query != null) {
questionWidget = new ItemsetWidget(context, fep, readOnlyOverride);
} else if (appearance.startsWith("printer")) {
questionWidget = new ExPrinterWidget(context, fep);
} else if (appearance.startsWith("ex:")) {
questionWidget = new ExStringWidget(context, fep);
} else if (appearance.equals("numbers")) {
questionWidget = new StringNumberWidget(context, fep, readOnlyOverride);
} else if (appearance.equals("url")) {
questionWidget = new UrlWidget(context, fep);
} else {
questionWidget = new StringWidget(context, fep, readOnlyOverride);
}
break;
default:
questionWidget = new StringWidget(context, fep, readOnlyOverride);
break;
}
break;
case Constants.CONTROL_IMAGE_CHOOSE:
if (appearance.equals("web")) {
questionWidget = new ImageWebViewWidget(context, fep);
} else if(appearance.equals("signature")) {
questionWidget = new SignatureWidget(context, fep);
} else if(appearance.equals("annotate")) {
questionWidget = new AnnotateWidget(context, fep);
} else if(appearance.equals("draw")) {
questionWidget = new DrawWidget(context, fep);
} else if(appearance.startsWith("align:")) {
questionWidget = new AlignedImageWidget(context, fep);
} else {
questionWidget = new ImageWidget(context, fep);
}
break;
case Constants.CONTROL_AUDIO_CAPTURE:
questionWidget = new AudioWidget(context, fep);
break;
case Constants.CONTROL_VIDEO_CAPTURE:
questionWidget = new VideoWidget(context, fep);
break;
case Constants.CONTROL_SELECT_ONE:
// SurveyCTO-revised support for dynamic select content (from .csv files)
// consider traditional ODK appearance to be first word in appearance string
if (appearance.startsWith("compact") || appearance.startsWith("quickcompact")) {
int numColumns = -1;
try {
String firstWord = appearance.split("\\s+")[0];
int idx = firstWord.indexOf("-");
if ( idx != -1 ) {
numColumns =
Integer.parseInt(firstWord.substring(idx + 1));
}
} catch (Exception e) {
// Do nothing, leave numColumns as -1
Log.e("WidgetFactory", "Exception parsing numColumns");
}
if (appearance.startsWith("quick")) {
questionWidget = new GridWidget(context, fep, numColumns, true);
} else {
questionWidget = new GridWidget(context, fep, numColumns, false);
}
} else if (appearance.startsWith("minimal")) {
questionWidget = new SpinnerWidget(context, fep);
}
// else if (appearance != null && appearance.contains("autocomplete")) {
// String filterType = null;
// try {
// filterType = appearance.substring(appearance.indexOf('-') + 1);
// } catch (Exception e) {
// // Do nothing, leave filerType null
// Log.e("WidgetFactory", "Exception parsing filterType");
// }
// questionWidget = new AutoCompleteWidget(context, fep, filterType);
//
// }
else if (appearance.startsWith("quick")) {
questionWidget = new SelectOneAutoAdvanceWidget(context, fep);
} else if (appearance.equals("list-nolabel")) {
questionWidget = new ListWidget(context, fep, false);
} else if (appearance.equals("list")) {
questionWidget = new ListWidget(context, fep, true);
} else if (appearance.equals("label")) {
questionWidget = new LabelWidget(context, fep);
} else {
questionWidget = new SelectOneWidget(context, fep);
}
break;
case Constants.CONTROL_SELECT_MULTI:
// SurveyCTO-revised support for dynamic select content (from .csv files)
// consider traditional ODK appearance to be first word in appearance string
if (appearance.startsWith("compact")) {
int numColumns = -1;
try {
String firstWord = appearance.split("\\s+")[0];
int idx = firstWord.indexOf("-");
if ( idx != -1 ) {
numColumns =
Integer.parseInt(firstWord.substring(idx + 1));
}
} catch (Exception e) {
// Do nothing, leave numColumns as -1
Log.e("WidgetFactory", "Exception parsing numColumns");
}
questionWidget = new GridMultiWidget(context, fep, numColumns);
} else if (appearance.startsWith("minimal")) {
questionWidget = new SpinnerMultiWidget(context, fep);
} else if (appearance.startsWith("list-nolabel")) {
questionWidget = new ListMultiWidget(context, fep, false);
} else if (appearance.startsWith("list")) {
questionWidget = new ListMultiWidget(context, fep, true);
} else if (appearance.startsWith("label")) {
questionWidget = new LabelWidget(context, fep);
} else {
questionWidget = new SelectMultiWidget(context, fep);
}
break;
case Constants.CONTROL_TRIGGER:
questionWidget = new TriggerWidget(context, fep);
break;
default:
questionWidget = new StringWidget(context, fep, readOnlyOverride);
break;
}
return questionWidget;
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/WidgetFactory.java
|
Java
|
asf20
| 10,271
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.widgets;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import org.javarosa.core.model.FormDef;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.core.model.instance.TreeElement;
import org.javarosa.form.api.FormEntryPrompt;
import org.javarosa.xpath.XPathNodeset;
import org.javarosa.xpath.XPathParseTool;
import org.javarosa.xpath.expr.XPathExpression;
import org.javarosa.xpath.parser.XPathSyntaxException;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.database.ItemsetDbAdapter;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.view.KeyEvent;
import android.view.inputmethod.InputMethodManager;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
/**
* The most basic widget that allows for entry of any text.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class ItemsetWidget extends QuestionWidget implements
android.widget.CompoundButton.OnCheckedChangeListener {
private static String tag = "ItemsetWidget";
boolean mReadOnly;
protected RadioGroup mButtons;
private String mAnswer = null;
// Hashmap linking label:value
private HashMap<String, String> mAnswers;
public ItemsetWidget(Context context, FormEntryPrompt prompt, boolean readOnlyOverride) {
this(context, prompt, readOnlyOverride, true);
}
protected ItemsetWidget(Context context, FormEntryPrompt prompt, boolean readOnlyOverride,
boolean derived) {
super(context, prompt);
mButtons = new RadioGroup(context);
mButtons.setId(QuestionWidget.newUniqueId());
mReadOnly = prompt.isReadOnly() || readOnlyOverride;
mAnswers = new HashMap<String, String>();
String currentAnswer = prompt.getAnswerText();
// the format of the query should be something like this:
// query="instance('cities')/root/item[state=/data/state and county=/data/county]"
// "query" is what we're using to notify that this is an
// itemset widget.
String nodesetStr = prompt.getQuestion().getAdditionalAttribute(null, "query");
// parse out the list name, between the ''
String list_name = nodesetStr.substring(nodesetStr.indexOf("'") + 1,
nodesetStr.lastIndexOf("'"));
// isolate the string between between the [ ] characters
String queryString = nodesetStr.substring(nodesetStr.indexOf("[") + 1,
nodesetStr.lastIndexOf("]"));
StringBuilder selection = new StringBuilder();
// add the list name as the first argument, which will always be there
selection.append("list_name=?");
// check to see if there are any arguments
if (queryString.indexOf("=") != -1) {
selection.append(" and ");
}
// can't just split on 'and' or 'or' because they have different
// behavior, so loop through and break them off until we don't have any
// more
// must include the spaces in indexOf so we don't match words like
// "land"
int andIndex = -1;
int orIndex = -1;
ArrayList<String> arguments = new ArrayList<String>();
while ((andIndex = queryString.indexOf(" and ")) != -1
|| (orIndex = queryString.indexOf(" or ")) != -1) {
if (andIndex != -1) {
String subString = queryString.substring(0, andIndex);
String pair[] = subString.split("=");
if (pair.length == 2) {
selection.append(pair[0].trim() + "=? and ");
arguments.add(pair[1].trim());
} else {
// parse error
}
// move string forward to after " and "
queryString = queryString.substring(andIndex + 5, queryString.length());
andIndex = -1;
} else if (orIndex != -1) {
String subString = queryString.substring(0, orIndex);
String pair[] = subString.split("=");
if (pair.length == 2) {
selection.append(pair[0].trim() + "=? or ");
arguments.add(pair[1].trim());
} else {
// parse error
}
// move string forward to after " or "
queryString = queryString.substring(orIndex + 4, queryString.length());
orIndex = -1;
}
}
// parse the last segment (or only segment if there are no 'and' or 'or'
// clauses
String pair[] = queryString.split("=");
if (pair.length == 2) {
selection.append(pair[0].trim() + "=?");
arguments.add(pair[1].trim());
}
if (pair.length == 1) {
// this is probably okay, because then you just list all items in
// the list
} else {
// parse error
}
// +1 is for the list_name
String[] selectionArgs = new String[arguments.size() + 1];
boolean nullArgs = false; // can't have any null arguments
selectionArgs[0] = list_name; // first argument is always listname
// loop through the arguments, evaluate any expressions
// and build the query string for the DB
for (int i = 0; i < arguments.size(); i++) {
XPathExpression xpr = null;
try {
xpr = XPathParseTool.parseXPath(arguments.get(i));
} catch (XPathSyntaxException e) {
e.printStackTrace();
TextView error = new TextView(context);
error.setText("XPathParser Exception: \"" + arguments.get(i) + "\"");
addView(error);
break;
}
if (xpr != null) {
FormDef form = Collect.getInstance().getFormController().getFormDef();
TreeElement mTreeElement = form.getMainInstance().resolveReference(prompt.getIndex().getReference());
EvaluationContext ec = new EvaluationContext(form.getEvaluationContext(),
mTreeElement.getRef());
Object value = xpr.eval(form.getMainInstance(), ec);
if (value == null) {
nullArgs = true;
} else {
if (value instanceof XPathNodeset) {
XPathNodeset xpn = (XPathNodeset) value;
value = xpn.getValAt(0);
}
selectionArgs[i + 1] = value.toString();
}
}
}
File itemsetFile = new File(Collect.getInstance().getFormController().getMediaFolder().getAbsolutePath() + "/itemsets.csv");
if (nullArgs) {
// we can't try to query with null values else it blows up
// so just leave the screen blank
// TODO: put an error?
} else if (itemsetFile.exists()) {
ItemsetDbAdapter ida = new ItemsetDbAdapter();
ida.open();
// name of the itemset table for this form
String pathHash = ItemsetDbAdapter.getMd5FromString(itemsetFile.getAbsolutePath());
try {
Cursor c = ida.query(pathHash, selection.toString(), selectionArgs);
if (c != null) {
c.move(-1);
while (c.moveToNext()) {
String label = "";
String val = "";
// try to get the value associated with the label:lang
// string if that doen't exist, then just use label
String lang = "";
if (Collect.getInstance().getFormController().getLanguages() != null
&& Collect.getInstance().getFormController().getLanguages().length > 0) {
lang = Collect.getInstance().getFormController().getLanguage();
}
// apparently you only need the double quotes in the
// column name when creating the column with a :
// included
String labelLang = "label" + "::" + lang;
int langCol = c.getColumnIndex(labelLang);
if (langCol == -1) {
label = c.getString(c.getColumnIndex("label"));
} else {
label = c.getString(c.getColumnIndex(labelLang));
}
// the actual value is stored in name
val = c.getString(c.getColumnIndex("name"));
mAnswers.put(label, val);
RadioButton rb = new RadioButton(context);
rb.setOnCheckedChangeListener(this);
rb.setText(label);
rb.setTextSize(mAnswerFontsize);
mButtons.addView(rb);
// have to add it to the radiogroup before checking it,
// else it lets two buttons be checked...
if (currentAnswer != null
&& val.compareTo(currentAnswer) == 0) {
rb.setChecked(true);
}
}
c.close();
}
} finally {
ida.close();
}
addView(mButtons);
} else {
TextView error = new TextView(context);
error.setText(getContext().getString(R.string.file_missing, itemsetFile.getAbsolutePath()));
addView(error);
}
}
@Override
public void clearAnswer() {
mButtons.clearCheck();
mAnswer = null;
}
@Override
public IAnswerData getAnswer() {
if (mAnswer == null) {
return null;
} else {
return new StringData(mAnswer);
}
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.isAltPressed() == true) {
return false;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mButtons.setOnLongClickListener(l);
for (int i = 0; i < mButtons.getChildCount(); i++) {
mButtons.getChildAt(i).setOnLongClickListener(l);
}
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mButtons.cancelLongPress();
for (int i = 0; i < mButtons.getChildCount(); i++) {
mButtons.getChildAt(i).cancelLongPress();
}
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mAnswer = mAnswers.get((String) buttonView.getText());
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/ItemsetWidget.java
|
Java
|
asf20
| 12,301
|
/*
* Copyright (C) 2013 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.widgets;
import java.io.File;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.activities.FormEntryActivity;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.utilities.MediaUtils;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
* Widget that allows user to invoke the aligned-image camera to take pictures and add them to the form.
* Modified to launch the Aligned-image camera app.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
* @author mitchellsundt@gmail.com
* @author Mitchell Tyler Lee
*/
public class AlignedImageWidget extends QuestionWidget implements IBinaryWidget {
private static final String ODK_CAMERA_TAKE_PICTURE_INTENT_COMPONENT = "org.opendatakit.camera.TakePicture";
private static final String ODK_CAMERA_INTENT_PACKAGE = "org.opendatakit.camera";
private static final String RETAKE_OPTION_EXTRA = "retakeOption";
private static final String DIMENSIONS_EXTRA = "dimensions";
private static final String FILE_PATH_EXTRA = "filePath";
private final static String t = "AlignedImageWidget";
private Button mCaptureButton;
private Button mChooseButton;
private ImageView mImageView;
private String mBinaryName;
private String mInstanceFolder;
private TextView mErrorTextView;
private int iArray[] = new int[6];
public AlignedImageWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
String appearance = prompt.getAppearanceHint();
String alignments = appearance.substring(appearance.indexOf(":") + 1);
String[] splits = alignments.split(" ");
if ( splits.length != 6 ) {
Log.w(t, "Only have " + splits.length + " alignment values");
}
for ( int i = 0 ; i < 6 ; ++i ) {
if ( splits.length < i ) {
iArray[i] = 0;
} else {
iArray[i] = Integer.valueOf(splits[i]);
}
}
mInstanceFolder =
Collect.getInstance().getFormController().getInstancePath().getParent();
setOrientation(LinearLayout.VERTICAL);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
params.setMargins(7, 5, 7, 5);
mErrorTextView = new TextView(context);
mErrorTextView.setId(QuestionWidget.newUniqueId());
mErrorTextView.setText("Selected file is not a valid image");
// setup capture button
mCaptureButton = new Button(getContext());
mCaptureButton.setId(QuestionWidget.newUniqueId());
mCaptureButton.setText(getContext().getString(R.string.capture_image));
mCaptureButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mCaptureButton.setPadding(20, 20, 20, 20);
mCaptureButton.setEnabled(!prompt.isReadOnly());
mCaptureButton.setLayoutParams(params);
// launch capture intent on click
mCaptureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "captureButton",
"click", mPrompt.getIndex());
mErrorTextView.setVisibility(View.GONE);
Intent i = new Intent();
i.setComponent(new ComponentName(ODK_CAMERA_INTENT_PACKAGE,
ODK_CAMERA_TAKE_PICTURE_INTENT_COMPONENT));
i.putExtra(FILE_PATH_EXTRA, Collect.CACHE_PATH);
i.putExtra(DIMENSIONS_EXTRA, iArray);
i.putExtra(RETAKE_OPTION_EXTRA, false);
// We give the camera an absolute filename/path where to put the
// picture because of bug:
// http://code.google.com/p/android/issues/detail?id=1480
// The bug appears to be fixed in Android 2.0+, but as of feb 2,
// 2010, G1 phones only run 1.6. Without specifying the path the
// images returned by the camera in 1.6 (and earlier) are ~1/4
// the size. boo.
// if this gets modified, the onActivityResult in
// FormEntyActivity will also need to be updated.
try {
Collect.getInstance().getFormController().setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.ALIGNED_IMAGE);
} catch (ActivityNotFoundException e) {
Toast.makeText(getContext(),
getContext().getString(R.string.activity_not_found, "aligned image capture"),
Toast.LENGTH_SHORT).show();
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
}
});
// setup chooser button
mChooseButton = new Button(getContext());
mChooseButton.setId(QuestionWidget.newUniqueId());
mChooseButton.setText(getContext().getString(R.string.choose_image));
mChooseButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mChooseButton.setPadding(20, 20, 20, 20);
mChooseButton.setEnabled(!prompt.isReadOnly());
mChooseButton.setLayoutParams(params);
// launch capture intent on click
mChooseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "chooseButton",
"click", mPrompt.getIndex());
mErrorTextView.setVisibility(View.GONE);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("image/*");
try {
Collect.getInstance().getFormController()
.setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.IMAGE_CHOOSER);
} catch (ActivityNotFoundException e) {
Toast.makeText(getContext(),
getContext().getString(R.string.activity_not_found, "choose image"),
Toast.LENGTH_SHORT).show();
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
}
});
// finish complex layout
addView(mCaptureButton);
addView(mChooseButton);
addView(mErrorTextView);
// and hide the capture and choose button if read-only
if ( prompt.isReadOnly() ) {
mCaptureButton.setVisibility(View.GONE);
mChooseButton.setVisibility(View.GONE);
}
mErrorTextView.setVisibility(View.GONE);
// retrieve answer from data model and update ui
mBinaryName = prompt.getAnswerText();
// Only add the imageView if the user has taken a picture
if (mBinaryName != null) {
mImageView = new ImageView(getContext());
mImageView.setId(QuestionWidget.newUniqueId());
Display display =
((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
File f = new File(mInstanceFolder + File.separator + mBinaryName);
if (f.exists()) {
Bitmap bmp = FileUtils.getBitmapScaledToDisplay(f, screenHeight, screenWidth);
if (bmp == null) {
mErrorTextView.setVisibility(View.VISIBLE);
}
mImageView.setImageBitmap(bmp);
} else {
mImageView.setImageBitmap(null);
}
mImageView.setPadding(10, 10, 10, 10);
mImageView.setAdjustViewBounds(true);
mImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "viewButton",
"click", mPrompt.getIndex());
Intent i = new Intent("android.intent.action.VIEW");
Uri uri = MediaUtils.getImageUriFromMediaProvider(mInstanceFolder + File.separator + mBinaryName);
if ( uri != null ) {
Log.i(t,"setting view path to: " + uri);
i.setDataAndType(uri, "image/*");
try {
getContext().startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(getContext(),
getContext().getString(R.string.activity_not_found, "view image"),
Toast.LENGTH_SHORT).show();
}
}
}
});
addView(mImageView);
}
}
private void deleteMedia() {
// get the file path and delete the file
String name = mBinaryName;
// clean up variables
mBinaryName = null;
// delete from media provider
int del = MediaUtils.deleteImageFileFromMediaProvider(mInstanceFolder + File.separator + name);
Log.i(t, "Deleted " + del + " rows from media content provider");
}
@Override
public void clearAnswer() {
// remove the file
deleteMedia();
mImageView.setImageBitmap(null);
mErrorTextView.setVisibility(View.GONE);
// reset buttons
mCaptureButton.setText(getContext().getString(R.string.capture_image));
}
@Override
public IAnswerData getAnswer() {
if (mBinaryName != null) {
return new StringData(mBinaryName.toString());
} else {
return null;
}
}
@Override
public void setBinaryData(Object newImageObj) {
// you are replacing an answer. delete the previous image using the
// content provider.
if (mBinaryName != null) {
deleteMedia();
}
File newImage = (File) newImageObj;
if (newImage.exists()) {
// Add the new image to the Media content provider so that the
// viewing is fast in Android 2.0+
ContentValues values = new ContentValues(6);
values.put(Images.Media.TITLE, newImage.getName());
values.put(Images.Media.DISPLAY_NAME, newImage.getName());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.Media.DATA, newImage.getAbsolutePath());
Uri imageURI = getContext().getContentResolver().insert(
Images.Media.EXTERNAL_CONTENT_URI, values);
Log.i(t, "Inserting image returned uri = " + imageURI.toString());
mBinaryName = newImage.getName();
Log.i(t, "Setting current answer to " + newImage.getName());
} else {
Log.e(t, "NO IMAGE EXISTS at: " + newImage.getAbsolutePath());
}
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
@Override
public boolean isWaitingForBinaryData() {
return mPrompt.getIndex().equals(Collect.getInstance().getFormController().getIndexWaitingForData());
}
@Override
public void cancelWaitingForBinaryData() {
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mCaptureButton.setOnLongClickListener(l);
mChooseButton.setOnLongClickListener(l);
if (mImageView != null) {
mImageView.setOnLongClickListener(l);
}
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mCaptureButton.cancelLongPress();
mChooseButton.cancelLongPress();
if (mImageView != null) {
mImageView.cancelLongPress();
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/AlignedImageWidget.java
|
Java
|
asf20
| 14,066
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.widgets;
/**
* Interface implemented by widgets that need binary data.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public interface IBinaryWidget {
public void setBinaryData(Object answer);
public void cancelWaitingForBinaryData();
public boolean isWaitingForBinaryData();
}
/*TODO carlhartung: we might want to move this into the QuestionWidget abstract class?
*
*/
|
0nima0-f
|
src/org/odk/collect/android/widgets/IBinaryWidget.java
|
Java
|
asf20
| 1,037
|
/*
* Copyright (C) 2011 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.widgets;
import java.util.ArrayList;
import java.util.List;
import org.javarosa.core.model.SelectChoice;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.SelectMultiData;
import org.javarosa.core.model.data.helper.Selection;
import org.javarosa.form.api.FormEntryPrompt;
import org.javarosa.xpath.expr.XPathFuncExpr;
import org.odk.collect.android.R;
import org.odk.collect.android.external.ExternalDataUtil;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.TypedValue;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;
/**
* SpinnerMultiWidget, like SelectMultiWidget handles multiple selection fields using checkboxes,
* but the user clicks a button to see the checkboxes. The goal is to be more compact. If images,
* audio, or video are specified in the select answers they are ignored. WARNING: There is a bug in
* android versions previous to 2.0 that affects this widget. You can find the report here:
* http://code.google.com/p/android/issues/detail?id=922 This bug causes text to be white in alert
* boxes, which makes the select options invisible in this widget. For this reason, this widget
* should not be used on phones with android versions lower than 2.0.
*
* @author Jeff Beorse (jeff@beorse.net)
*/
public class SpinnerMultiWidget extends QuestionWidget {
List<SelectChoice> mItems;
// The possible select answers
CharSequence[] answer_items;
// The button to push to display the answers to choose from
Button button;
// Defines which answers are selected
boolean[] selections;
// The alert box that contains the answer selection view
AlertDialog.Builder alert_builder;
// Displays the current selections below the button
TextView selectionText;
@SuppressWarnings("unchecked")
public SpinnerMultiWidget(final Context context, FormEntryPrompt prompt) {
super(context, prompt);
// SurveyCTO-added support for dynamic select content (from .csv files)
XPathFuncExpr xPathFuncExpr = ExternalDataUtil.getSearchXPathExpression(prompt.getAppearanceHint());
if (xPathFuncExpr != null) {
mItems = ExternalDataUtil.populateExternalChoices(prompt, xPathFuncExpr);
} else {
mItems = prompt.getSelectChoices();
}
mPrompt = prompt;
selections = new boolean[mItems.size()];
answer_items = new CharSequence[mItems.size()];
alert_builder = new AlertDialog.Builder(context);
button = new Button(context);
selectionText = new TextView(getContext());
// Build View
for (int i = 0; i < mItems.size(); i++) {
answer_items[i] = prompt.getSelectChoiceText(mItems.get(i));
}
selectionText.setText(context.getString(R.string.selected));
selectionText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize);
selectionText.setVisibility(View.GONE);
button.setText(context.getString(R.string.select_answer));
button.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize);
button.setPadding(0, 0, 0, 7);
// Give the button a click listener. This defines the alert as well. All the
// click and selection behavior is defined here.
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
alert_builder.setTitle(mPrompt.getQuestionText()).setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
boolean first = true;
selectionText.setText("");
for (int i = 0; i < selections.length; i++) {
if (selections[i]) {
if (first) {
first = false;
selectionText.setText(context.getString(R.string.selected)
+ answer_items[i].toString());
selectionText.setVisibility(View.VISIBLE);
} else {
selectionText.setText(selectionText.getText() + ", "
+ answer_items[i].toString());
}
}
}
}
});
alert_builder.setMultiChoiceItems(answer_items, selections,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
selections[which] = isChecked;
}
});
AlertDialog alert = alert_builder.create();
alert.show();
}
});
// Fill in previous answers
List<Selection> ve = new ArrayList<Selection>();
if (prompt.getAnswerValue() != null) {
ve = (List<Selection>) prompt.getAnswerValue().getValue();
}
if (ve != null) {
boolean first = true;
for (int i = 0; i < selections.length; ++i) {
String value = mItems.get(i).getValue();
boolean found = false;
for (Selection s : ve) {
if (value.equals(s.getValue())) {
found = true;
break;
}
}
selections[i] = found;
if (found) {
if (first) {
first = false;
selectionText.setText(context.getString(R.string.selected)
+ answer_items[i].toString());
selectionText.setVisibility(View.VISIBLE);
} else {
selectionText.setText(selectionText.getText() + ", "
+ answer_items[i].toString());
}
}
}
}
addView(button);
addView(selectionText);
}
@Override
public IAnswerData getAnswer() {
clearFocus();
List<Selection> vc = new ArrayList<Selection>();
for (int i = 0; i < mItems.size(); i++) {
if (selections[i]) {
SelectChoice sc = mItems.get(i);
vc.add(new Selection(sc));
}
}
if (vc.size() == 0) {
return null;
} else {
return new SelectMultiData(vc);
}
}
@Override
public void clearAnswer() {
selectionText.setText(R.string.selected);
selectionText.setVisibility(View.GONE);
for (int i = 0; i < selections.length; i++) {
selections[i] = false;
}
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
button.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
button.cancelLongPress();
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/SpinnerMultiWidget.java
|
Java
|
asf20
| 8,467
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.widgets;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.form.api.FormEntryPrompt;
import android.content.Context;
import android.text.InputType;
import android.text.method.DigitsKeyListener;
import android.util.TypedValue;
/**
* Widget that restricts values to integers.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class StringNumberWidget extends StringWidget {
public StringNumberWidget(Context context, FormEntryPrompt prompt, boolean readOnlyOverride) {
super(context, prompt, readOnlyOverride, true);
mAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mAnswer.setInputType(InputType.TYPE_NUMBER_FLAG_SIGNED);
// needed to make long readonly text scroll
mAnswer.setHorizontallyScrolling(false);
mAnswer.setSingleLine(false);
mAnswer.setKeyListener(new DigitsKeyListener() {
@Override
protected char[] getAcceptedChars() {
char[] accepted = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '-', '+', ' ', ','
};
return accepted;
}
});
if (prompt.isReadOnly()) {
setBackgroundDrawable(null);
setFocusable(false);
setClickable(false);
}
String s = null;
if (prompt.getAnswerValue() != null)
s = (String) prompt.getAnswerValue().getValue();
if (s != null) {
mAnswer.setText(s);
}
setupChangeListener();
}
@Override
public IAnswerData getAnswer() {
clearFocus();
String s = mAnswer.getText().toString();
if (s == null || s.equals("")) {
return null;
} else {
try {
return new StringData(s);
} catch (Exception NumberFormatException) {
return null;
}
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/StringNumberWidget.java
|
Java
|
asf20
| 2,651
|
/*
* Copyright (C) 2012 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.widgets;
import java.util.Map;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.activities.FormEntryActivity;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.exception.ExternalParamsException;
import org.odk.collect.android.external.ExternalAppsUtils;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.method.TextKeyListener;
import android.text.method.TextKeyListener.Capitalize;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.Toast;
/**
* <p>Launch an external app to supply a string value. If the app
* does not launch, enable the text area for regular data entry.</p>
*
* <p>The default button text is "Launch"
*
* <p>You may override the button text and the error text that is
* displayed when the app is missing by using jr:itext() values.
*
* <p>To use this widget, define an appearance on the <input/>
* tag that begins "ex:" and then contains the intent action to lauch.
*
* <p>e.g.,
*
* <pre>
* <input appearance="ex:change.uw.android.TEXTANSWER" ref="/form/passPhrase" >
* </pre>
* <p>or, to customize the button text and error strings with itext:
* <pre>
* ...
* <bind nodeset="/form/passPhrase" type="string" />
* ...
* <itext>
* <translation lang="English">
* <text id="textAnswer">
* <value form="short">Text question</value>
* <value form="long">Enter your pass phrase</value>
* <value form="buttonText">Get Pass Phrase</value>
* <value form="noAppErrorString">Pass Phrase Tool is not installed!
* Please proceed to manually enter pass phrase.</value>
* </text>
* </translation>
* </itext>
* ...
* <input appearance="ex:change.uw.android.TEXTANSWER" ref="/form/passPhrase">
* <label ref="jr:itext('textAnswer')"/>
* </input>
* </pre>
*
* @author mitchellsundt@gmail.com
*
*/
public class ExStringWidget extends QuestionWidget implements IBinaryWidget {
private final String t = getClass().getName();
private boolean mHasExApp = true;
private Button mLaunchIntentButton;
private Drawable mTextBackground;
protected EditText mAnswer;
public ExStringWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
params.setMargins(7, 5, 7, 5);
// set text formatting
mAnswer = new EditText(context);
mAnswer.setId(QuestionWidget.newUniqueId());
mAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mAnswer.setLayoutParams(params);
mTextBackground = mAnswer.getBackground();
mAnswer.setBackgroundDrawable(null);
// capitalize nothing
mAnswer.setKeyListener(new TextKeyListener(Capitalize.NONE, false));
// needed to make long read only text scroll
mAnswer.setHorizontallyScrolling(false);
mAnswer.setSingleLine(false);
String s = prompt.getAnswerText();
if (s != null) {
mAnswer.setText(s);
}
if (mPrompt.isReadOnly()) {
mAnswer.setBackgroundDrawable(null);
}
if (mPrompt.isReadOnly() || mHasExApp) {
mAnswer.setFocusable(false);
mAnswer.setClickable(false);
}
String appearance = prompt.getAppearanceHint();
String[] attrs = appearance.split(":");
final String intentName = ExternalAppsUtils.extractIntentName(attrs[1]);
final Map<String, String> exParams = ExternalAppsUtils.extractParameters(attrs[1]);
final String buttonText;
final String errorString;
String v = mPrompt.getSpecialFormQuestionText("buttonText");
buttonText = (v != null) ? v : context.getString(R.string.launch_app);
v = mPrompt.getSpecialFormQuestionText("noAppErrorString");
errorString = (v != null) ? v : context.getString(R.string.no_app);
// set button formatting
mLaunchIntentButton = new Button(getContext());
mLaunchIntentButton.setId(QuestionWidget.newUniqueId());
mLaunchIntentButton.setText(buttonText);
mLaunchIntentButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mLaunchIntentButton.setPadding(20, 20, 20, 20);
mLaunchIntentButton.setEnabled(!mPrompt.isReadOnly());
mLaunchIntentButton.setLayoutParams(params);
mLaunchIntentButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(intentName);
try {
ExternalAppsUtils.populateParameters(i, exParams, mPrompt.getIndex().getReference());
Collect.getInstance().getFormController().setIndexWaitingForData(mPrompt.getIndex());
fireActivity(i);
} catch (ExternalParamsException e) {
Log.e(t, e.getMessage(), e);
onException(e.getMessage());
} catch (ActivityNotFoundException e) {
Log.e(t, e.getMessage(), e);
onException(errorString);
}
}
private void onException(String toastText) {
mHasExApp = false;
if ( !mPrompt.isReadOnly() ) {
mAnswer.setBackgroundDrawable(mTextBackground);
mAnswer.setFocusable(true);
mAnswer.setFocusableInTouchMode(true);
mAnswer.setClickable(true);
}
mLaunchIntentButton.setEnabled(false);
mLaunchIntentButton.setFocusable(false);
Collect.getInstance().getFormController().setIndexWaitingForData(null);
Toast.makeText(getContext(),
toastText, Toast.LENGTH_SHORT)
.show();
ExStringWidget.this.mAnswer.requestFocus();
}
});
// finish complex layout
addView(mLaunchIntentButton);
addView(mAnswer);
}
protected void fireActivity(Intent i) throws ActivityNotFoundException {
i.putExtra("value", mPrompt.getAnswerText());
Collect.getInstance().getActivityLogger().logInstanceAction(this, "launchIntent",
i.getAction(), mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.EX_STRING_CAPTURE);
}
@Override
public void clearAnswer() {
mAnswer.setText(null);
}
@Override
public IAnswerData getAnswer() {
String s = mAnswer.getText().toString();
if (s == null || s.equals("")) {
return null;
} else {
return new StringData(s);
}
}
/**
* Allows answer to be set externally in {@Link FormEntryActivity}.
*/
@Override
public void setBinaryData(Object answer) {
StringData stringData = ExternalAppsUtils.asStringData(answer);
mAnswer.setText(stringData == null ? null : stringData.getValue().toString());
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setFocus(Context context) {
// Put focus on text input field and display soft keyboard if appropriate.
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if ( mHasExApp ) {
// hide keyboard
inputManager.hideSoftInputFromWindow(mAnswer.getWindowToken(), 0);
// focus on launch button
mLaunchIntentButton.requestFocus();
} else {
if (!mPrompt.isReadOnly()) {
mAnswer.requestFocus();
inputManager.showSoftInput(mAnswer, 0);
/*
* If you do a multi-question screen after a "add another group" dialog, this won't
* automatically pop up. It's an Android issue.
*
* That is, if I have an edit text in an activity, and pop a dialog, and in that
* dialog's button's OnClick() I call edittext.requestFocus() and
* showSoftInput(edittext, 0), showSoftinput() returns false. However, if the edittext
* is focused before the dialog pops up, everything works fine. great.
*/
} else {
inputManager.hideSoftInputFromWindow(mAnswer.getWindowToken(), 0);
}
}
}
@Override
public boolean isWaitingForBinaryData() {
return mPrompt.getIndex().equals(Collect.getInstance().getFormController().getIndexWaitingForData());
}
@Override
public void cancelWaitingForBinaryData() {
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.isAltPressed() == true) {
return false;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mAnswer.setOnLongClickListener(l);
mLaunchIntentButton.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mAnswer.cancelLongPress();
mLaunchIntentButton.cancelLongPress();
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/ExStringWidget.java
|
Java
|
asf20
| 10,713
|
/*
* Copyright (C) 2012 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.widgets;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.Toast;
/**
* <p>Use the ODK Sensors framework to print data to a connected printer.</p>
*
* <p>The default button text is "Print Label"
*
* <p>You may override the button text and the error text that is
* displayed when the app is missing by using jr:itext() values. The
* special itext form values are 'buttonText' and 'noPrinterErrorString',
* respectively.</p>
*
* <p>To use via XLSForm, specify a 'note' type with a 'calculation' that defines
* the data to be printed and with an 'appearance' as described below.
*
* <p>Within the XForms XML, to use this widget, define an appearance on the
* <input/> tag that begins "printer:" and then contains the intent
* action to launch. That intent starts the printer app. The data to print
* is sent via a broadcast intent to intentname.data The printer then pops
* a UI to initiate the actual printing (or change the destination printer).
* </p>
*
* <p>Implementation-wise, this widget is an ExStringWidget that is read-only.</p>
*
* <p>The ODK Sensors Zebra printer uses this appearance (intent):</p>
* <pre>
* "printer:org.opendatakit.sensors.ZebraPrinter"
* </pre>
*
* <p>The data that is printed should be defined in the calculate attribute
* of the bind. The structure of that string is a <br> separated list
* of values consisting of:</p>
* <ul><li>numeric barcode to emit (optional)</li>
* <li>string qrcode to emit (optional)</li>
* <li>text line 1 (optional)</li>
* <li>additional text line (repeat as needed)</li></ul>
*
* <p>E.g., if you wanted to emit a barcode of 123, a qrcode of "mycode" and
* two text lines of "line 1" and "line 2", you would define the calculate
* as:</p>
*
* <pre>
* <bind nodeset="/printerForm/printme" type="string" readonly="true()"
* calculate="concat('123','<br>','mycode','<br>','line 1','<br>','line 2')" />
* </pre>
*
* <p>Depending upon what you supply, the printer may print just a
* barcode, just a qrcode, just text, or some combination of all 3.</p>
*
* <p>Despite using <br> as a separator, the supplied Zebra
* printer does not recognize html.</p>
*
* <pre>
* <input appearance="ex:change.uw.android.TEXTANSWER" ref="/printerForm/printme" >
* </pre>
* <p>or, to customize the button text and error strings with itext:
* <pre>
* ...
* <bind nodeset="/printerForm/printme" type="string" readonly="true()" calculate="concat('<br>',
* /printerForm/some_text ,'<br>Text: ', /printerForm/shortened_text ,'<br>Integer: ',
* /printerForm/a_integer ,'<br>Decimal: ', /printerForm/a_decimal )"/>
* ...
* <itext>
* <translation lang="English">
* <text id="printAnswer">
* <value form="short">Print your label</value>
* <value form="long">Print your label</value>
* <value form="buttonText">Print now</value>
* <value form="noPrinterErrorString">ODK Sensors Zebra Printer is not installed!
* Please install ODK Sensors Framework and ODK Sensors Zebra Printer from Google Play.</value>
* </text>
* </translation>
* </itext>
* ...
* <input appearance="printer:org.opendatakit.sensors.ZebraPrinter" ref="/form/printme">
* <label ref="jr:itext('printAnswer')"/>
* </input>
* </pre>
*
* @author mitchellsundt@gmail.com
*
*/
public class ExPrinterWidget extends QuestionWidget implements IBinaryWidget {
private Button mLaunchIntentButton;
public ExPrinterWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
params.setMargins(7, 5, 7, 5);
String appearance = prompt.getAppearanceHint();
String[] attrs = appearance.split(":");
final String intentName = (attrs.length < 2 || attrs[1].length() == 0) ? "org.opendatakit.sensors.ZebraPrinter" : attrs[1];
final String buttonText;
final String errorString;
String v = mPrompt.getSpecialFormQuestionText("buttonText");
buttonText = (v != null) ? v : context.getString(R.string.launch_printer);
v = mPrompt.getSpecialFormQuestionText("noPrinterErrorString");
errorString = (v != null) ? v : context.getString(R.string.no_printer);
// set button formatting
mLaunchIntentButton = new Button(getContext());
mLaunchIntentButton.setId(QuestionWidget.newUniqueId());
mLaunchIntentButton.setText(buttonText);
mLaunchIntentButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mLaunchIntentButton.setPadding(20, 20, 20, 20);
mLaunchIntentButton.setLayoutParams(params);
mLaunchIntentButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
Collect.getInstance().getFormController().setIndexWaitingForData(mPrompt.getIndex());
firePrintingActivity(intentName);
} catch (ActivityNotFoundException e) {
Collect.getInstance().getFormController().setIndexWaitingForData(null);
Toast.makeText(getContext(),
errorString, Toast.LENGTH_SHORT)
.show();
}
}
});
// finish complex layout
addView(mLaunchIntentButton);
}
protected void firePrintingActivity(String intentName) throws ActivityNotFoundException {
String s = mPrompt.getAnswerText();
Collect.getInstance().getActivityLogger().logInstanceAction(this, "launchPrinter",
intentName, mPrompt.getIndex());
Intent i = new Intent(intentName);
((Activity) getContext()).startActivity(i);
String[] splits;
if ( s != null ) {
splits = s.split("<br>");
} else {
splits = null;
}
Bundle printDataBundle = new Bundle();
String e;
if (splits != null) {
if ( splits.length >= 1 ) {
e = splits[0];
if ( e.length() > 0) {
printDataBundle.putString("BARCODE", e);
}
}
if ( splits.length >= 2 ) {
e = splits[1];
if ( e.length() > 0) {
printDataBundle.putString("QRCODE", e);
}
}
if ( splits.length > 2 ) {
String[] text = new String[splits.length-2];
for ( int j = 2 ; j < splits.length ; ++j ) {
e = splits[j];
text[j-2] = e;
}
printDataBundle.putStringArray("TEXT-STRINGS", text);
}
}
//send the printDataBundle to the activity via broadcast intent
Intent bcastIntent = new Intent(intentName + ".data");
bcastIntent.putExtra("DATA", printDataBundle);
((Activity) getContext()).sendBroadcast(bcastIntent);
}
@Override
public void clearAnswer() {
}
@Override
public IAnswerData getAnswer() {
return mPrompt.getAnswerValue();
}
/**
* Allows answer to be set externally in {@Link FormEntryActivity}.
*/
@Override
public void setBinaryData(Object answer) {
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setFocus(Context context) {
// focus on launch button
mLaunchIntentButton.requestFocus();
}
@Override
public boolean isWaitingForBinaryData() {
return mPrompt.getIndex().equals(Collect.getInstance().getFormController().getIndexWaitingForData());
}
@Override
public void cancelWaitingForBinaryData() {
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.isAltPressed() == true) {
return false;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mLaunchIntentButton.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mLaunchIntentButton.cancelLongPress();
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/ExPrinterWidget.java
|
Java
|
asf20
| 9,482
|
/*
* Copyright (C) 2011 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.widgets;
import java.io.File;
import java.util.List;
import org.javarosa.core.model.SelectChoice;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryPrompt;
import org.javarosa.xpath.expr.XPathFuncExpr;
import org.odk.collect.android.R;
import org.odk.collect.android.external.ExternalDataUtil;
import org.odk.collect.android.external.ExternalSelectChoice;
import org.odk.collect.android.utilities.FileUtils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* The Label Widget does not return an answer. The purpose of this widget is to be the top entry in
* a field-list with a bunch of list widgets below. This widget provides the labels, so that the
* list widgets can hide their labels and reduce the screen clutter. This class is essentially
* ListWidget with all the answer generating code removed.
*
* @author Jeff Beorse
*/
public class LabelWidget extends QuestionWidget {
private static final String t = "LabelWidget";
LinearLayout buttonLayout;
LinearLayout questionLayout;
List<SelectChoice> mItems;
private TextView mQuestionText;
private TextView mMissingImage;
private ImageView mImageView;
private TextView label;
public LabelWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
// SurveyCTO-added support for dynamic select content (from .csv files)
XPathFuncExpr xPathFuncExpr = ExternalDataUtil.getSearchXPathExpression(prompt.getAppearanceHint());
if (xPathFuncExpr != null) {
mItems = ExternalDataUtil.populateExternalChoices(prompt, xPathFuncExpr);
} else {
mItems = prompt.getSelectChoices();
}
mPrompt = prompt;
buttonLayout = new LinearLayout(context);
if (mItems != null) {
for (int i = 0; i < mItems.size(); i++) {
String imageURI;
if (mItems.get(i) instanceof ExternalSelectChoice) {
imageURI = ((ExternalSelectChoice) mItems.get(i)).getImage();
} else {
imageURI = prompt.getSpecialFormSelectChoiceText(mItems.get(i), FormEntryCaption.TEXT_FORM_IMAGE);
}
// build image view (if an image is provided)
mImageView = null;
mMissingImage = null;
final int labelId = QuestionWidget.newUniqueId();
// Now set up the image view
String errorMsg = null;
if (imageURI != null) {
try {
String imageFilename =
ReferenceManager._().DeriveReference(imageURI).getLocalURI();
final File imageFile = new File(imageFilename);
if (imageFile.exists()) {
Bitmap b = null;
try {
Display display =
((WindowManager) getContext().getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
b =
FileUtils.getBitmapScaledToDisplay(imageFile, screenHeight,
screenWidth);
} catch (OutOfMemoryError e) {
errorMsg = "ERROR: " + e.getMessage();
}
if (b != null) {
mImageView = new ImageView(getContext());
mImageView.setPadding(2, 2, 2, 2);
mImageView.setAdjustViewBounds(true);
mImageView.setImageBitmap(b);
mImageView.setId(labelId);
} else if (errorMsg == null) {
// An error hasn't been logged and loading the image failed, so it's
// likely
// a bad file.
errorMsg = getContext().getString(R.string.file_invalid, imageFile);
}
} else if (errorMsg == null) {
// An error hasn't been logged. We should have an image, but the file
// doesn't
// exist.
errorMsg = getContext().getString(R.string.file_missing, imageFile);
}
if (errorMsg != null) {
// errorMsg is only set when an error has occured
Log.e(t, errorMsg);
mMissingImage = new TextView(getContext());
mMissingImage.setText(errorMsg);
mMissingImage.setPadding(2, 2, 2, 2);
mMissingImage.setId(labelId);
}
} catch (InvalidReferenceException e) {
Log.e(t, "image invalid reference exception");
e.printStackTrace();
}
} else {
// There's no imageURI listed, so just ignore it.
}
// build text label. Don't assign the text to the built in label to he
// button because it aligns horizontally, and we want the label on top
label = new TextView(getContext());
label.setText(prompt.getSelectChoiceText(mItems.get(i)));
label.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize);
label.setGravity(Gravity.CENTER_HORIZONTAL);
// answer layout holds the label text/image on top and the radio button on bottom
RelativeLayout answer = new RelativeLayout(getContext());
RelativeLayout.LayoutParams headerParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
headerParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
headerParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
if (mImageView != null) {
mImageView.setScaleType(ScaleType.CENTER);
answer.addView(mImageView, headerParams);
} else if (mMissingImage != null) {
answer.addView(mMissingImage, headerParams);
} else {
label.setId(labelId);
answer.addView(label, headerParams);
}
answer.setPadding(4, 0, 4, 0);
// Each button gets equal weight
LinearLayout.LayoutParams answerParams =
new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
answerParams.weight = 1;
buttonLayout.addView(answer, answerParams);
}
}
// Align the buttons so that they appear horizonally and are right justified
// buttonLayout.setGravity(Gravity.RIGHT);
buttonLayout.setOrientation(LinearLayout.HORIZONTAL);
// LinearLayout.LayoutParams params = new
// LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
// buttonLayout.setLayoutParams(params);
// The buttons take up the right half of the screen
LinearLayout.LayoutParams buttonParams =
new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
buttonParams.weight = 1;
questionLayout.addView(buttonLayout, buttonParams);
addView(questionLayout);
}
@Override
public void clearAnswer() {
// Do nothing, no answers to clear
}
@Override
public IAnswerData getAnswer() {
return null;
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
// Override QuestionWidget's add question text. Build it the same
// but add it to the relative layout
protected void addQuestionText(FormEntryPrompt p) {
// Add the text view. Textview always exists, regardless of whether there's text.
mQuestionText = new TextView(getContext());
mQuestionText.setText(p.getLongText());
mQuestionText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize);
mQuestionText.setTypeface(null, Typeface.BOLD);
mQuestionText.setPadding(0, 0, 0, 7);
mQuestionText.setId(QuestionWidget.newUniqueId()); // assign random id
// Wrap to the size of the parent view
mQuestionText.setHorizontallyScrolling(false);
if (p.getLongText() == null) {
mQuestionText.setVisibility(GONE);
}
// Put the question text on the left half of the screen
LinearLayout.LayoutParams labelParams =
new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
labelParams.weight = 1;
questionLayout = new LinearLayout(getContext());
questionLayout.setOrientation(LinearLayout.HORIZONTAL);
questionLayout.addView(mQuestionText, labelParams);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mQuestionText.cancelLongPress();
if (mMissingImage != null) {
mMissingImage.cancelLongPress();
}
if (mImageView != null) {
mImageView.cancelLongPress();
}
if (label != null) {
label.cancelLongPress();
}
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mQuestionText.setOnLongClickListener(l);
if (mMissingImage != null) {
mMissingImage.setOnLongClickListener(l);
}
if (mImageView != null) {
mImageView.setOnLongClickListener(l);
}
if (label != null) {
label.setOnLongClickListener(l);
}
}
}
|
0nima0-f
|
src/org/odk/collect/android/widgets/LabelWidget.java
|
Java
|
asf20
| 11,793
|