code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* 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.Vector;
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.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.views.AudioButton.AudioHandler;
import org.odk.collect.android.views.ExpandedHeightGridView;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
/**
* GridWidget handles multiple selection fields using a grid of icons. The user clicks the desired
* icon and the background changes from black to orange. If text, audio or video are specified in
* the select answers they are ignored. This is almost identical to GridWidget, except multiple
* icons can be selected simultaneously.
*
* @author Jeff Beorse (jeff@beorse.net)
*/
public class GridMultiWidget extends QuestionWidget {
// The RGB value for the orange background
public static final int orangeRedVal = 255;
public static final int orangeGreenVal = 140;
public static final int orangeBlueVal = 0;
private static final int HORIZONTAL_PADDING = 7;
private static final int VERTICAL_PADDING = 5;
private static final int SPACING = 2;
private static final int IMAGE_PADDING = 8;
private static final int SCROLL_WIDTH = 16;
Vector<SelectChoice> mItems;
// The possible select choices
String[] choices;
// The Gridview that will hold the icons
ExpandedHeightGridView gridview;
// Defines which icon is selected
boolean[] selected;
// The image views for each of the icons
View[] imageViews;
AudioHandler[] audioHandlers;
// need to remember the last click position for audio treatment
int lastClickPosition = 0;
// The number of columns in the grid, can be user defined (<= 0 if unspecified)
int numColumns;
int resizeWidth;
@SuppressWarnings("unchecked")
public GridMultiWidget(Context context, FormEntryPrompt prompt, int numColumns) {
super(context, prompt);
mItems = prompt.getSelectChoices();
mPrompt = prompt;
selected = new boolean[mItems.size()];
choices = new String[mItems.size()];
gridview = new ExpandedHeightGridView(context);
imageViews = new View[mItems.size()];
audioHandlers = new AudioHandler[mItems.size()];
// The max width of an icon in a given column. Used to line
// up the columns and automatically fit the columns in when
// they are chosen automatically
int maxColumnWidth = -1;
int maxCellHeight = -1;
this.numColumns = numColumns;
for (int i = 0; i < mItems.size(); i++) {
imageViews[i] = new ImageView(getContext());
}
Display display =
((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
if ( display.getOrientation() % 2 == 1 ) {
// rotated 90 degrees...
int temp = screenWidth;
screenWidth = screenHeight;
screenHeight = temp;
}
if ( numColumns > 0 ) {
resizeWidth = ((screenWidth - 2*HORIZONTAL_PADDING - SCROLL_WIDTH - (IMAGE_PADDING+SPACING)*numColumns) / numColumns );
}
// Build view
for (int i = 0; i < mItems.size(); i++) {
SelectChoice sc = mItems.get(i);
int curHeight = -1;
// Create an audioHandler iff there is an audio prompt associated with this selection.
String audioURI =
prompt.getSpecialFormSelectChoiceText(sc, FormEntryCaption.TEXT_FORM_AUDIO);
if ( audioURI != null) {
audioHandlers[i] = new AudioHandler(prompt.getIndex(), sc.getValue(), audioURI);
} else {
audioHandlers[i] = null;
}
// Read the image sizes and set maxColumnWidth. This allows us to make sure all of our
// columns are going to fit
String imageURI =
prompt.getSpecialFormSelectChoiceText(sc, FormEntryCaption.TEXT_FORM_IMAGE);
String errorMsg = null;
if (imageURI != null) {
choices[i] = imageURI;
String imageFilename;
try {
imageFilename = ReferenceManager._().DeriveReference(imageURI).getLocalURI();
final File imageFile = new File(imageFilename);
if (imageFile.exists()) {
Bitmap b =
FileUtils
.getBitmapScaledToDisplay(imageFile, screenHeight, screenWidth);
if (b != null) {
if (b.getWidth() > maxColumnWidth) {
maxColumnWidth = b.getWidth();
}
ImageView imageView = (ImageView) imageViews[i];
imageView.setBackgroundColor(Color.WHITE);
if ( numColumns > 0 ) {
int resizeHeight = (b.getHeight() * resizeWidth) / b.getWidth();
b = Bitmap.createScaledBitmap(b, resizeWidth, resizeHeight, false);
}
imageView.setPadding(IMAGE_PADDING, IMAGE_PADDING, IMAGE_PADDING, IMAGE_PADDING);
imageView.setImageBitmap(b);
imageView.setLayoutParams(new ListView.LayoutParams(ListView.LayoutParams.WRAP_CONTENT, ListView.LayoutParams.WRAP_CONTENT));
imageView.setScaleType(ScaleType.FIT_XY);
imageView.measure(0, 0);
curHeight = imageView.getMeasuredHeight();
} 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);
}
} catch (InvalidReferenceException e) {
Log.e("GridMultiWidget", "image invalid reference exception");
e.printStackTrace();
}
} else {
errorMsg = "";
}
if (errorMsg != null) {
choices[i] = prompt.getSelectChoiceText(sc);
TextView missingImage = new TextView(getContext());
missingImage.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
missingImage.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
missingImage.setPadding(IMAGE_PADDING, IMAGE_PADDING, IMAGE_PADDING, IMAGE_PADDING);
if ( choices[i] != null && choices[i].length() != 0 ) {
missingImage.setText(choices[i]);
} else {
// errorMsg is only set when an error has occurred
Log.e("GridMultiWidget", errorMsg);
missingImage.setText(errorMsg);
}
if ( numColumns > 0 ) {
maxColumnWidth = resizeWidth;
// force the max width to find the needed height...
missingImage.setMaxWidth(resizeWidth);
missingImage.measure(MeasureSpec.makeMeasureSpec(resizeWidth, MeasureSpec.EXACTLY), 0);
curHeight = missingImage.getMeasuredHeight();
} else {
missingImage.measure(0, 0);
int width = missingImage.getMeasuredWidth();
if (width > maxColumnWidth) {
maxColumnWidth = width;
}
curHeight = missingImage.getMeasuredHeight();
}
imageViews[i] = missingImage;
}
// if we get a taller image/text, force all cells to be that height
// could also set cell heights on a per-row basis if user feedback requests it.
if ( curHeight > maxCellHeight ) {
maxCellHeight = curHeight;
for ( int j = 0 ; j < i ; j++ ) {
imageViews[j].setMinimumHeight(maxCellHeight);
}
}
imageViews[i].setMinimumHeight(maxCellHeight);
}
// Read the screen dimensions and fit the grid view to them. It is important that the grid
// knows how far out it can stretch.
if ( numColumns > 0 ) {
// gridview.setNumColumns(numColumns);
gridview.setNumColumns(GridView.AUTO_FIT);
} else {
resizeWidth = maxColumnWidth;
gridview.setNumColumns(GridView.AUTO_FIT);
}
gridview.setColumnWidth(resizeWidth);
gridview.setPadding(HORIZONTAL_PADDING, VERTICAL_PADDING, HORIZONTAL_PADDING, VERTICAL_PADDING);
gridview.setHorizontalSpacing(SPACING);
gridview.setVerticalSpacing(SPACING);
gridview.setGravity(Gravity.CENTER);
gridview.setScrollContainer(false);
gridview.setStretchMode(GridView.NO_STRETCH);
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
if (selected[position]) {
selected[position] = false;
if ( audioHandlers[position] != null) {
audioHandlers[position].stopPlaying();
}
imageViews[position].setBackgroundColor(Color.WHITE);
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onItemClick.deselect",
mItems.get(position).getValue(), mPrompt.getIndex());
} else {
selected[position] = true;
if ( audioHandlers[lastClickPosition] != null) {
audioHandlers[lastClickPosition].stopPlaying();
}
imageViews[position].setBackgroundColor(Color.rgb(orangeRedVal, orangeGreenVal,
orangeBlueVal));
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onItemClick.select",
mItems.get(position).getValue(), mPrompt.getIndex());
if ( audioHandlers[position] != null) {
audioHandlers[position].playAudio(getContext());
}
lastClickPosition = position;
}
}
});
// Fill in answer
IAnswerData answer = prompt.getAnswerValue();
Vector<Selection> ve;
if ((answer == null) || (answer.getValue() == null)) {
ve = new Vector<Selection>();
} else {
ve = (Vector<Selection>) answer.getValue();
}
for (int i = 0; i < choices.length; ++i) {
String value = mItems.get(i).getValue();
boolean found = false;
for (Selection s : ve) {
if (value.equals(s.getValue())) {
found = true;
break;
}
}
selected[i] = found;
if (selected[i]) {
imageViews[i].setBackgroundColor(Color.rgb(orangeRedVal, orangeGreenVal,
orangeBlueVal));
} else {
imageViews[i].setBackgroundColor(Color.WHITE);
}
}
// Use the custom image adapter and initialize the grid view
ImageAdapter ia = new ImageAdapter(getContext(), choices);
gridview.setAdapter(ia);
addView(gridview, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
}
@Override
public IAnswerData getAnswer() {
Vector<Selection> vc = new Vector<Selection>();
for (int i = 0; i < mItems.size(); i++) {
if (selected[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() {
for (int i = 0; i < mItems.size(); ++i) {
selected[i] = false;
imageViews[i].setBackgroundColor(Color.WHITE);
}
}
@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);
}
// Custom image adapter. Most of the code is copied from
// media layout for using a picture.
private class ImageAdapter extends BaseAdapter {
private String[] choices;
public ImageAdapter(Context c, String[] choices) {
this.choices = choices;
}
public int getCount() {
return choices.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
if ( position < imageViews.length ) {
return imageViews[position];
} else {
return convertView;
}
}
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
gridview.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
gridview.cancelLongPress();
}
}
| Java |
/*
* 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.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.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore.Audio;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.Toast;
import java.io.File;
/**
* Widget that allows user to take pictures, sounds or video and add them to the
* form.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class AudioWidget extends QuestionWidget implements IBinaryWidget {
private final static String t = "MediaWidget";
private Button mCaptureButton;
private Button mPlayButton;
private Button mChooseButton;
private String mBinaryName;
private String mInstanceFolder;
public AudioWidget(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);
// setup capture button
mCaptureButton = new Button(getContext());
mCaptureButton.setId(QuestionWidget.newUniqueId());
mCaptureButton.setText(getContext().getString(R.string.capture_audio));
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());
Intent i = new Intent(
android.provider.MediaStore.Audio.Media.RECORD_SOUND_ACTION);
i.putExtra(
android.provider.MediaStore.EXTRA_OUTPUT,
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
.toString());
try {
Collect.getInstance().getFormController()
.setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.AUDIO_CAPTURE);
} catch (ActivityNotFoundException e) {
Toast.makeText(
getContext(),
getContext().getString(R.string.activity_not_found,
"audio capture"), Toast.LENGTH_SHORT)
.show();
Collect.getInstance().getFormController()
.setIndexWaitingForData(null);
}
}
});
// setup capture button
mChooseButton = new Button(getContext());
mChooseButton.setId(QuestionWidget.newUniqueId());
mChooseButton.setText(getContext().getString(R.string.choose_sound));
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());
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("audio/*");
try {
Collect.getInstance().getFormController()
.setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.AUDIO_CHOOSER);
} catch (ActivityNotFoundException e) {
Toast.makeText(
getContext(),
getContext().getString(R.string.activity_not_found,
"choose audio"), Toast.LENGTH_SHORT).show();
Collect.getInstance().getFormController()
.setIndexWaitingForData(null);
}
}
});
// setup play button
mPlayButton = new Button(getContext());
mPlayButton.setId(QuestionWidget.newUniqueId());
mPlayButton.setText(getContext().getString(R.string.play_audio));
mPlayButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mPlayButton.setPadding(20, 20, 20, 20);
mPlayButton.setLayoutParams(params);
// on play, launch the appropriate viewer
mPlayButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "playButton", "click",
mPrompt.getIndex());
Intent i = new Intent("android.intent.action.VIEW");
File f = new File(mInstanceFolder + File.separator
+ mBinaryName);
i.setDataAndType(Uri.fromFile(f), "audio/*");
try {
((Activity) getContext()).startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(
getContext(),
getContext().getString(R.string.activity_not_found,
"play audio"), Toast.LENGTH_SHORT).show();
}
}
});
// retrieve answer from data model and update ui
mBinaryName = prompt.getAnswerText();
if (mBinaryName != null) {
mPlayButton.setEnabled(true);
} else {
mPlayButton.setEnabled(false);
}
// finish complex layout
addView(mCaptureButton);
addView(mChooseButton);
addView(mPlayButton);
// and hide the capture and choose button if read-only
if (mPrompt.isReadOnly()) {
mCaptureButton.setVisibility(View.GONE);
mChooseButton.setVisibility(View.GONE);
}
}
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.deleteAudioFileFromMediaProvider(mInstanceFolder + File.separator + name);
Log.i(t, "Deleted " + del + " rows from media content provider");
}
@Override
public void clearAnswer() {
// remove the file
deleteMedia();
// reset buttons
mPlayButton.setEnabled(false);
}
@Override
public IAnswerData getAnswer() {
if (mBinaryName != null) {
return new StringData(mBinaryName.toString());
} else {
return null;
}
}
private String getPathFromUri(Uri uri) {
if (uri.toString().startsWith("file")) {
return uri.toString().substring(6);
} else {
String[] audioProjection = { Audio.Media.DATA };
String audioPath = null;
Cursor c = null;
try {
c = getContext().getContentResolver().query(uri,
audioProjection, null, null, null);
int column_index = c.getColumnIndexOrThrow(Audio.Media.DATA);
if (c.getCount() > 0) {
c.moveToFirst();
audioPath = c.getString(column_index);
}
return audioPath;
} finally {
if (c != null) {
c.close();
}
}
}
}
@Override
public void setBinaryData(Object binaryuri) {
// when replacing an answer. remove the current media.
if (mBinaryName != null) {
deleteMedia();
}
// get the file path and create a copy in the instance folder
String binaryPath = getPathFromUri((Uri) binaryuri);
String extension = binaryPath.substring(binaryPath.lastIndexOf("."));
String destAudioPath = mInstanceFolder + File.separator
+ System.currentTimeMillis() + extension;
File source = new File(binaryPath);
File newAudio = new File(destAudioPath);
FileUtils.copyFile(source, newAudio);
if (newAudio.exists()) {
// Add the copy to the content provier
ContentValues values = new ContentValues(6);
values.put(Audio.Media.TITLE, newAudio.getName());
values.put(Audio.Media.DISPLAY_NAME, newAudio.getName());
values.put(Audio.Media.DATE_ADDED, System.currentTimeMillis());
values.put(Audio.Media.DATA, newAudio.getAbsolutePath());
Uri AudioURI = getContext().getContentResolver().insert(
Audio.Media.EXTERNAL_CONTENT_URI, values);
Log.i(t, "Inserting AUDIO returned uri = " + AudioURI.toString());
mBinaryName = newAudio.getName();
Log.i(t, "Setting current answer to " + newAudio.getName());
} else {
Log.e(t, "Inserting Audio file FAILED");
}
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);
mPlayButton.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mCaptureButton.cancelLongPress();
mChooseButton.cancelLongPress();
mPlayButton.cancelLongPress();
}
}
| Java |
/*
* 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.Vector;
import org.javarosa.core.model.SelectChoice;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.SelectOneData;
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.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
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.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* ListWidget handles select-one fields using radio buttons. The radio buttons 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.
*
* @author Jeff Beorse (jeff@beorse.net)
*/
public class ListWidget extends QuestionWidget implements OnCheckedChangeListener {
private static final String t = "ListWidget";
// 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;
Vector<SelectChoice> mItems; // may take a while to compute
ArrayList<RadioButton> buttons;
public ListWidget(Context context, FormEntryPrompt prompt, boolean displayLabel) {
super(context, prompt);
mItems = prompt.getSelectChoices();
buttons = new ArrayList<RadioButton>();
// Layout holds the horizontal list of buttons
LinearLayout buttonLayout = new LinearLayout(context);
String s = null;
if (prompt.getAnswerValue() != null) {
s = ((Selection) prompt.getAnswerValue().getValue()).getValue();
}
if (mItems != null) {
for (int i = 0; i < mItems.size(); i++) {
RadioButton r = new RadioButton(getContext());
r.setId(QuestionWidget.newUniqueId());
r.setTag(Integer.valueOf(i));
r.setEnabled(!prompt.isReadOnly());
r.setFocusable(!prompt.isReadOnly());
buttons.add(r);
if (mItems.get(i).getValue().equals(s)) {
r.setChecked(true);
}
r.setOnCheckedChangeListener(this);
String imageURI = null;
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(r, 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 is created and populated with the question text in the
// super() constructor via a call to addQuestionText
questionLayout.addView(buttonLayout, buttonParams);
addView(questionLayout);
}
@Override
public void clearAnswer() {
for (RadioButton button : this.buttons) {
if (button.isChecked()) {
button.setChecked(false);
return;
}
}
}
@Override
public IAnswerData getAnswer() {
int i = getCheckedId();
if (i == -1) {
return null;
} else {
SelectChoice sc = mItems.elementAt(i);
return new SelectOneData(new Selection(sc));
}
}
@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);
}
public int getCheckedId() {
for (int i=0; i < buttons.size(); ++i ) {
RadioButton button = buttons.get(i);
if (button.isChecked()) {
return i;
}
}
return -1;
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!isChecked) {
// If it got unchecked, we don't care.
return;
}
for (RadioButton button : this.buttons) {
if (button.isChecked() && !(buttonView == button)) {
button.setChecked(false);
}
}
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onCheckedChanged",
mItems.get((Integer)buttonView.getTag()).getValue(), mPrompt.getIndex());
}
// 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.
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 (RadioButton r : buttons) {
r.setOnLongClickListener(l);
}
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
for (RadioButton r : buttons) {
r.cancelLongPress();
}
}
}
| Java |
/*
* 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 org.javarosa.core.model.SelectChoice;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.SelectOneData;
import org.javarosa.core.model.data.helper.Selection;
import org.javarosa.form.api.FormEntryPrompt;
import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Vector;
/**
* AutoCompleteWidget handles select-one fields using an autocomplete text box. The user types part
* of the desired selection and suggestions appear in a list below. The full list of possible
* answers is not displayed to the user. The goal is to be more compact; this question type is best
* suited for select one questions with a large number of possible answers. If images, audio, or
* video are specified in the select answers they are ignored.
*
* @author Jeff Beorse (jeff@beorse.net)
*/
public class AutoCompleteWidget extends QuestionWidget {
AutoCompleteAdapter choices;
AutoCompleteTextView autocomplete;
Vector<SelectChoice> mItems;
// Defines which filter to use to display autocomplete possibilities
String filterType;
// The various filter types
String match_substring = "substring";
String match_prefix = "prefix";
String match_chars = "chars";
public AutoCompleteWidget(Context context, FormEntryPrompt prompt, String filterType) {
super(context, prompt);
mItems = prompt.getSelectChoices();
mPrompt = prompt;
choices = new AutoCompleteAdapter(getContext(), android.R.layout.simple_list_item_1);
autocomplete = new AutoCompleteTextView(getContext());
// Default to matching substring
if (filterType != null) {
this.filterType = filterType;
} else {
this.filterType = match_substring;
}
for (SelectChoice sc : mItems) {
choices.add(prompt.getSelectChoiceText(sc));
}
choices.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
autocomplete.setAdapter(choices);
autocomplete.setTextColor(Color.BLACK);
setGravity(Gravity.LEFT);
// Fill in answer
String s = null;
if (mPrompt.getAnswerValue() != null) {
s = ((Selection) mPrompt.getAnswerValue().getValue()).getValue();
}
for (int i = 0; i < mItems.size(); ++i) {
String sMatch = mItems.get(i).getValue();
if (sMatch.equals(s)) {
autocomplete.setText(mItems.get(i).getLabelInnerText());
}
}
addView(autocomplete);
}
@Override
public IAnswerData getAnswer() {
clearFocus();
String response = autocomplete.getText().toString();
for (SelectChoice sc : mItems) {
if (response.equals(mPrompt.getSelectChoiceText(sc))) {
return new SelectOneData(new Selection(sc));
}
}
// If the user has typed text into the autocomplete box that doesn't match any answer, warn
// them that their
// solution didn't count.
if (!response.equals("")) {
Toast.makeText(getContext(),
"Warning: \"" + response + "\" does not match any answers. No answer recorded.",
Toast.LENGTH_LONG).show();
}
return null;
}
@Override
public void clearAnswer() {
autocomplete.setText("");
}
@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);
}
private class AutoCompleteAdapter extends ArrayAdapter<String> implements Filterable {
private ItemsFilter mFilter;
public ArrayList<String> mItems;
public AutoCompleteAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
mItems = new ArrayList<String>();
}
@Override
public void add(String toAdd) {
super.add(toAdd);
mItems.add(toAdd);
}
@Override
public int getCount() {
return mItems.size();
}
@Override
public String getItem(int position) {
return mItems.get(position);
}
@Override
public int getPosition(String item) {
return mItems.indexOf(item);
}
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ItemsFilter(mItems);
}
return mFilter;
}
@Override
public long getItemId(int position) {
return position;
}
private class ItemsFilter extends Filter {
final ArrayList<String> mItemsArray;
public ItemsFilter(ArrayList<String> list) {
if (list == null) {
mItemsArray = new ArrayList<String>();
} else {
mItemsArray = new ArrayList<String>(list);
}
}
@Override
protected FilterResults performFiltering(CharSequence prefix) {
// Initiate our results object
FilterResults results = new FilterResults();
// If the adapter array is empty, check the actual items array and use it
if (mItems == null) {
mItems = new ArrayList<String>(mItemsArray);
}
// No prefix is sent to filter by so we're going to send back the original array
if (prefix == null || prefix.length() == 0) {
results.values = mItemsArray;
results.count = mItemsArray.size();
} else {
// Compare lower case strings
String prefixString = prefix.toString().toLowerCase(Locale.getDefault());
// Local to here so we're not changing actual array
final ArrayList<String> items = mItems;
final int count = items.size();
final ArrayList<String> newItems = new ArrayList<String>(count);
for (int i = 0; i < count; i++) {
final String item = items.get(i);
String item_compare = item.toLowerCase(Locale.getDefault());
// Match the strings using the filter specified
if (filterType.equals(match_substring)
&& (item_compare.startsWith(prefixString) || item_compare
.contains(prefixString))) {
newItems.add(item);
} else if (filterType.equals(match_prefix)
&& item_compare.startsWith(prefixString)) {
newItems.add(item);
} else if (filterType.equals(match_chars)) {
char[] toMatch = prefixString.toCharArray();
boolean matches = true;
for (int j = 0; j < toMatch.length; j++) {
int index = item_compare.indexOf(toMatch[j]);
if (index > -1) {
item_compare =
item_compare.substring(0, index)
+ item_compare.substring(index + 1);
} else {
matches = false;
break;
}
}
if (matches) {
newItems.add(item);
}
} else {
// Default to substring
if (item_compare.startsWith(prefixString)
|| item_compare.contains(prefixString)) {
newItems.add(item);
}
}
}
// Set and return
results.values = newItems;
results.count = newItems.size();
}
return results;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mItems = (ArrayList<String>) results.values;
// Let the adapter know about the updated list
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
autocomplete.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
autocomplete.cancelLongPress();
}
}
| Java |
/*
* 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.R;
import org.odk.collect.android.application.Collect;
import android.content.Context;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* Widget that allows user to scan barcodes and add them to the form.
*
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class TriggerWidget extends QuestionWidget {
private CheckBox mTriggerButton;
private TextView mStringAnswer;
private static final String mOK = "OK";
private FormEntryPrompt mPrompt;
public FormEntryPrompt getPrompt() {
return mPrompt;
}
public TriggerWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mPrompt = prompt;
this.setOrientation(LinearLayout.VERTICAL);
mTriggerButton = new CheckBox(getContext());
mTriggerButton.setId(QuestionWidget.newUniqueId());
mTriggerButton.setText(getContext().getString(R.string.trigger));
mTriggerButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
// mActionButton.setPadding(20, 20, 20, 20);
mTriggerButton.setEnabled(!prompt.isReadOnly());
mTriggerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mTriggerButton.isChecked()) {
mStringAnswer.setText(mOK);
Collect.getInstance().getActivityLogger().logInstanceAction(TriggerWidget.this, "triggerButton",
"OK", mPrompt.getIndex());
} else {
mStringAnswer.setText(null);
Collect.getInstance().getActivityLogger().logInstanceAction(TriggerWidget.this, "triggerButton",
"null", mPrompt.getIndex());
}
}
});
mStringAnswer = new TextView(getContext());
mStringAnswer.setId(QuestionWidget.newUniqueId());
mStringAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mStringAnswer.setGravity(Gravity.CENTER);
String s = prompt.getAnswerText();
if (s != null) {
if (s.equals(mOK)) {
mTriggerButton.setChecked(true);
} else {
mTriggerButton.setChecked(false);
}
mStringAnswer.setText(s);
}
// finish complex layout
this.addView(mTriggerButton);
// this.addView(mStringAnswer);
}
@Override
public void clearAnswer() {
mStringAnswer.setText(null);
mTriggerButton.setChecked(false);
}
@Override
public IAnswerData getAnswer() {
String s = mStringAnswer.getText().toString();
if (s == null || s.equals("")) {
return null;
} else {
return new StringData(s);
}
}
@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) {
mTriggerButton.setOnLongClickListener(l);
mStringAnswer.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mTriggerButton.cancelLongPress();
mStringAnswer.cancelLongPress();
}
}
| Java |
/*
* 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.Vector;
import org.javarosa.core.model.SelectChoice;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.SelectOneData;
import org.javarosa.core.model.data.helper.Selection;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
/**
* SpinnerWidget handles select-one fields. Instead of a list of buttons it uses a spinner, wherein
* the user clicks a button and the choices pop up in a dialogue box. The goal is to be more
* compact. If images, audio, or video are specified in the select answers they are ignored.
*
* @author Jeff Beorse (jeff@beorse.net)
*/
public class SpinnerWidget extends QuestionWidget {
Vector<SelectChoice> mItems;
Spinner spinner;
String[] choices;
private static final int BROWN = 0xFF936931;
public SpinnerWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mItems = prompt.getSelectChoices();
spinner = new Spinner(context);
choices = new String[mItems.size()+1];
for (int i = 0; i < mItems.size(); i++) {
choices[i] = prompt.getSelectChoiceText(mItems.get(i));
}
choices[mItems.size()] = getContext().getString(R.string.select_one);
// The spinner requires a custom adapter. It is defined below
SpinnerAdapter adapter =
new SpinnerAdapter(getContext(), android.R.layout.simple_spinner_item, choices,
TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize);
spinner.setAdapter(adapter);
spinner.setPrompt(prompt.getQuestionText());
spinner.setEnabled(!prompt.isReadOnly());
spinner.setFocusable(!prompt.isReadOnly());
// Fill in previous answer
String s = null;
if (prompt.getAnswerValue() != null) {
s = ((Selection) prompt.getAnswerValue().getValue()).getValue();
}
spinner.setSelection(mItems.size());
if (s != null) {
for (int i = 0; i < mItems.size(); ++i) {
String sMatch = mItems.get(i).getValue();
if (sMatch.equals(s)) {
spinner.setSelection(i);
}
}
}
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
if ( position == mItems.size() ) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onCheckedChanged.clearValue",
"", mPrompt.getIndex());
} else {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onCheckedChanged",
mItems.get(position).getValue(), mPrompt.getIndex());
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}});
addView(spinner);
}
@Override
public IAnswerData getAnswer() {
clearFocus();
int i = spinner.getSelectedItemPosition();
if (i == -1 || i == mItems.size()) {
return null;
} else {
SelectChoice sc = mItems.elementAt(i);
return new SelectOneData(new Selection(sc));
}
}
@Override
public void clearAnswer() {
// It seems that spinners cannot return a null answer. This resets the answer
// to its original value, but it is not null.
spinner.setSelection(mItems.size());
}
@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);
}
// Defines how to display the select answers
private class SpinnerAdapter extends ArrayAdapter<String> {
Context context;
String[] items = new String[] {};
int textUnit;
float textSize;
public SpinnerAdapter(final Context context, final int textViewResourceId,
final String[] objects, int textUnit, float textSize) {
super(context, textViewResourceId, objects);
this.items = objects;
this.context = context;
this.textUnit = textUnit;
this.textSize = textSize;
}
@Override
// Defines the text view parameters for the drop down list entries
public View getDropDownView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.custom_spinner_item, parent, false);
}
TextView tv = (TextView) convertView.findViewById(android.R.id.text1);
tv.setTextSize(textUnit, textSize);
tv.setBackgroundColor(Color.WHITE);
tv.setPadding(10, 10, 10, 10); // Are these values OK?
if (position == items.length-1) {
tv.setText(parent.getContext().getString(R.string.clear_answer));
tv.setTextColor(BROWN);
tv.setTypeface(null, Typeface.NORMAL);
if (spinner.getSelectedItemPosition() == position) {
tv.setBackgroundColor(Color.LTGRAY);
}
} else {
tv.setText(items[position]);
tv.setTextColor(Color.BLACK);
tv.setTypeface(null, (spinner.getSelectedItemPosition() == position)
? Typeface.BOLD : Typeface.NORMAL);
}
return convertView;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(android.R.layout.simple_spinner_item, parent, false);
}
TextView tv = (TextView) convertView.findViewById(android.R.id.text1);
tv.setText(items[position]);
tv.setTextSize(textUnit, textSize);
tv.setTextColor(Color.BLACK);
tv.setTypeface(null, Typeface.BOLD);
if (position == items.length-1) {
tv.setTextColor(BROWN);
tv.setTypeface(null, Typeface.NORMAL);
}
return convertView;
}
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
spinner.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
spinner.cancelLongPress();
}
}
| Java |
/*
* 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.ArrayList;
import java.util.Vector;
import org.javarosa.core.model.SelectChoice;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.SelectOneData;
import org.javarosa.core.model.data.helper.Selection;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.views.MediaLayout;
import android.content.Context;
import android.util.TypedValue;
import android.view.inputmethod.InputMethodManager;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
/**
* SelectOneWidgets handles select-one fields using radio buttons.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class SelectOneWidget extends QuestionWidget implements
OnCheckedChangeListener {
Vector<SelectChoice> mItems; // may take a while to compute
ArrayList<RadioButton> buttons;
public SelectOneWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mItems = prompt.getSelectChoices();
buttons = new ArrayList<RadioButton>();
// Layout holds the vertical list of buttons
LinearLayout buttonLayout = new LinearLayout(context);
String s = null;
if (prompt.getAnswerValue() != null) {
s = ((Selection) prompt.getAnswerValue().getValue()).getValue();
}
if (mItems != null) {
for (int i = 0; i < mItems.size(); i++) {
RadioButton r = new RadioButton(getContext());
r.setText(prompt.getSelectChoiceText(mItems.get(i)));
r.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
r.setTag(Integer.valueOf(i));
r.setId(QuestionWidget.newUniqueId());
r.setEnabled(!prompt.isReadOnly());
r.setFocusable(!prompt.isReadOnly());
buttons.add(r);
if (mItems.get(i).getValue().equals(s)) {
r.setChecked(true);
}
r.setOnCheckedChangeListener(this);
String audioURI = null;
audioURI = prompt.getSpecialFormSelectChoiceText(mItems.get(i),
FormEntryCaption.TEXT_FORM_AUDIO);
String imageURI = null;
imageURI = prompt.getSpecialFormSelectChoiceText(mItems.get(i),
FormEntryCaption.TEXT_FORM_IMAGE);
String videoURI = null;
videoURI = prompt.getSpecialFormSelectChoiceText(mItems.get(i),
"video");
String bigImageURI = null;
bigImageURI = prompt.getSpecialFormSelectChoiceText(
mItems.get(i), "big-image");
MediaLayout mediaLayout = new MediaLayout(getContext());
mediaLayout.setAVT(prompt.getIndex(), "." + Integer.toString(i), r, audioURI, imageURI,
videoURI, bigImageURI);
if (i != mItems.size() - 1) {
// Last, add the dividing line (except for the last element)
ImageView divider = new ImageView(getContext());
divider.setBackgroundResource(android.R.drawable.divider_horizontal_bright);
mediaLayout.addDivider(divider);
}
buttonLayout.addView(mediaLayout);
}
}
buttonLayout.setOrientation(LinearLayout.VERTICAL);
// The buttons take up the right half of the screen
LayoutParams buttonParams = new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
addView(buttonLayout, buttonParams);
}
@Override
public void clearAnswer() {
for (RadioButton button : this.buttons) {
if (button.isChecked()) {
button.setChecked(false);
return;
}
}
}
@Override
public IAnswerData getAnswer() {
int i = getCheckedId();
if (i == -1) {
return null;
} else {
SelectChoice sc = mItems.elementAt(i);
return new SelectOneData(new Selection(sc));
}
}
@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);
}
public int getCheckedId() {
for (int i = 0; i < buttons.size(); ++i) {
RadioButton button = buttons.get(i);
if (button.isChecked()) {
return i;
}
}
return -1;
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!isChecked) {
// If it got unchecked, we don't care.
return;
}
for (RadioButton button : buttons ) {
if (button.isChecked() && !(buttonView == button)) {
button.setChecked(false);
}
}
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onCheckedChanged",
mItems.get((Integer)buttonView.getTag()).getValue(), mPrompt.getIndex());
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
for (RadioButton r : buttons) {
r.setOnLongClickListener(l);
}
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
for (RadioButton button : this.buttons) {
button.cancelLongPress();
}
}
}
| Java |
/*
* 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 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.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 take pictures, sounds or video and add them to the form.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class ImageWidget extends QuestionWidget implements IBinaryWidget {
private final static String t = "MediaWidget";
private Button mCaptureButton;
private Button mChooseButton;
private ImageView mImageView;
private String mBinaryName;
private String mInstanceFolder;
private TextView mErrorTextView;
public ImageWidget(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 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(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// 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.
i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
Uri.fromFile(new File(Collect.TMPFILE_PATH)));
try {
Collect.getInstance().getFormController().setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.IMAGE_CAPTURE);
} catch (ActivityNotFoundException e) {
Toast.makeText(getContext(),
getContext().getString(R.string.activity_not_found, "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();
}
}
}
| Java |
/*
* 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.IntegerData;
import org.javarosa.form.api.FormEntryPrompt;
import android.content.Context;
import android.text.InputFilter;
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 IntegerWidget extends StringWidget {
private Integer getIntegerAnswerValue() {
IAnswerData dataHolder = mPrompt.getAnswerValue();
Integer d = null;
if (dataHolder != null) {
Object dataValue = dataHolder.getValue();
if ( dataValue != null ) {
if (dataValue instanceof Double){
d = Integer.valueOf(((Double) dataValue).intValue());
} else {
d = (Integer)dataValue;
}
}
}
return d;
}
public IntegerWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt, 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);
// only allows numbers and no periods
mAnswer.setKeyListener(new DigitsKeyListener(true, false));
// ints can only hold 2,147,483,648. we allow 999,999,999
InputFilter[] fa = new InputFilter[1];
fa[0] = new InputFilter.LengthFilter(9);
mAnswer.setFilters(fa);
if (prompt.isReadOnly()) {
setBackgroundDrawable(null);
setFocusable(false);
setClickable(false);
}
Integer i = getIntegerAnswerValue();
if (i != null) {
mAnswer.setText(i.toString());
}
setupChangeListener();
}
@Override
public IAnswerData getAnswer() {
clearFocus();
String s = mAnswer.getText().toString();
if (s == null || s.equals("")) {
return null;
} else {
try {
return new IntegerData(Integer.parseInt(s));
} catch (Exception NumberFormatException) {
return null;
}
}
}
}
| Java |
/*
* 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.DateTimeData;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.form.api.FormEntryPrompt;
import org.joda.time.DateTime;
import org.odk.collect.android.application.Collect;
import android.content.Context;
import android.view.Gravity;
import android.view.inputmethod.InputMethodManager;
import android.widget.DatePicker;
import android.widget.TimePicker;
import java.util.Calendar;
import java.util.Date;
/**
* Displays a DatePicker widget. DateWidget handles leap years and does not allow dates that do not
* exist.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class DateTimeWidget extends QuestionWidget {
private DatePicker mDatePicker;
private TimePicker mTimePicker;
private DatePicker.OnDateChangedListener mDateListener;
public DateTimeWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mDatePicker = new DatePicker(getContext());
mDatePicker.setId(QuestionWidget.newUniqueId());
mDatePicker.setFocusable(!prompt.isReadOnly());
mDatePicker.setEnabled(!prompt.isReadOnly());
mTimePicker = new TimePicker(getContext());
mTimePicker.setId(QuestionWidget.newUniqueId());
mTimePicker.setFocusable(!prompt.isReadOnly());
mTimePicker.setEnabled(!prompt.isReadOnly());
mTimePicker.setPadding(0, 20, 0, 0);
String clockType =
android.provider.Settings.System.getString(context.getContentResolver(),
android.provider.Settings.System.TIME_12_24);
if (clockType == null || clockType.equalsIgnoreCase("24")) {
mTimePicker.setIs24HourView(true);
}
// If there's an answer, use it.
setAnswer();
mDateListener = new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int month, int day) {
if (mPrompt.isReadOnly()) {
setAnswer();
} else {
// handle leap years and number of days in month
// TODO
// http://code.google.com/p/android/issues/detail?id=2081
// in older versions of android (1.6ish) the datepicker lets you pick bad dates
// in newer versions, calling updateDate() calls onDatechangedListener(), causing an
// endless loop.
Calendar c = Calendar.getInstance();
c.set(year, month, 1);
int max = c.getActualMaximum(Calendar.DAY_OF_MONTH);
if (day > max) {
if (! (mDatePicker.getDayOfMonth()==day && mDatePicker.getMonth()==month && mDatePicker.getYear()==year) ) {
Collect.getInstance().getActivityLogger().logInstanceAction(DateTimeWidget.this, "onDateChanged",
String.format("%1$04d-%2$02d-%3$02d",year, month, max), mPrompt.getIndex());
mDatePicker.updateDate(year, month, max);
}
} else {
if (! (mDatePicker.getDayOfMonth()==day && mDatePicker.getMonth()==month && mDatePicker.getYear()==year) ) {
Collect.getInstance().getActivityLogger().logInstanceAction(DateTimeWidget.this, "onDateChanged",
String.format("%1$04d-%2$02d-%3$02d",year, month, day), mPrompt.getIndex());
mDatePicker.updateDate(year, month, day);
}
}
}
}
};
mTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
Collect.getInstance().getActivityLogger().logInstanceAction(DateTimeWidget.this, "onTimeChanged",
String.format("%1$02d:%2$02d",hourOfDay, minute), mPrompt.getIndex());
}
});
setGravity(Gravity.LEFT);
addView(mDatePicker);
addView(mTimePicker);
}
private void setAnswer() {
if (mPrompt.getAnswerValue() != null) {
DateTime ldt =
new DateTime(
((Date) ((DateTimeData) mPrompt.getAnswerValue()).getValue()).getTime());
mDatePicker.init(ldt.getYear(), ldt.getMonthOfYear() - 1, ldt.getDayOfMonth(),
mDateListener);
mTimePicker.setCurrentHour(ldt.getHourOfDay());
mTimePicker.setCurrentMinute(ldt.getMinuteOfHour());
} else {
// create time widget with current time as of right now
clearAnswer();
}
}
/**
* Resets date to today.
*/
@Override
public void clearAnswer() {
DateTime ldt = new DateTime();
mDatePicker.init(ldt.getYear(), ldt.getMonthOfYear() - 1, ldt.getDayOfMonth(),
mDateListener);
mTimePicker.setCurrentHour(ldt.getHourOfDay());
mTimePicker.setCurrentMinute(ldt.getMinuteOfHour());
}
@Override
public IAnswerData getAnswer() {
clearFocus();
DateTime ldt =
new DateTime(mDatePicker.getYear(), mDatePicker.getMonth() + 1,
mDatePicker.getDayOfMonth(), mTimePicker.getCurrentHour(),
mTimePicker.getCurrentMinute(), 0);
//DateTime utc = ldt.withZone(DateTimeZone.forID("UTC"));
return new DateTimeData(ldt.toDate());
}
@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) {
mDatePicker.setOnLongClickListener(l);
mTimePicker.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mDatePicker.cancelLongPress();
mTimePicker.cancelLongPress();
}
}
| Java |
/*
* 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.TimeData;
import org.javarosa.form.api.FormEntryPrompt;
import org.joda.time.DateTime;
import org.odk.collect.android.application.Collect;
import android.content.Context;
import android.view.Gravity;
import android.view.inputmethod.InputMethodManager;
import android.widget.TimePicker;
import java.util.Date;
/**
* Displays a TimePicker widget.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class TimeWidget extends QuestionWidget {
private TimePicker mTimePicker;
public TimeWidget(Context context, final FormEntryPrompt prompt) {
super(context, prompt);
mTimePicker = new TimePicker(getContext());
mTimePicker.setId(QuestionWidget.newUniqueId());
mTimePicker.setFocusable(!prompt.isReadOnly());
mTimePicker.setEnabled(!prompt.isReadOnly());
String clockType =
android.provider.Settings.System.getString(context.getContentResolver(),
android.provider.Settings.System.TIME_12_24);
if (clockType == null || clockType.equalsIgnoreCase("24")) {
mTimePicker.setIs24HourView(true);
}
// If there's an answer, use it.
if (prompt.getAnswerValue() != null) {
// create a new date time from date object using default time zone
DateTime ldt =
new DateTime(((Date) ((TimeData) prompt.getAnswerValue()).getValue()).getTime());
System.out.println("retrieving:" + ldt);
mTimePicker.setCurrentHour(ldt.getHourOfDay());
mTimePicker.setCurrentMinute(ldt.getMinuteOfHour());
} else {
// create time widget with current time as of right now
clearAnswer();
}
mTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
Collect.getInstance().getActivityLogger().logInstanceAction(TimeWidget.this, "onTimeChanged",
String.format("%1$02d:%2$02d",hourOfDay, minute), mPrompt.getIndex());
}
});
setGravity(Gravity.LEFT);
addView(mTimePicker);
}
/**
* Resets time to today.
*/
@Override
public void clearAnswer() {
DateTime ldt = new DateTime();
mTimePicker.setCurrentHour(ldt.getHourOfDay());
mTimePicker.setCurrentMinute(ldt.getMinuteOfHour());
}
@Override
public IAnswerData getAnswer() {
clearFocus();
// use picker time, convert to today's date, store as utc
DateTime ldt =
(new DateTime()).withTime(mTimePicker.getCurrentHour(), mTimePicker.getCurrentMinute(),
0, 0);
//DateTime utc = ldt.withZone(DateTimeZone.forID("UTC"));
System.out.println("storing:" + ldt);
return new TimeData(ldt.toDate());
}
@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) {
mTimePicker.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mTimePicker.cancelLongPress();
}
}
| Java |
/*
* 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.text.NumberFormat;
import org.javarosa.core.model.data.DecimalData;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.form.api.FormEntryPrompt;
import android.content.Context;
import android.text.InputFilter;
import android.text.InputType;
import android.text.method.DigitsKeyListener;
import android.util.TypedValue;
/**
* A widget that restricts values to floating point numbers.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class DecimalWidget extends StringWidget {
private Double getDoubleAnswerValue() {
IAnswerData dataHolder = mPrompt.getAnswerValue();
Double d = null;
if (dataHolder != null) {
Object dataValue = dataHolder.getValue();
if ( dataValue != null ) {
if (dataValue instanceof Integer){
d = Double.valueOf(((Integer)dataValue).intValue());
} else {
d = (Double) dataValue;
}
}
}
return d;
}
public DecimalWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt, true);
// formatting
mAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mAnswer.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
// needed to make long readonly text scroll
mAnswer.setHorizontallyScrolling(false);
mAnswer.setSingleLine(false);
// only numbers are allowed
mAnswer.setKeyListener(new DigitsKeyListener(true, true));
// only 15 characters allowed
InputFilter[] fa = new InputFilter[1];
fa[0] = new InputFilter.LengthFilter(15);
mAnswer.setFilters(fa);
Double d = getDoubleAnswerValue();
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(15);
nf.setMaximumIntegerDigits(15);
nf.setGroupingUsed(false);
if (d != null) {
// truncate to 15 digits max...
String dString = nf.format(d);
d = Double.parseDouble(dString.replace(',', '.'));
mAnswer.setText(d.toString());
}
// disable if read only
if (prompt.isReadOnly()) {
setBackgroundDrawable(null);
setFocusable(false);
setClickable(false);
}
setupChangeListener();
}
@Override
public IAnswerData getAnswer() {
clearFocus();
String s = mAnswer.getText().toString();
if (s == null || s.equals("")) {
return null;
} else {
try {
return new DecimalData(Double.valueOf(s).doubleValue());
} catch (Exception NumberFormatException) {
return null;
}
}
}
}
| Java |
/*
* 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.DateData;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.form.api.FormEntryPrompt;
import org.joda.time.DateTime;
import org.odk.collect.android.application.Collect;
import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.DatePicker;
import java.lang.reflect.Field;
import java.util.Calendar;
import java.util.Date;
/**
* Displays a DatePicker widget. DateWidget handles leap years and does not allow dates that do not
* exist.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class DateWidget extends QuestionWidget {
private DatePicker mDatePicker;
private DatePicker.OnDateChangedListener mDateListener;
private boolean hideDay = false;
private boolean hideMonth = false;
public DateWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mDatePicker = new DatePicker(getContext());
mDatePicker.setId(QuestionWidget.newUniqueId());
mDatePicker.setFocusable(!prompt.isReadOnly());
mDatePicker.setEnabled(!prompt.isReadOnly());
hideDayFieldIfNotInFormat(prompt);
// If there's an answer, use it.
setAnswer();
mDateListener = new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int month, int day) {
if (mPrompt.isReadOnly()) {
setAnswer();
} else {
// TODO support dates <1900 >2100
// handle leap years and number of days in month
// http://code.google.com/p/android/issues/detail?id=2081
Calendar c = Calendar.getInstance();
c.set(year, month, 1);
int max = c.getActualMaximum(Calendar.DAY_OF_MONTH);
// in older versions of android (1.6ish) the datepicker lets you pick bad dates
// in newer versions, calling updateDate() calls onDatechangedListener(), causing an
// endless loop.
if (day > max) {
if (! (mDatePicker.getDayOfMonth()==day && mDatePicker.getMonth()==month && mDatePicker.getYear()==year) ) {
Collect.getInstance().getActivityLogger().logInstanceAction(DateWidget.this, "onDateChanged",
String.format("%1$04d-%2$02d-%3$02d",year, month, max), mPrompt.getIndex());
mDatePicker.updateDate(year, month, max);
}
} else {
if (! (mDatePicker.getDayOfMonth()==day && mDatePicker.getMonth()==month && mDatePicker.getYear()==year) ) {
Collect.getInstance().getActivityLogger().logInstanceAction(DateWidget.this, "onDateChanged",
String.format("%1$04d-%2$02d-%3$02d",year, month, day), mPrompt.getIndex());
mDatePicker.updateDate(year, month, day);
}
}
}
}
};
setGravity(Gravity.LEFT);
addView(mDatePicker);
}
private void hideDayFieldIfNotInFormat(FormEntryPrompt prompt) {
String appearance = prompt.getQuestion().getAppearanceAttr();
if ( appearance == null ) return;
if ( "month-year".equals(appearance) ) {
hideDay = true;
} else if ( "year".equals(appearance) ) {
hideMonth = true;
}
if ( hideMonth || hideDay ) {
for (Field datePickerDialogField : this.mDatePicker.getClass().getDeclaredFields()) {
if ("mDayPicker".equals(datePickerDialogField.getName()) ||
"mDaySpinner".equals(datePickerDialogField.getName())) {
datePickerDialogField.setAccessible(true);
Object dayPicker = new Object();
try {
dayPicker = datePickerDialogField.get(this.mDatePicker);
} catch (Exception e) {
e.printStackTrace();
}
((View) dayPicker).setVisibility(View.GONE);
}
if ( hideMonth ) {
if ("mMonthPicker".equals(datePickerDialogField.getName()) ||
"mMonthSpinner".equals(datePickerDialogField.getName())) {
datePickerDialogField.setAccessible(true);
Object monthPicker = new Object();
try {
monthPicker = datePickerDialogField.get(this.mDatePicker);
} catch (Exception e) {
e.printStackTrace();
}
((View) monthPicker).setVisibility(View.GONE);
}
}
}
}
}
private void setAnswer() {
if (mPrompt.getAnswerValue() != null) {
DateTime ldt =
new DateTime(((Date) ((DateData) mPrompt.getAnswerValue()).getValue()).getTime());
mDatePicker.init(ldt.getYear(), ldt.getMonthOfYear() - 1, ldt.getDayOfMonth(),
mDateListener);
} else {
// create date widget with current time as of right now
clearAnswer();
}
}
/**
* Resets date to today.
*/
@Override
public void clearAnswer() {
DateTime ldt = new DateTime();
mDatePicker.init(ldt.getYear(), ldt.getMonthOfYear() - 1, ldt.getDayOfMonth(),
mDateListener);
}
@Override
public IAnswerData getAnswer() {
clearFocus();
DateTime ldt =
new DateTime(mDatePicker.getYear(), hideMonth ? 1 : mDatePicker.getMonth() + 1,
(hideMonth || hideDay) ? 1 : mDatePicker.getDayOfMonth(), 0, 0);
// DateTime utc = ldt.withZone(DateTimeZone.forID("UTC"));
return new DateData(ldt.toDate());
}
@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) {
mDatePicker.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mDatePicker.cancelLongPress();
}
}
| Java |
/*
* 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.core.model.data.IntegerData;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.activities.FormEntryActivity;
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.text.InputFilter;
import android.text.InputType;
import android.text.method.DigitsKeyListener;
/**
* Launch an external app to supply an integer value. If the app
* does not launch, enable the text area for regular data entry.
*
* See {@link org.odk.collect.android.widgets.ExStringWidget} for usage.
*
* @author mitchellsundt@gmail.com
*
*/
public class ExIntegerWidget extends ExStringWidget {
private Integer getIntegerAnswerValue() {
IAnswerData dataHolder = mPrompt.getAnswerValue();
Integer d = null;
if (dataHolder != null) {
Object dataValue = dataHolder.getValue();
if ( dataValue != null ) {
if (dataValue instanceof Double){
d = Integer.valueOf(((Double) dataValue).intValue());
} else {
d = (Integer)dataValue;
}
}
}
return d;
}
public ExIntegerWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mAnswer.setInputType(InputType.TYPE_NUMBER_FLAG_SIGNED);
// only allows numbers and no periods
mAnswer.setKeyListener(new DigitsKeyListener(true, false));
// ints can only hold 2,147,483,648. we allow 999,999,999
InputFilter[] fa = new InputFilter[1];
fa[0] = new InputFilter.LengthFilter(9);
mAnswer.setFilters(fa);
Integer i = getIntegerAnswerValue();
if (i != null) {
mAnswer.setText(i.toString());
}
}
@Override
protected void fireActivity(Intent i) throws ActivityNotFoundException {
i.putExtra("value", getIntegerAnswerValue());
Collect.getInstance().getActivityLogger().logInstanceAction(this, "launchIntent",
i.getAction(), mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.EX_INT_CAPTURE);
}
@Override
public IAnswerData getAnswer() {
String s = mAnswer.getText().toString();
if (s == null || s.equals("")) {
return null;
} else {
try {
return new IntegerData(Integer.parseInt(s));
} catch (Exception NumberFormatException) {
return null;
}
}
}
/**
* Allows answer to be set externally in {@Link FormEntryActivity}.
*/
@Override
public void setBinaryData(Object answer) {
mAnswer.setText( answer == null ? null : ((Integer) answer).toString());
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
}
| Java |
/*
* 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.Vector;
import org.javarosa.core.model.SelectChoice;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.SelectOneData;
import org.javarosa.core.model.data.helper.Selection;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.AdvanceToNextListener;
import org.odk.collect.android.views.MediaLayout;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.inputmethod.InputMethodManager;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
/**
* SelectOneWidgets handles select-one fields using radio buttons. Unlike the classic
* SelectOneWidget, when a user clicks an option they are then immediately advanced to the next
* question.
*
* @author Jeff Beorse (jeff@beorse.net)
*/
public class SelectOneAutoAdvanceWidget extends QuestionWidget implements OnCheckedChangeListener {
Vector<SelectChoice> mItems; // may take a while to compute
ArrayList<RadioButton> buttons;
AdvanceToNextListener listener;
public SelectOneAutoAdvanceWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
LayoutInflater inflater = LayoutInflater.from(getContext());
mItems = prompt.getSelectChoices();
buttons = new ArrayList<RadioButton>();
listener = (AdvanceToNextListener) context;
String s = null;
if (prompt.getAnswerValue() != null) {
s = ((Selection) prompt.getAnswerValue().getValue()).getValue();
}
// use this for recycle
Bitmap b = BitmapFactory.decodeResource(getContext().getResources(),
R.drawable.expander_ic_right);
if (mItems != null) {
for (int i = 0; i < mItems.size(); i++) {
RelativeLayout thisParentLayout =
(RelativeLayout) inflater.inflate(R.layout.quick_select_layout, null);
LinearLayout questionLayout = (LinearLayout) thisParentLayout.getChildAt(0);
ImageView rightArrow = (ImageView) thisParentLayout.getChildAt(1);
RadioButton r = new RadioButton(getContext());
r.setText(prompt.getSelectChoiceText(mItems.get(i)));
r.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
r.setTag(Integer.valueOf(i));
r.setId(QuestionWidget.newUniqueId());
r.setEnabled(!prompt.isReadOnly());
r.setFocusable(!prompt.isReadOnly());
rightArrow.setImageBitmap(b);
buttons.add(r);
if (mItems.get(i).getValue().equals(s)) {
r.setChecked(true);
}
r.setOnCheckedChangeListener(this);
String audioURI = null;
audioURI =
prompt.getSpecialFormSelectChoiceText(mItems.get(i),
FormEntryCaption.TEXT_FORM_AUDIO);
String imageURI = null;
imageURI =
prompt.getSpecialFormSelectChoiceText(mItems.get(i),
FormEntryCaption.TEXT_FORM_IMAGE);
String videoURI = null;
videoURI = prompt.getSpecialFormSelectChoiceText(mItems.get(i), "video");
String bigImageURI = null;
bigImageURI = prompt.getSpecialFormSelectChoiceText(mItems.get(i), "big-image");
MediaLayout mediaLayout = new MediaLayout(getContext());
mediaLayout.setAVT(prompt.getIndex(), "", r, audioURI, imageURI, videoURI, bigImageURI);
if (i != mItems.size() - 1) {
// Last, add the dividing line (except for the last element)
ImageView divider = new ImageView(getContext());
divider.setBackgroundResource(android.R.drawable.divider_horizontal_bright);
mediaLayout.addDivider(divider);
}
questionLayout.addView(mediaLayout);
addView(thisParentLayout);
}
}
}
@Override
public void clearAnswer() {
for (RadioButton button : this.buttons) {
if (button.isChecked()) {
button.setChecked(false);
return;
}
}
}
@Override
public IAnswerData getAnswer() {
int i = getCheckedId();
if (i == -1) {
return null;
} else {
SelectChoice sc = mItems.elementAt(i);
return new SelectOneData(new Selection(sc));
}
}
@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);
}
public int getCheckedId() {
for (int i = 0; i < buttons.size(); ++i) {
RadioButton button = buttons.get(i);
if (button.isChecked()) {
return i;
}
}
return -1;
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!buttonView.isPressed()) {
return;
}
if (!isChecked) {
// If it got unchecked, we don't care.
return;
}
for (RadioButton button : this.buttons) {
if (button.isChecked() && !(buttonView == button)) {
button.setChecked(false);
}
}
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onCheckedChanged",
mItems.get((Integer)buttonView.getTag()).getValue(), mPrompt.getIndex());
listener.advance();
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
for (RadioButton r : buttons) {
r.setOnLongClickListener(l);
}
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
for (RadioButton r : buttons) {
r.cancelLongPress();
}
}
}
| Java |
/*
* 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 java.util.Date;
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.MediaUtils;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
* Widget that allows user to take pictures, sounds or video and add them to the
* form.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class ImageWebViewWidget extends QuestionWidget implements IBinaryWidget {
private final static String t = "MediaWidget";
private Button mCaptureButton;
private Button mChooseButton;
private WebView mImageDisplay;
private String mBinaryName;
private String mInstanceFolder;
private TextView mErrorTextView;
private String constructImageElement() {
File f = new File(mInstanceFolder + File.separator + mBinaryName);
Display display = ((WindowManager) getContext().getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay();
int screenWidth = display.getWidth();
// int screenHeight = display.getHeight();
String imgElement = f.exists() ? ("<img align=\"middle\" src=\"file:///"
+ f.getAbsolutePath()
+
// Appending the time stamp to the filename is a hack to prevent
// caching.
"?"
+ new Date().getTime()
+ "\" width=\""
+ Integer.toString(screenWidth - 10) + "\" >")
: "";
return imgElement;
}
public boolean suppressFlingGesture(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
if (mImageDisplay == null
|| mImageDisplay.getVisibility() != View.VISIBLE) {
return false;
}
Rect rect = new Rect();
mImageDisplay.getHitRect(rect);
// Log.i(t, "hitRect: " + rect.left + "," + rect.top + " : " +
// rect.right + "," + rect.bottom );
// Log.i(t, "e1 Raw, Clean: " + e1.getRawX() + "," + e1.getRawY() +
// " : " + e1.getX() + "," + e1.getY());
// Log.i(t, "e2 Raw, Clean: " + e2.getRawX() + "," + e2.getRawY() +
// " : " + e2.getX() + "," + e2.getY());
// starts in WebView
if (rect.contains((int) e1.getRawX(), (int) e1.getRawY())) {
return true;
}
// ends in WebView
if (rect.contains((int) e2.getRawX(), (int) e2.getRawY())) {
return true;
}
// transits WebView
if (rect.contains((int) ((e1.getRawX() + e2.getRawX()) / 2.0),
(int) ((e1.getRawY() + e2.getRawY()) / 2.0))) {
return true;
}
// Log.i(t, "NOT SUPPRESSED");
return false;
}
public ImageWebViewWidget(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 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(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// 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.
i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
Uri.fromFile(new File(Collect.TMPFILE_PATH)));
try {
Collect.getInstance().getFormController()
.setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.IMAGE_CAPTURE);
} catch (ActivityNotFoundException e) {
Toast.makeText(
getContext(),
getContext().getString(R.string.activity_not_found,
"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) {
mImageDisplay = new WebView(getContext());
mImageDisplay.setId(QuestionWidget.newUniqueId());
mImageDisplay.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
mImageDisplay.getSettings().setBuiltInZoomControls(true);
mImageDisplay.getSettings().setDefaultZoom(
WebSettings.ZoomDensity.FAR);
mImageDisplay.setVisibility(View.VISIBLE);
mImageDisplay.setLayoutParams(params);
// HTML is used to display the image.
String html = "<body>" + constructImageElement() + "</body>";
mImageDisplay.loadDataWithBaseURL("file:///" + mInstanceFolder
+ File.separator, html, "text/html", "utf-8", "");
addView(mImageDisplay);
}
}
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();
if (mImageDisplay != null) {
// update HTML to not hold image file reference.
String html = "<body></body>";
mImageDisplay.loadDataWithBaseURL("file:///" + mInstanceFolder
+ File.separator, html, "text/html", "utf-8", "");
mImageDisplay.setVisibility(View.INVISIBLE);
}
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);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mCaptureButton.cancelLongPress();
mChooseButton.cancelLongPress();
}
}
| Java |
/*
* 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.data.IAnswerData;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.views.MediaLayout;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public abstract class QuestionWidget extends LinearLayout {
@SuppressWarnings("unused")
private final static String t = "QuestionWidget";
private static int idGenerator = 1211322;
/**
* Generate a unique ID to keep Android UI happy when the screen orientation
* changes.
*
* @return
*/
public static int newUniqueId() {
return ++idGenerator;
}
private LinearLayout.LayoutParams mLayout;
protected FormEntryPrompt mPrompt;
protected final int mQuestionFontsize;
protected final int mAnswerFontsize;
private TextView mQuestionText;
private MediaLayout mediaLayout;
private TextView mHelpText;
public QuestionWidget(Context context, FormEntryPrompt p) {
super(context);
mQuestionFontsize = Collect.getQuestionFontsize();
mAnswerFontsize = mQuestionFontsize + 2;
mPrompt = p;
setOrientation(LinearLayout.VERTICAL);
setGravity(Gravity.TOP);
setPadding(0, 7, 0, 0);
mLayout =
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
mLayout.setMargins(10, 0, 10, 0);
addQuestionText(p);
addHelpText(p);
}
public void playAudio() {
mediaLayout.playAudio();
}
public void playVideo() {
mediaLayout.playVideo();
}
public FormEntryPrompt getPrompt() {
return mPrompt;
}
// http://code.google.com/p/android/issues/detail?id=8488
private void recycleDrawablesRecursive(ViewGroup viewGroup, List<ImageView> images) {
int childCount = viewGroup.getChildCount();
for(int index = 0; index < childCount; index++)
{
View child = viewGroup.getChildAt(index);
if ( child instanceof ImageView ) {
images.add((ImageView)child);
} else if ( child instanceof ViewGroup ) {
recycleDrawablesRecursive((ViewGroup) child, images);
}
}
viewGroup.destroyDrawingCache();
}
// http://code.google.com/p/android/issues/detail?id=8488
public void recycleDrawables() {
List<ImageView> images = new ArrayList<ImageView>();
// collect all the image views
recycleDrawablesRecursive(this, images);
for ( ImageView imageView : images ) {
imageView.destroyDrawingCache();
Drawable d = imageView.getDrawable();
if ( d != null && d instanceof BitmapDrawable) {
imageView.setImageDrawable(null);
BitmapDrawable bd = (BitmapDrawable) d;
Bitmap bmp = bd.getBitmap();
if ( bmp != null ) {
bmp.recycle();
}
}
}
}
// Abstract methods
public abstract IAnswerData getAnswer();
public abstract void clearAnswer();
public abstract void setFocus(Context context);
public abstract void setOnLongClickListener(OnLongClickListener l);
/**
* Override this to implement fling gesture suppression (e.g. for embedded WebView treatments).
* @param e1
* @param e2
* @param velocityX
* @param velocityY
* @return true if the fling gesture should be suppressed
*/
public boolean suppressFlingGesture(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
/**
* Add a Views containing the question text, audio (if applicable), and image (if applicable).
* To satisfy the RelativeLayout constraints, we add the audio first if it exists, then the
* TextView to fit the rest of the space, then the image if applicable.
*/
protected void addQuestionText(FormEntryPrompt p) {
String imageURI = p.getImageText();
String audioURI = p.getAudioText();
String videoURI = p.getSpecialFormQuestionText("video");
// shown when image is clicked
String bigImageURI = p.getSpecialFormQuestionText("big-image");
// 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);
}
// Create the layout for audio, image, text
mediaLayout = new MediaLayout(getContext());
mediaLayout.setAVT(p.getIndex(), "", mQuestionText, audioURI, imageURI, videoURI, bigImageURI);
addView(mediaLayout, mLayout);
}
/**
* Add a TextView containing the help text.
*/
private void addHelpText(FormEntryPrompt p) {
String s = p.getHelpText();
if (s != null && !s.equals("")) {
mHelpText = new TextView(getContext());
mHelpText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize - 3);
mHelpText.setPadding(0, -5, 0, 7);
// wrap to the widget of view
mHelpText.setHorizontallyScrolling(false);
mHelpText.setText(s);
mHelpText.setTypeface(null, Typeface.ITALIC);
addView(mHelpText, mLayout);
}
}
/**
* Every subclassed widget should override this, adding any views they may contain, and calling
* super.cancelLongPress()
*/
public void cancelLongPress() {
super.cancelLongPress();
if (mQuestionText != null) {
mQuestionText.cancelLongPress();
}
if (mHelpText != null) {
mHelpText.cancelLongPress();
}
}
}
| Java |
/*
* 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.text.NumberFormat;
import org.javarosa.core.model.data.DecimalData;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.activities.FormEntryActivity;
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.text.InputFilter;
import android.text.InputType;
import android.text.method.DigitsKeyListener;
/**
* Launch an external app to supply a decimal value. If the app
* does not launch, enable the text area for regular data entry.
*
* See {@link org.odk.collect.android.widgets.ExStringWidget} for usage.
*
* @author mitchellsundt@gmail.com
*
*/
public class ExDecimalWidget extends ExStringWidget {
private Double getDoubleAnswerValue() {
IAnswerData dataHolder = mPrompt.getAnswerValue();
Double d = null;
if (dataHolder != null) {
Object dataValue = dataHolder.getValue();
if ( dataValue != null ) {
if (dataValue instanceof Integer){
d = Double.valueOf(((Integer)dataValue).intValue());
} else {
d = (Double) dataValue;
}
}
}
return d;
}
public ExDecimalWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mAnswer.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
// only allows numbers and no periods
mAnswer.setKeyListener(new DigitsKeyListener(true, true));
// only 15 characters allowed
InputFilter[] fa = new InputFilter[1];
fa[0] = new InputFilter.LengthFilter(15);
mAnswer.setFilters(fa);
Double d = getDoubleAnswerValue();
// apparently an attempt at rounding to no more than 15 digit precision???
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(15);
nf.setMaximumIntegerDigits(15);
nf.setGroupingUsed(false);
if (d != null) {
// truncate to 15 digits max...
String dString = nf.format(d);
d = Double.parseDouble(dString.replace(',', '.')); // in case , is decimal pt
mAnswer.setText(d.toString());
}
}
@Override
protected void fireActivity(Intent i) throws ActivityNotFoundException {
i.putExtra("value", getDoubleAnswerValue());
Collect.getInstance().getActivityLogger().logInstanceAction(this, "launchIntent",
i.getAction(), mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.EX_DECIMAL_CAPTURE);
}
@Override
public IAnswerData getAnswer() {
String s = mAnswer.getText().toString();
if (s == null || s.equals("")) {
return null;
} else {
try {
return new DecimalData(Double.valueOf(s).doubleValue());
} catch (Exception NumberFormatException) {
return null;
}
}
}
/**
* Allows answer to be set externally in {@Link FormEntryActivity}.
*/
@Override
public void setBinaryData(Object answer) {
mAnswer.setText( answer == null ? null : ((Double) answer).toString());
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
}
| Java |
/*
* 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.tasks;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.javarosa.xform.parse.XFormParser;
import org.kxml2.kdom.Element;
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.logic.FormDetails;
import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns;
import org.odk.collect.android.utilities.DocumentFetchResult;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.utilities.WebUtils;
import org.opendatakit.httpclientandroidlib.HttpResponse;
import org.opendatakit.httpclientandroidlib.HttpStatus;
import org.opendatakit.httpclientandroidlib.client.HttpClient;
import org.opendatakit.httpclientandroidlib.client.methods.HttpGet;
import org.opendatakit.httpclientandroidlib.protocol.HttpContext;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
/**
* Background task for downloading a given list of forms. We assume right now that the forms are
* coming from the same server that presented the form list, but theoretically that won't always be
* true.
*
* @author msundt
* @author carlhartung
*/
public class DownloadFormsTask extends
AsyncTask<ArrayList<FormDetails>, String, HashMap<FormDetails, String>> {
private static final String t = "DownloadFormsTask";
private static final String MD5_COLON_PREFIX = "md5:";
private FormDownloaderListener mStateListener;
private static final String NAMESPACE_OPENROSA_ORG_XFORMS_XFORMS_MANIFEST =
"http://openrosa.org/xforms/xformsManifest";
private boolean isXformsManifestNamespacedElement(Element e) {
return e.getNamespace().equalsIgnoreCase(NAMESPACE_OPENROSA_ORG_XFORMS_XFORMS_MANIFEST);
}
@Override
protected HashMap<FormDetails, String> doInBackground(ArrayList<FormDetails>... values) {
ArrayList<FormDetails> toDownload = values[0];
int total = toDownload.size();
int count = 1;
Collect.getInstance().getActivityLogger().logAction(this, "downloadForms", String.valueOf(total));
HashMap<FormDetails, String> result = new HashMap<FormDetails, String>();
for (int i = 0; i < total; i++) {
FormDetails fd = toDownload.get(i);
publishProgress(fd.formName, Integer.valueOf(count).toString(), Integer.valueOf(total)
.toString());
String message = "";
try {
// get the xml file
// if we've downloaded a duplicate, this gives us the file
File dl = downloadXform(fd.formName, fd.downloadUrl);
Cursor alreadyExists = null;
Uri uri = null;
try {
String[] projection = {
FormsColumns._ID, FormsColumns.FORM_FILE_PATH
};
String[] selectionArgs = {
dl.getAbsolutePath()
};
String selection = FormsColumns.FORM_FILE_PATH + "=?";
alreadyExists = Collect.getInstance()
.getContentResolver()
.query(FormsColumns.CONTENT_URI, projection, selection, selectionArgs,
null);
if (alreadyExists.getCount() <= 0) {
// doesn't exist, so insert it
ContentValues v = new ContentValues();
v.put(FormsColumns.FORM_FILE_PATH, dl.getAbsolutePath());
HashMap<String, String> formInfo = FileUtils.parseXML(dl);
v.put(FormsColumns.DISPLAY_NAME, formInfo.get(FileUtils.TITLE));
v.put(FormsColumns.JR_VERSION, formInfo.get(FileUtils.VERSION));
v.put(FormsColumns.JR_FORM_ID, formInfo.get(FileUtils.FORMID));
v.put(FormsColumns.SUBMISSION_URI, formInfo.get(FileUtils.SUBMISSIONURI));
v.put(FormsColumns.BASE64_RSA_PUBLIC_KEY, formInfo.get(FileUtils.BASE64_RSA_PUBLIC_KEY));
uri =
Collect.getInstance().getContentResolver()
.insert(FormsColumns.CONTENT_URI, v);
Collect.getInstance().getActivityLogger().logAction(this, "insert", dl.getAbsolutePath());
} else {
alreadyExists.moveToFirst();
uri =
Uri.withAppendedPath(FormsColumns.CONTENT_URI,
alreadyExists.getString(alreadyExists.getColumnIndex(FormsColumns._ID)));
Collect.getInstance().getActivityLogger().logAction(this, "refresh", dl.getAbsolutePath());
}
} finally {
if ( alreadyExists != null ) {
alreadyExists.close();
}
}
if (fd.manifestUrl != null) {
String formMediaPath = null;
Cursor c = null;
try {
c = Collect.getInstance().getContentResolver()
.query(uri, null, null, null, null);
if (c.getCount() > 0) {
// should be exactly 1
c.moveToFirst();
formMediaPath = c.getString(c.getColumnIndex(FormsColumns.FORM_MEDIA_PATH));
}
} finally {
if ( c != null ) {
c.close();
}
}
if ( formMediaPath != null ) {
String error =
downloadManifestAndMediaFiles(formMediaPath, fd,
count, total);
if (error != null) {
message += error;
}
}
} else {
Log.i(t, "No Manifest for: " + fd.formName);
}
} catch (SocketTimeoutException se) {
se.printStackTrace();
message += se.getMessage();
} catch (Exception e) {
e.printStackTrace();
if (e.getCause() != null) {
message += e.getCause().getMessage();
} else {
message += e.getMessage();
}
}
count++;
if (message.equalsIgnoreCase("")) {
message = Collect.getInstance().getString(R.string.success);
}
result.put(fd, message);
}
return result;
}
/**
* Takes the formName and the URL and attempts to download the specified file. Returns a file
* object representing the downloaded file.
*
* @param formName
* @param url
* @return
* @throws Exception
*/
private File downloadXform(String formName, String url) throws Exception {
File f = null;
// clean up friendly form name...
String rootName = formName.replaceAll("[^\\p{L}\\p{Digit}]", " ");
rootName = rootName.replaceAll("\\p{javaWhitespace}+", " ");
rootName = rootName.trim();
// proposed name of xml file...
String path = Collect.FORMS_PATH + File.separator + rootName + ".xml";
int i = 2;
f = new File(path);
while (f.exists()) {
path = Collect.FORMS_PATH + File.separator + rootName + "_" + i + ".xml";
f = new File(path);
i++;
}
downloadFile(f, url);
// we've downloaded the file, and we may have renamed it
// make sure it's not the same as a file we already have
String[] projection = {
FormsColumns.FORM_FILE_PATH
};
String[] selectionArgs = {
FileUtils.getMd5Hash(f)
};
String selection = FormsColumns.MD5_HASH + "=?";
Cursor c = null;
try {
c = Collect.getInstance().getContentResolver()
.query(FormsColumns.CONTENT_URI, projection, selection, selectionArgs, null);
if (c.getCount() > 0) {
// Should be at most, 1
c.moveToFirst();
// delete the file we just downloaded, because it's a duplicate
f.delete();
// set the file returned to the file we already had
f = new File(c.getString(c.getColumnIndex(FormsColumns.FORM_FILE_PATH)));
}
} finally {
if ( c != null ) {
c.close();
}
}
return f;
}
/**
* Common routine to download a document from the downloadUrl and save the contents in the file
* 'f'. Shared by media file download and form file download.
*
* @param f
* @param downloadUrl
* @throws Exception
*/
private void downloadFile(File f, String downloadUrl) throws Exception {
URI uri = null;
try {
// assume the downloadUrl is escaped properly
URL url = new URL(downloadUrl);
uri = url.toURI();
} catch (MalformedURLException e) {
e.printStackTrace();
throw e;
} catch (URISyntaxException e) {
e.printStackTrace();
throw e;
}
// WiFi network connections can be renegotiated during a large form download sequence.
// This will cause intermittent download failures. Silently retry once after each
// failure. Only if there are two consecutive failures, do we abort.
boolean success = false;
int attemptCount = 0;
final int MAX_ATTEMPT_COUNT = 2;
while ( !success && ++attemptCount <= MAX_ATTEMPT_COUNT ) {
// get shared HttpContext so that authentication and cookies are retained.
HttpContext localContext = Collect.getInstance().getHttpContext();
HttpClient httpclient = WebUtils.createHttpClient(WebUtils.CONNECTION_TIMEOUT);
// set up request...
HttpGet req = WebUtils.createOpenRosaHttpGet(uri);
HttpResponse response = null;
try {
response = httpclient.execute(req, localContext);
int statusCode = response.getStatusLine().getStatusCode();
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 errMsg =
Collect.getInstance().getString(R.string.file_fetch_failed, downloadUrl,
response.getStatusLine().getReasonPhrase(), statusCode);
Log.e(t, errMsg);
throw new Exception(errMsg);
}
// write connection to file
InputStream is = null;
OutputStream os = null;
try {
is = response.getEntity().getContent();
os = new FileOutputStream(f);
byte buf[] = new byte[1024];
int len;
while ((len = is.read(buf)) > 0) {
os.write(buf, 0, len);
}
os.flush();
success = true;
} finally {
if (os != null) {
try {
os.close();
} catch (Exception e) {
}
}
if (is != null) {
try {
// ensure stream is consumed...
final long count = 1024L;
while (is.skip(count) == count)
;
} catch (Exception e) {
// no-op
}
try {
is.close();
} catch (Exception e) {
}
}
}
} catch (Exception e) {
Log.e(t, e.toString());
e.printStackTrace();
// silently retry unless this is the last attempt,
// in which case we rethrow the exception.
if ( attemptCount == MAX_ATTEMPT_COUNT ) {
throw e;
}
}
}
}
private static class MediaFile {
final String filename;
final String hash;
final String downloadUrl;
MediaFile(String filename, String hash, String downloadUrl) {
this.filename = filename;
this.hash = hash;
this.downloadUrl = downloadUrl;
}
}
private String downloadManifestAndMediaFiles(String mediaPath, FormDetails fd, int count,
int total) {
if (fd.manifestUrl == null)
return null;
publishProgress(Collect.getInstance().getString(R.string.fetching_manifest, fd.formName),
Integer.valueOf(count).toString(), Integer.valueOf(total).toString());
List<MediaFile> files = new ArrayList<MediaFile>();
// get shared HttpContext so that authentication and cookies are retained.
HttpContext localContext = Collect.getInstance().getHttpContext();
HttpClient httpclient = WebUtils.createHttpClient(WebUtils.CONNECTION_TIMEOUT);
DocumentFetchResult result =
WebUtils.getXmlDocument(fd.manifestUrl, localContext, httpclient);
if (result.errorMessage != null) {
return result.errorMessage;
}
String errMessage = Collect.getInstance().getString(R.string.access_error, fd.manifestUrl);
if (!result.isOpenRosaResponse) {
errMessage += Collect.getInstance().getString(R.string.manifest_server_error);
Log.e(t, errMessage);
return errMessage;
}
// Attempt OpenRosa 1.0 parsing
Element manifestElement = result.doc.getRootElement();
if (!manifestElement.getName().equals("manifest")) {
errMessage +=
Collect.getInstance().getString(R.string.root_element_error,
manifestElement.getName());
Log.e(t, errMessage);
return errMessage;
}
String namespace = manifestElement.getNamespace();
if (!isXformsManifestNamespacedElement(manifestElement)) {
errMessage += Collect.getInstance().getString(R.string.root_namespace_error, namespace);
Log.e(t, errMessage);
return errMessage;
}
int nElements = manifestElement.getChildCount();
for (int i = 0; i < nElements; ++i) {
if (manifestElement.getType(i) != Element.ELEMENT) {
// e.g., whitespace (text)
continue;
}
Element mediaFileElement = (Element) manifestElement.getElement(i);
if (!isXformsManifestNamespacedElement(mediaFileElement)) {
// someone else's extension?
continue;
}
String name = mediaFileElement.getName();
if (name.equalsIgnoreCase("mediaFile")) {
String filename = null;
String hash = null;
String downloadUrl = null;
// don't process descriptionUrl
int childCount = mediaFileElement.getChildCount();
for (int j = 0; j < childCount; ++j) {
if (mediaFileElement.getType(j) != Element.ELEMENT) {
// e.g., whitespace (text)
continue;
}
Element child = mediaFileElement.getElement(j);
if (!isXformsManifestNamespacedElement(child)) {
// someone else's extension?
continue;
}
String tag = child.getName();
if (tag.equals("filename")) {
filename = XFormParser.getXMLText(child, true);
if (filename != null && filename.length() == 0) {
filename = null;
}
} else if (tag.equals("hash")) {
hash = XFormParser.getXMLText(child, true);
if (hash != null && hash.length() == 0) {
hash = null;
}
} else if (tag.equals("downloadUrl")) {
downloadUrl = XFormParser.getXMLText(child, true);
if (downloadUrl != null && downloadUrl.length() == 0) {
downloadUrl = null;
}
}
}
if (filename == null || downloadUrl == null || hash == null) {
errMessage +=
Collect.getInstance().getString(R.string.manifest_tag_error,
Integer.toString(i));
Log.e(t, errMessage);
return errMessage;
}
files.add(new MediaFile(filename, hash, downloadUrl));
}
}
// OK we now have the full set of files to download...
Log.i(t, "Downloading " + files.size() + " media files.");
int mediaCount = 0;
if (files.size() > 0) {
FileUtils.createFolder(mediaPath);
File mediaDir = new File(mediaPath);
for (MediaFile toDownload : files) {
if (isCancelled()) {
return "cancelled";
}
++mediaCount;
publishProgress(
Collect.getInstance().getString(R.string.form_download_progress, fd.formName,
mediaCount, files.size()), Integer.valueOf(count).toString(), Integer
.valueOf(total).toString());
try {
File mediaFile = new File(mediaDir, toDownload.filename);
if (!mediaFile.exists()) {
downloadFile(mediaFile, toDownload.downloadUrl);
} else {
String currentFileHash = FileUtils.getMd5Hash(mediaFile);
String downloadFileHash = toDownload.hash.substring(MD5_COLON_PREFIX.length());
if (!currentFileHash.contentEquals(downloadFileHash)) {
// if the hashes match, it's the same file
// otherwise delete our current one and replace it with the new one
mediaFile.delete();
downloadFile(mediaFile, toDownload.downloadUrl);
} else {
// exists, and the hash is the same
// no need to download it again
Log.i(t, "Skipping media file fetch -- file hashes identical: " + mediaFile.getAbsolutePath());
}
}
} catch (Exception e) {
return e.getLocalizedMessage();
}
}
}
return null;
}
@Override
protected void onPostExecute(HashMap<FormDetails, String> value) {
synchronized (this) {
if (mStateListener != null) {
mStateListener.formsDownloadingComplete(value);
}
}
}
@Override
protected void onProgressUpdate(String... values) {
synchronized (this) {
if (mStateListener != null) {
// update progress and total
mStateListener.progressUpdate(values[0],
Integer.valueOf(values[1]),
Integer.valueOf(values[2]));
}
}
}
public void setDownloaderListener(FormDownloaderListener sl) {
synchronized (this) {
mStateListener = sl;
}
}
}
| Java |
/*
* 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.tasks;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.javarosa.core.model.FormDef;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.instance.TreeElement;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.core.reference.RootTranslator;
import org.javarosa.core.services.PrototypeManager;
import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.javarosa.form.api.FormEntryController;
import org.javarosa.form.api.FormEntryModel;
import org.javarosa.model.xform.XFormsModule;
import org.javarosa.xform.parse.XFormParseException;
import org.javarosa.xform.parse.XFormParser;
import org.javarosa.xform.util.XFormUtils;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.FormLoaderListener;
import org.odk.collect.android.logic.FileReferenceFactory;
import org.odk.collect.android.logic.FormController;
import org.odk.collect.android.utilities.FileUtils;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
/**
* Background task for loading a form.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class FormLoaderTask extends AsyncTask<String, String, FormLoaderTask.FECWrapper> {
private final static String t = "FormLoaderTask";
/**
* Classes needed to serialize objects. Need to put anything from JR in here.
*/
public final static String[] SERIALIABLE_CLASSES = {
"org.javarosa.core.services.locale.ResourceFileDataSource", // JavaRosaCoreModule
"org.javarosa.core.services.locale.TableLocaleSource", // JavaRosaCoreModule
"org.javarosa.core.model.FormDef",
"org.javarosa.core.model.SubmissionProfile", // CoreModelModule
"org.javarosa.core.model.QuestionDef", // CoreModelModule
"org.javarosa.core.model.GroupDef", // CoreModelModule
"org.javarosa.core.model.instance.FormInstance", // CoreModelModule
"org.javarosa.core.model.data.BooleanData", // CoreModelModule
"org.javarosa.core.model.data.DateData", // CoreModelModule
"org.javarosa.core.model.data.DateTimeData", // CoreModelModule
"org.javarosa.core.model.data.DecimalData", // CoreModelModule
"org.javarosa.core.model.data.GeoPointData", // CoreModelModule
"org.javarosa.core.model.data.IntegerData", // CoreModelModule
"org.javarosa.core.model.data.LongData", // CoreModelModule
"org.javarosa.core.model.data.MultiPointerAnswerData", // CoreModelModule
"org.javarosa.core.model.data.PointerAnswerData", // CoreModelModule
"org.javarosa.core.model.data.SelectMultiData", // CoreModelModule
"org.javarosa.core.model.data.SelectOneData", // CoreModelModule
"org.javarosa.core.model.data.StringData", // CoreModelModule
"org.javarosa.core.model.data.TimeData", // CoreModelModule
"org.javarosa.core.model.data.UncastData", // CoreModelModule
"org.javarosa.core.model.data.helper.BasicDataPointer" // CoreModelModule
};
private FormLoaderListener mStateListener;
private String mErrorMsg;
private final String mInstancePath;
private final String mXPath;
private final String mWaitingXPath;
private boolean pendingActivityResult = false;
private int requestCode = 0;
private int resultCode = 0;
private Intent intent = null;
protected class FECWrapper {
FormController controller;
boolean usedSavepoint;
protected FECWrapper(FormController controller, boolean usedSavepoint) {
this.controller = controller;
this.usedSavepoint = usedSavepoint;
}
protected FormController getController() {
return controller;
}
protected boolean hasUsedSavepoint() {
return usedSavepoint;
}
protected void free() {
controller = null;
}
}
FECWrapper data;
public FormLoaderTask(String instancePath, String XPath, String waitingXPath) {
mInstancePath = instancePath;
mXPath = XPath;
mWaitingXPath = waitingXPath;
}
/**
* Initialize {@link FormEntryController} with {@link FormDef} from binary or from XML. If given
* an instance, it will be used to fill the {@link FormDef}.
*/
@Override
protected FECWrapper doInBackground(String... path) {
FormEntryController fec = null;
FormDef fd = null;
FileInputStream fis = null;
mErrorMsg = null;
String formPath = path[0];
File formXml = new File(formPath);
String formHash = FileUtils.getMd5Hash(formXml);
File formBin = new File(Collect.CACHE_PATH + File.separator + formHash + ".formdef");
if (formBin.exists()) {
// if we have binary, deserialize binary
Log.i(
t,
"Attempting to load " + formXml.getName() + " from cached file: "
+ formBin.getAbsolutePath());
fd = deserializeFormDef(formBin);
if (fd == null) {
// some error occured with deserialization. Remove the file, and make a new .formdef
// from xml
Log.w(t,
"Deserialization FAILED! Deleting cache file: " + formBin.getAbsolutePath());
formBin.delete();
}
}
if (fd == null) {
// no binary, read from xml
try {
Log.i(t, "Attempting to load from: " + formXml.getAbsolutePath());
fis = new FileInputStream(formXml);
fd = XFormUtils.getFormFromInputStream(fis);
if (fd == null) {
mErrorMsg = "Error reading XForm file";
} else {
serializeFormDef(fd, formPath);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
mErrorMsg = e.getMessage();
} catch (XFormParseException e) {
mErrorMsg = e.getMessage();
e.printStackTrace();
} catch (Exception e) {
mErrorMsg = e.getMessage();
e.printStackTrace();
}
}
if (mErrorMsg != null) {
return null;
}
// new evaluation context for function handlers
fd.setEvaluationContext(new EvaluationContext(null));
// create FormEntryController from formdef
FormEntryModel fem = new FormEntryModel(fd);
fec = new FormEntryController(fem);
boolean usedSavepoint = false;
try {
// import existing data into formdef
if (mInstancePath != null) {
File instance = new File(mInstancePath);
File shadowInstance = SaveToDiskTask.savepointFile(instance);
if ( shadowInstance.exists() &&
( shadowInstance.lastModified() > instance.lastModified()) ) {
// the savepoint is newer than the saved value of the instance.
// use it.
usedSavepoint = true;
instance = shadowInstance;
Log.w(t,"Loading instance from shadow file: " + shadowInstance.getAbsolutePath());
}
if ( instance.exists() ) {
// This order is important. Import data, then initialize.
importData(instance, fec);
fd.initialize(false);
} else {
fd.initialize(true);
}
} else {
fd.initialize(true);
}
} catch (RuntimeException e) {
mErrorMsg = e.getMessage();
return null;
}
// set paths to /sdcard/odk/forms/formfilename-media/
String formFileName = formXml.getName().substring(0, formXml.getName().lastIndexOf("."));
File formMediaDir = new File( formXml.getParent(), formFileName + "-media");
// Remove previous forms
ReferenceManager._().clearSession();
// This should get moved to the Application Class
if (ReferenceManager._().getFactories().length == 0) {
// this is /sdcard/odk
ReferenceManager._().addReferenceFactory(
new FileReferenceFactory(Collect.ODK_ROOT));
}
// Set jr://... to point to /sdcard/odk/forms/filename-media/
ReferenceManager._().addSessionRootTranslator(
new RootTranslator("jr://images/", "jr://file/forms/" + formFileName + "-media/"));
ReferenceManager._().addSessionRootTranslator(
new RootTranslator("jr://image/", "jr://file/forms/" + formFileName + "-media/"));
ReferenceManager._().addSessionRootTranslator(
new RootTranslator("jr://audio/", "jr://file/forms/" + formFileName + "-media/"));
ReferenceManager._().addSessionRootTranslator(
new RootTranslator("jr://video/", "jr://file/forms/" + formFileName + "-media/"));
// clean up vars
fis = null;
fd = null;
formBin = null;
formXml = null;
formPath = null;
FormController fc = new FormController(formMediaDir, fec, mInstancePath == null ? null : new File(mInstancePath));
if ( mXPath != null ) {
// we are resuming after having terminated -- set index to this position...
FormIndex idx = fc.getIndexFromXPath(mXPath);
fc.jumpToIndex(idx);
}
if ( mWaitingXPath != null ) {
FormIndex idx = fc.getIndexFromXPath(mWaitingXPath);
fc.setIndexWaitingForData(idx);
}
data = new FECWrapper(fc, usedSavepoint);
return data;
}
public boolean importData(File instanceFile, FormEntryController fec) {
// convert files into a byte array
byte[] fileBytes = FileUtils.getFileAsBytes(instanceFile);
// get the root of the saved and template instances
TreeElement savedRoot = XFormParser.restoreDataModel(fileBytes, null).getRoot();
TreeElement templateRoot = fec.getModel().getForm().getInstance().getRoot().deepCopy(true);
// weak check for matching forms
if (!savedRoot.getName().equals(templateRoot.getName()) || savedRoot.getMult() != 0) {
Log.e(t, "Saved form instance does not match template form definition");
return false;
} else {
// populate the data model
TreeReference tr = TreeReference.rootRef();
tr.add(templateRoot.getName(), TreeReference.INDEX_UNBOUND);
templateRoot.populate(savedRoot, fec.getModel().getForm());
// populated model to current form
fec.getModel().getForm().getInstance().setRoot(templateRoot);
// fix any language issues
// : http://bitbucket.org/javarosa/main/issue/5/itext-n-appearing-in-restored-instances
if (fec.getModel().getLanguages() != null) {
fec.getModel()
.getForm()
.localeChanged(fec.getModel().getLanguage(),
fec.getModel().getForm().getLocalizer());
}
return true;
}
}
/**
* Read serialized {@link FormDef} from file and recreate as object.
*
* @param formDef serialized FormDef file
* @return {@link FormDef} object
*/
public FormDef deserializeFormDef(File formDef) {
// TODO: any way to remove reliance on jrsp?
// need a list of classes that formdef uses
// unfortunately, the JR registerModule() functions do more than this.
// register just the classes that would have been registered by:
// new JavaRosaCoreModule().registerModule();
// new CoreModelModule().registerModule();
// replace with direct call to PrototypeManager
PrototypeManager.registerPrototypes(SERIALIABLE_CLASSES);
new XFormsModule().registerModule();
FileInputStream fis = null;
FormDef fd = null;
try {
// create new form def
fd = new FormDef();
fis = new FileInputStream(formDef);
DataInputStream dis = new DataInputStream(fis);
// read serialized formdef into new formdef
fd.readExternal(dis, ExtUtil.defaultPrototypes());
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
fd = null;
} catch (IOException e) {
e.printStackTrace();
fd = null;
} catch (DeserializationException e) {
e.printStackTrace();
fd = null;
} catch (Exception e) {
e.printStackTrace();
fd = null;
}
return fd;
}
/**
* Write the FormDef to the file system as a binary blog.
*
* @param filepath path to the form file
*/
public void serializeFormDef(FormDef fd, String filepath) {
// calculate unique md5 identifier
String hash = FileUtils.getMd5Hash(new File(filepath));
File formDef = new File(Collect.CACHE_PATH + File.separator + hash + ".formdef");
// formdef does not exist, create one.
if (!formDef.exists()) {
FileOutputStream fos;
try {
fos = new FileOutputStream(formDef);
DataOutputStream dos = new DataOutputStream(fos);
fd.writeExternal(dos);
dos.flush();
dos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
protected void onPostExecute(FECWrapper wrapper) {
synchronized (this) {
if (mStateListener != null) {
if (wrapper == null) {
mStateListener.loadingError(mErrorMsg);
} else {
mStateListener.loadingComplete(this);
}
}
}
}
public void setFormLoaderListener(FormLoaderListener sl) {
synchronized (this) {
mStateListener = sl;
}
}
public FormController getFormController() {
return ( data != null ) ? data.getController() : null;
}
public boolean hasUsedSavepoint() {
return (data != null ) ? data.hasUsedSavepoint() : false;
}
public void destroy() {
if (data != null) {
data.free();
data = null;
}
}
public boolean hasPendingActivityResult() {
return pendingActivityResult;
}
public int getRequestCode() {
return requestCode;
}
public int getResultCode() {
return resultCode;
}
public Intent getIntent() {
return intent;
}
public void setActivityResult(int requestCode, int resultCode, Intent intent) {
this.pendingActivityResult = true;
this.requestCode = requestCode;
this.resultCode = resultCode;
this.intent = intent;
}
}
| Java |
/*
* 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.tasks;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.DeleteInstancesListener;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import android.content.ContentResolver;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
/**
* Task responsible for deleting selected instances.
* @author norman86@gmail.com
* @author mitchellsundt@gmail.com
*
*/
public class DeleteInstancesTask extends AsyncTask<Long, Void, Integer> {
private static final String t = "DeleteInstancesTask";
private ContentResolver cr;
private DeleteInstancesListener dl;
private int successCount = 0;
@Override
protected Integer doInBackground(Long... params) {
int deleted = 0;
if (params == null ||cr == null || dl == null) {
return deleted;
}
// delete files from database and then from file system
for (int i = 0; i < params.length; i++) {
if ( isCancelled() ) {
break;
}
try {
Uri deleteForm =
Uri.withAppendedPath(InstanceColumns.CONTENT_URI, params[i].toString());
int wasDeleted = cr.delete(deleteForm, null, null);
deleted += wasDeleted;
if (wasDeleted > 0) {
Collect.getInstance().getActivityLogger().logAction(this, "delete", deleteForm.toString());
}
} catch ( Exception ex ) {
Log.e(t,"Exception during delete of: " + params[i].toString() + " exception: " + ex.toString());
}
}
successCount = deleted;
return deleted;
}
@Override
protected void onPostExecute(Integer result) {
cr = null;
if (dl != null) {
dl.deleteComplete(result);
}
super.onPostExecute(result);
}
@Override
protected void onCancelled() {
cr = null;
if (dl != null) {
dl.deleteComplete(successCount);
}
}
public void setDeleteListener(DeleteInstancesListener listener) {
dl = listener;
}
public void setContentResolver(ContentResolver resolver){
cr = resolver;
}
public int getDeleteCount() {
return successCount;
}
}
| Java |
/*
* 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.tasks;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
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.utilities.FileUtils;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
/**
* Background task for adding to the forms content provider, any forms that have been added to the
* sdcard manually. Returns immediately if it detects an error.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class DiskSyncTask extends AsyncTask<Void, String, String> {
private final static String t = "DiskSyncTask";
private static int counter = 0;
int instance;
DiskSyncListener mListener;
String statusMessage;
private static class UriFile {
public final Uri uri;
public final File file;
UriFile(Uri uri, File file) {
this.uri = uri;
this.file = file;
}
}
@Override
protected String doInBackground(Void... params) {
instance = ++counter; // roughly track the scan # we're on... logging use only
Log.i(t, "["+instance+"] doInBackground begins!");
try {
// Process everything then report what didn't work.
StringBuffer errors = new StringBuffer();
File formDir = new File(Collect.FORMS_PATH);
if (formDir.exists() && formDir.isDirectory()) {
// Get all the files in the /odk/foms directory
List<File> xFormsToAdd = new LinkedList<File>();
// Step 1: assemble the candidate form files
// discard files beginning with "."
// discard files not ending with ".xml" or ".xhtml"
{
File[] formDefs = formDir.listFiles();
for ( File addMe: formDefs ) {
// Ignore invisible files that start with periods.
if (!addMe.getName().startsWith(".")
&& (addMe.getName().endsWith(".xml") || addMe.getName().endsWith(".xhtml"))) {
xFormsToAdd.add(addMe);
} else {
Log.i(t, "["+instance+"] Ignoring: " + addMe.getAbsolutePath());
}
}
}
// Step 2: quickly run through and figure out what files we need to
// parse and update; this is quick, as we only calculate the md5
// and see if it has changed.
List<UriFile> uriToUpdate = new ArrayList<UriFile>();
Cursor mCursor = null;
// open the cursor within a try-catch block so it can always be closed.
try {
mCursor = Collect.getInstance().getContentResolver()
.query(FormsColumns.CONTENT_URI, null, null, null, null);
if (mCursor == null) {
Log.e(t, "["+instance+"] Forms Content Provider returned NULL");
errors.append("Internal Error: Unable to access Forms content provider").append("\r\n");
return errors.toString();
}
mCursor.moveToPosition(-1);
while (mCursor.moveToNext()) {
// For each element in the provider, see if the file already exists
String sqlFilename =
mCursor.getString(mCursor.getColumnIndex(FormsColumns.FORM_FILE_PATH));
String md5 = mCursor.getString(mCursor.getColumnIndex(FormsColumns.MD5_HASH));
File sqlFile = new File(sqlFilename);
if (sqlFile.exists()) {
// remove it from the list of forms (we only want forms
// we haven't added at the end)
xFormsToAdd.remove(sqlFile);
if (!FileUtils.getMd5Hash(sqlFile).contentEquals(md5)) {
// Probably someone overwrite the file on the sdcard
// So re-parse it and update it's information
String id = mCursor.getString(mCursor.getColumnIndex(FormsColumns._ID));
Uri updateUri = Uri.withAppendedPath(FormsColumns.CONTENT_URI, id);
uriToUpdate.add(new UriFile(updateUri, sqlFile));
}
} else {
Log.w(t, "["+instance+"] file referenced by content provider does not exist " + sqlFile);
}
}
} finally {
if ( mCursor != null ) {
mCursor.close();
}
}
// Step3: go through uriToUpdate to parse and update each in turn.
// This is slow because buildContentValues(...) is slow.
Collections.shuffle(uriToUpdate); // Big win if multiple DiskSyncTasks running
for ( UriFile entry : uriToUpdate ) {
Uri updateUri = entry.uri;
File formDefFile = entry.file;
// Probably someone overwrite the file on the sdcard
// So re-parse it and update it's information
ContentValues values;
try {
values = buildContentValues(formDefFile);
} catch ( IllegalArgumentException e) {
errors.append(e.getMessage()).append("\r\n");
File badFile = new File(formDefFile.getParentFile(), formDefFile.getName() + ".bad");
badFile.delete();
formDefFile.renameTo(badFile);
continue;
}
// update in content provider
int count =
Collect.getInstance().getContentResolver()
.update(updateUri, values, null, null);
Log.i(t, "["+instance+"] " + count + " records successfully updated");
}
uriToUpdate.clear();
// Step 4: go through the newly-discovered files in xFormsToAdd and add them.
// This is slow because buildContentValues(...) is slow.
//
Collections.shuffle(xFormsToAdd); // Big win if multiple DiskSyncTasks running
while ( !xFormsToAdd.isEmpty() ) {
File formDefFile = xFormsToAdd.remove(0);
// Since parsing is so slow, if there are multiple tasks,
// they may have already updated the database.
// Skip this file if that is the case.
if ( isAlreadyDefined(formDefFile) ) {
Log.i(t, "["+instance+"] skipping -- definition already recorded: " + formDefFile.getAbsolutePath());
continue;
}
// Parse it for the first time...
ContentValues values;
try {
values = buildContentValues(formDefFile);
} catch ( IllegalArgumentException e) {
errors.append(e.getMessage()).append("\r\n");
File badFile = new File(formDefFile.getParentFile(), formDefFile.getName() + ".bad");
badFile.delete();
formDefFile.renameTo(badFile);
continue;
}
// insert into content provider
try {
// insert failures are OK and expected if multiple
// DiskSync scanners are active.
Collect.getInstance().getContentResolver()
.insert(FormsColumns.CONTENT_URI, values);
} catch ( SQLException e ) {
Log.i(t, "["+instance+"] " + e.toString());
}
}
}
if ( errors.length() != 0 ) {
statusMessage = errors.toString();
} else {
statusMessage = Collect.getInstance().getString(R.string.finished_disk_scan);
}
return statusMessage;
} finally {
Log.i(t, "["+instance+"] doInBackground ends!");
}
}
private boolean isAlreadyDefined(File formDefFile) {
// first try to see if a record with this filename already exists...
String[] projection = {
FormsColumns._ID, FormsColumns.FORM_FILE_PATH
};
String[] selectionArgs = { formDefFile.getAbsolutePath() };
String selection = FormsColumns.FORM_FILE_PATH + "=?";
Cursor c = null;
try {
c = Collect.getInstance().getContentResolver()
.query(FormsColumns.CONTENT_URI, projection, selection, selectionArgs, null);
return ( c.getCount() > 0 );
} finally {
if ( c != null ) {
c.close();
}
}
}
public String getStatusMessage() {
return statusMessage;
}
/**
* Attempts to parse the formDefFile as an XForm.
* This is slow because FileUtils.parseXML is slow
*
* @param formDefFile
* @return key-value list to update or insert into the content provider
* @throws IllegalArgumentException if the file failed to parse or was missing fields
*/
public ContentValues buildContentValues(File formDefFile) throws IllegalArgumentException {
// Probably someone overwrite the file on the sdcard
// So re-parse it and update it's information
ContentValues updateValues = new ContentValues();
HashMap<String, String> fields = null;
try {
fields = FileUtils.parseXML(formDefFile);
} catch (RuntimeException e) {
throw new IllegalArgumentException(formDefFile.getName() + " :: " + e.toString());
}
String title = fields.get(FileUtils.TITLE);
String version = fields.get(FileUtils.VERSION);
String formid = fields.get(FileUtils.FORMID);
String submission = fields.get(FileUtils.SUBMISSIONURI);
String base64RsaPublicKey = fields.get(FileUtils.BASE64_RSA_PUBLIC_KEY);
// update date
Long now = Long.valueOf(System.currentTimeMillis());
updateValues.put(FormsColumns.DATE, now);
if (title != null) {
updateValues.put(FormsColumns.DISPLAY_NAME, title);
} else {
throw new IllegalArgumentException(Collect.getInstance().getString(R.string.xform_parse_error,
formDefFile.getName(), "title"));
}
if (formid != null) {
updateValues.put(FormsColumns.JR_FORM_ID, formid);
} else {
throw new IllegalArgumentException(Collect.getInstance().getString(R.string.xform_parse_error,
formDefFile.getName(), "id"));
}
if (version != null) {
updateValues.put(FormsColumns.JR_VERSION, version);
}
if (submission != null) {
updateValues.put(FormsColumns.SUBMISSION_URI, submission);
}
if (base64RsaPublicKey != null) {
updateValues.put(FormsColumns.BASE64_RSA_PUBLIC_KEY, base64RsaPublicKey);
}
// Note, the path doesn't change here, but it needs to be included so the
// update will automatically update the .md5 and the cache path.
updateValues.put(FormsColumns.FORM_FILE_PATH, formDefFile.getAbsolutePath());
return updateValues;
}
public void setDiskSyncListener(DiskSyncListener l) {
mListener = l;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (mListener != null) {
mListener.SyncComplete(result);
}
}
}
| Java |
/*
* 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.tasks;
import org.opendatakit.httpclientandroidlib.client.HttpClient;
import org.opendatakit.httpclientandroidlib.protocol.HttpContext;
import org.javarosa.xform.parse.XFormParser;
import org.kxml2.kdom.Element;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
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.utilities.DocumentFetchResult;
import org.odk.collect.android.utilities.WebUtils;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import java.util.HashMap;
/**
* Background task for downloading forms from urls or a formlist from a url. We overload this task a
* bit so that we don't have to keep track of two separate downloading tasks and it simplifies
* interfaces. If LIST_URL is passed to doInBackground(), we fetch a form list. If a hashmap
* containing form/url pairs is passed, we download those forms.
*
* @author carlhartung
*/
public class DownloadFormListTask extends AsyncTask<Void, String, HashMap<String, FormDetails>> {
private static final String t = "DownloadFormsTask";
// used to store error message if one occurs
public static final String DL_ERROR_MSG = "dlerrormessage";
public static final String DL_AUTH_REQUIRED = "dlauthrequired";
private FormListDownloaderListener mStateListener;
private static final String NAMESPACE_OPENROSA_ORG_XFORMS_XFORMS_LIST =
"http://openrosa.org/xforms/xformsList";
private boolean isXformsListNamespacedElement(Element e) {
return e.getNamespace().equalsIgnoreCase(NAMESPACE_OPENROSA_ORG_XFORMS_XFORMS_LIST);
}
@Override
protected HashMap<String, FormDetails> doInBackground(Void... values) {
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(Collect.getInstance().getBaseContext());
String downloadListUrl =
settings.getString(PreferencesActivity.KEY_SERVER_URL,
Collect.getInstance().getString(R.string.default_server_url));
// NOTE: /formlist must not be translated! It is the well-known path on the server.
String formListUrl = Collect.getInstance().getApplicationContext().getString(R.string.default_odk_formlist);
String downloadPath = settings.getString(PreferencesActivity.KEY_FORMLIST_URL, formListUrl);
downloadListUrl += downloadPath;
Collect.getInstance().getActivityLogger().logAction(this, formListUrl, downloadListUrl);
// We populate this with available forms from the specified server.
// <formname, details>
HashMap<String, FormDetails> formList = new HashMap<String, FormDetails>();
// get shared HttpContext so that authentication and cookies are retained.
HttpContext localContext = Collect.getInstance().getHttpContext();
HttpClient httpclient = WebUtils.createHttpClient(WebUtils.CONNECTION_TIMEOUT);
DocumentFetchResult result =
WebUtils.getXmlDocument(downloadListUrl, localContext, httpclient);
// If we can't get the document, return the error, cancel the task
if (result.errorMessage != null) {
if (result.responseCode == 401) {
formList.put(DL_AUTH_REQUIRED, new FormDetails(result.errorMessage));
} else {
formList.put(DL_ERROR_MSG, new FormDetails(result.errorMessage));
}
return formList;
}
if (result.isOpenRosaResponse) {
// Attempt OpenRosa 1.0 parsing
Element xformsElement = result.doc.getRootElement();
if (!xformsElement.getName().equals("xforms")) {
String error = "root element is not <xforms> : " + xformsElement.getName();
Log.e(t, "Parsing OpenRosa reply -- " + error);
formList.put(
DL_ERROR_MSG,
new FormDetails(Collect.getInstance().getString(
R.string.parse_openrosa_formlist_failed, error)));
return formList;
}
String namespace = xformsElement.getNamespace();
if (!isXformsListNamespacedElement(xformsElement)) {
String error = "root element namespace is incorrect:" + namespace;
Log.e(t, "Parsing OpenRosa reply -- " + error);
formList.put(
DL_ERROR_MSG,
new FormDetails(Collect.getInstance().getString(
R.string.parse_openrosa_formlist_failed, error)));
return formList;
}
int nElements = xformsElement.getChildCount();
for (int i = 0; i < nElements; ++i) {
if (xformsElement.getType(i) != Element.ELEMENT) {
// e.g., whitespace (text)
continue;
}
Element xformElement = (Element) xformsElement.getElement(i);
if (!isXformsListNamespacedElement(xformElement)) {
// someone else's extension?
continue;
}
String name = xformElement.getName();
if (!name.equalsIgnoreCase("xform")) {
// someone else's extension?
continue;
}
// this is something we know how to interpret
String formId = null;
String formName = null;
String version = null;
String majorMinorVersion = null;
String description = null;
String downloadUrl = null;
String manifestUrl = null;
// don't process descriptionUrl
int fieldCount = xformElement.getChildCount();
for (int j = 0; j < fieldCount; ++j) {
if (xformElement.getType(j) != Element.ELEMENT) {
// whitespace
continue;
}
Element child = xformElement.getElement(j);
if (!isXformsListNamespacedElement(child)) {
// someone else's extension?
continue;
}
String tag = child.getName();
if (tag.equals("formID")) {
formId = XFormParser.getXMLText(child, true);
if (formId != null && formId.length() == 0) {
formId = null;
}
} else if (tag.equals("name")) {
formName = XFormParser.getXMLText(child, true);
if (formName != null && formName.length() == 0) {
formName = null;
}
} else if (tag.equals("version")) {
version = XFormParser.getXMLText(child, true);
if (version != null && version.length() == 0) {
version = null;
}
} else if (tag.equals("majorMinorVersion")) {
majorMinorVersion = XFormParser.getXMLText(child, true);
if (majorMinorVersion != null && majorMinorVersion.length() == 0) {
majorMinorVersion = null;
}
} else if (tag.equals("descriptionText")) {
description = XFormParser.getXMLText(child, true);
if (description != null && description.length() == 0) {
description = null;
}
} else if (tag.equals("downloadUrl")) {
downloadUrl = XFormParser.getXMLText(child, true);
if (downloadUrl != null && downloadUrl.length() == 0) {
downloadUrl = null;
}
} else if (tag.equals("manifestUrl")) {
manifestUrl = XFormParser.getXMLText(child, true);
if (manifestUrl != null && manifestUrl.length() == 0) {
manifestUrl = null;
}
}
}
if (formId == null || downloadUrl == null || formName == null) {
String error =
"Forms list entry " + Integer.toString(i)
+ " is missing one or more tags: formId, name, or downloadUrl";
Log.e(t, "Parsing OpenRosa reply -- " + error);
formList.clear();
formList.put(
DL_ERROR_MSG,
new FormDetails(Collect.getInstance().getString(
R.string.parse_openrosa_formlist_failed, error)));
return formList;
}
formList.put(formId, new FormDetails(formName, downloadUrl, manifestUrl, formId, (version != null) ? version : majorMinorVersion));
}
} else {
// Aggregate 0.9.x mode...
// populate HashMap with form names and urls
Element formsElement = result.doc.getRootElement();
int formsCount = formsElement.getChildCount();
String formId = null;
for (int i = 0; i < formsCount; ++i) {
if (formsElement.getType(i) != Element.ELEMENT) {
// whitespace
continue;
}
Element child = formsElement.getElement(i);
String tag = child.getName();
if (tag.equals("formID")) {
formId = XFormParser.getXMLText(child, true);
if (formId != null && formId.length() == 0) {
formId = null;
}
}
if (tag.equalsIgnoreCase("form")) {
String formName = XFormParser.getXMLText(child, true);
if (formName != null && formName.length() == 0) {
formName = null;
}
String downloadUrl = child.getAttributeValue(null, "url");
downloadUrl = downloadUrl.trim();
if (downloadUrl != null && downloadUrl.length() == 0) {
downloadUrl = null;
}
if (downloadUrl == null || formName == null) {
String error =
"Forms list entry " + Integer.toString(i)
+ " is missing form name or url attribute";
Log.e(t, "Parsing OpenRosa reply -- " + error);
formList.clear();
formList.put(
DL_ERROR_MSG,
new FormDetails(Collect.getInstance().getString(
R.string.parse_legacy_formlist_failed, error)));
return formList;
}
formList.put(formName, new FormDetails(formName, downloadUrl, null, formId, null));
formId = null;
}
}
}
return formList;
}
@Override
protected void onPostExecute(HashMap<String, FormDetails> value) {
synchronized (this) {
if (mStateListener != null) {
mStateListener.formListDownloadingComplete(value);
}
}
}
public void setDownloaderListener(FormListDownloaderListener sl) {
synchronized (this) {
mStateListener = sl;
}
}
}
| Java |
/*
* 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.tasks;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import org.javarosa.core.model.FormDef;
import org.javarosa.core.services.transport.payload.ByteArrayPayload;
import org.javarosa.form.api.FormEntryController;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.FormSavedListener;
import org.odk.collect.android.logic.FormController;
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.utilities.EncryptionUtils;
import org.odk.collect.android.utilities.EncryptionUtils.EncryptedFormInformation;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
/**
* Background task for loading a form.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class SaveToDiskTask extends AsyncTask<Void, String, Integer> {
private final static String t = "SaveToDiskTask";
private FormSavedListener mSavedListener;
private Boolean mSave;
private Boolean mMarkCompleted;
private Uri mUri;
private String mInstanceName;
public static final int SAVED = 500;
public static final int SAVE_ERROR = 501;
public static final int VALIDATE_ERROR = 502;
public static final int VALIDATED = 503;
public static final int SAVED_AND_EXIT = 504;
public SaveToDiskTask(Uri uri, Boolean saveAndExit, Boolean markCompleted, String updatedName) {
mUri = uri;
mSave = saveAndExit;
mMarkCompleted = markCompleted;
mInstanceName = updatedName;
}
/**
* Initialize {@link FormEntryController} with {@link FormDef} from binary or from XML. If given
* an instance, it will be used to fill the {@link FormDef}.
*/
@Override
protected Integer doInBackground(Void... nothing) {
FormController formController = Collect.getInstance().getFormController();
// validation failed, pass specific failure
int validateStatus = formController.validateAnswers(mMarkCompleted);
if (validateStatus != FormEntryController.ANSWER_OK) {
return validateStatus;
}
if (mMarkCompleted) {
formController.postProcessInstance();
}
Collect.getInstance().getActivityLogger().logInstanceAction(this, "save", Boolean.toString(mMarkCompleted));
// if there is a meta/instanceName field, be sure we are using the latest value
// just in case the validate somehow triggered an update.
String updatedSaveName = formController.getSubmissionMetadata().instanceName;
if ( updatedSaveName != null ) {
mInstanceName = updatedSaveName;
}
boolean saveOutcome = exportData(mMarkCompleted);
// attempt to remove any scratch file
File shadowInstance = savepointFile(formController.getInstancePath());
if ( shadowInstance.exists() ) {
shadowInstance.delete();
}
if (saveOutcome) {
return mSave ? SAVED_AND_EXIT : SAVED;
}
return SAVE_ERROR;
}
private void updateInstanceDatabase(boolean incomplete, boolean canEditAfterCompleted) {
FormController formController = Collect.getInstance().getFormController();
// Update the instance database...
ContentValues values = new ContentValues();
if (mInstanceName != null) {
values.put(InstanceColumns.DISPLAY_NAME, mInstanceName);
}
if (incomplete || !mMarkCompleted) {
values.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_INCOMPLETE);
} else {
values.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_COMPLETE);
}
// update this whether or not the status is complete...
values.put(InstanceColumns.CAN_EDIT_WHEN_COMPLETE, Boolean.toString(canEditAfterCompleted));
// If FormEntryActivity was started with an Instance, just update that instance
if (Collect.getInstance().getContentResolver().getType(mUri) == InstanceColumns.CONTENT_ITEM_TYPE) {
int updated = Collect.getInstance().getContentResolver().update(mUri, values, null, null);
if (updated > 1) {
Log.w(t, "Updated more than one entry, that's not good: " + mUri.toString());
} else if (updated == 1) {
Log.i(t, "Instance successfully updated");
} else {
Log.e(t, "Instance doesn't exist but we have its Uri!! " + mUri.toString());
}
} else if (Collect.getInstance().getContentResolver().getType(mUri) == FormsColumns.CONTENT_ITEM_TYPE) {
// If FormEntryActivity was started with a form, then it's likely the first time we're
// saving.
// However, it could be a not-first time saving if the user has been using the manual
// 'save data' option from the menu. So try to update first, then make a new one if that
// fails.
String instancePath = formController.getInstancePath().getAbsolutePath();
String where = InstanceColumns.INSTANCE_FILE_PATH + "=?";
String[] whereArgs = {
instancePath
};
int updated =
Collect.getInstance().getContentResolver()
.update(InstanceColumns.CONTENT_URI, values, where, whereArgs);
if (updated > 1) {
Log.w(t, "Updated more than one entry, that's not good: " + instancePath);
} else if (updated == 1) {
Log.i(t, "Instance found and successfully updated: " + instancePath);
// already existed and updated just fine
} else {
Log.i(t, "No instance found, creating");
// Entry didn't exist, so create it.
Cursor c = null;
try {
// retrieve the form definition...
c = Collect.getInstance().getContentResolver().query(mUri, null, null, null, null);
c.moveToFirst();
String jrformid = c.getString(c.getColumnIndex(FormsColumns.JR_FORM_ID));
String jrversion = c.getString(c.getColumnIndex(FormsColumns.JR_VERSION));
String formname = c.getString(c.getColumnIndex(FormsColumns.DISPLAY_NAME));
String submissionUri = null;
if ( !c.isNull(c.getColumnIndex(FormsColumns.SUBMISSION_URI)) ) {
submissionUri = c.getString(c.getColumnIndex(FormsColumns.SUBMISSION_URI));
}
// add missing fields into values
values.put(InstanceColumns.INSTANCE_FILE_PATH, instancePath);
values.put(InstanceColumns.SUBMISSION_URI, submissionUri);
if (mInstanceName != null) {
values.put(InstanceColumns.DISPLAY_NAME, mInstanceName);
} else {
values.put(InstanceColumns.DISPLAY_NAME, formname);
}
values.put(InstanceColumns.JR_FORM_ID, jrformid);
values.put(InstanceColumns.JR_VERSION, jrversion);
} finally {
if ( c != null ) {
c.close();
}
}
mUri = Collect.getInstance().getContentResolver()
.insert(InstanceColumns.CONTENT_URI, values);
}
}
}
/**
* Return the name of the savepoint file for a given instance.
*
* @param instancePath
* @return
*/
public static File savepointFile(File instancePath) {
File tempDir = new File(Collect.CACHE_PATH);
File temp = new File(tempDir, instancePath.getName() + ".save");
return temp;
}
/**
* Blocking write of the instance data to a temp file. Used to safeguard data
* during intent launches for, e.g., taking photos.
*
* @param tempPath
* @return
*/
public static String blockingExportTempData() {
FormController formController = Collect.getInstance().getFormController();
long start = System.currentTimeMillis();
File temp = savepointFile(formController.getInstancePath());
ByteArrayPayload payload;
try {
payload = formController.getFilledInFormXml();
// write out xml
if ( exportXmlFile(payload, temp.getAbsolutePath()) ) {
return temp.getAbsolutePath();
}
return null;
} catch (IOException e) {
Log.e(t, "Error creating serialized payload");
e.printStackTrace();
return null;
} finally {
long end = System.currentTimeMillis();
Log.i(t, "Savepoint ms: " + Long.toString(end - start));
}
}
/**
* Write's the data to the sdcard, and updates the instances content provider.
* In theory we don't have to write to disk, and this is where you'd add
* other methods.
* @param markCompleted
* @return
*/
private boolean exportData(boolean markCompleted) {
FormController formController = Collect.getInstance().getFormController();
ByteArrayPayload payload;
try {
payload = formController.getFilledInFormXml();
// write out xml
String instancePath = formController.getInstancePath().getAbsolutePath();
exportXmlFile(payload, instancePath);
} catch (IOException e) {
Log.e(t, "Error creating serialized payload");
e.printStackTrace();
return false;
}
// update the mUri. We have exported the reloadable instance, so update status...
// Since we saved a reloadable instance, it is flagged as re-openable so that if any error
// occurs during the packaging of the data for the server fails (e.g., encryption),
// we can still reopen the filled-out form and re-save it at a later time.
updateInstanceDatabase(true, true);
if ( markCompleted ) {
// now see if the packaging of the data for the server would make it
// non-reopenable (e.g., encryption or send an SMS or other fraction of the form).
boolean canEditAfterCompleted = formController.isSubmissionEntireForm();
boolean isEncrypted = false;
// build a submission.xml to hold the data being submitted
// and (if appropriate) encrypt the files on the side
// pay attention to the ref attribute of the submission profile...
try {
payload = formController.getSubmissionXml();
} catch (IOException e) {
Log.e(t, "Error creating serialized payload");
e.printStackTrace();
return false;
}
File instanceXml = formController.getInstancePath();
File submissionXml = new File(instanceXml.getParentFile(), "submission.xml");
// write out submission.xml -- the data to actually submit to aggregate
exportXmlFile(payload, submissionXml.getAbsolutePath());
// see if the form is encrypted and we can encrypt it...
EncryptedFormInformation formInfo = EncryptionUtils.getEncryptedFormInformation(mUri,
formController.getSubmissionMetadata());
if ( formInfo != null ) {
// if we are encrypting, the form cannot be reopened afterward
canEditAfterCompleted = false;
// and encrypt the submission (this is a one-way operation)...
if ( !EncryptionUtils.generateEncryptedSubmission(instanceXml, submissionXml, formInfo) ) {
return false;
}
isEncrypted = true;
}
// At this point, we have:
// 1. the saved original instanceXml,
// 2. all the plaintext attachments
// 2. the submission.xml that is the completed xml (whether encrypting or not)
// 3. all the encrypted attachments if encrypting (isEncrypted = true).
//
// NEXT:
// 1. Update the instance database (with status complete).
// 2. Overwrite the instanceXml with the submission.xml
// and remove the plaintext attachments if encrypting
updateInstanceDatabase(false, canEditAfterCompleted);
if ( !canEditAfterCompleted ) {
// AT THIS POINT, there is no going back. We are committed
// to returning "success" (true) whether or not we can
// rename "submission.xml" to instanceXml and whether or
// not we can delete the plaintext media files.
//
// Handle the fall-out for a failed "submission.xml" rename
// in the InstanceUploader task. Leftover plaintext media
// files are handled during form deletion.
// delete the restore Xml file.
if ( !instanceXml.delete() ) {
Log.e(t, "Error deleting " + instanceXml.getAbsolutePath()
+ " prior to renaming submission.xml");
return true;
}
// rename the submission.xml to be the instanceXml
if ( !submissionXml.renameTo(instanceXml) ) {
Log.e(t, "Error renaming submission.xml to " + instanceXml.getAbsolutePath());
return true;
}
} else {
// try to delete the submissionXml file, since it is
// identical to the existing instanceXml file
// (we don't need to delete and rename anything).
if ( !submissionXml.delete() ) {
Log.w(t, "Error deleting " + submissionXml.getAbsolutePath()
+ " (instance is re-openable)");
}
}
// if encrypted, delete all plaintext files
// (anything not named instanceXml or anything not ending in .enc)
if ( isEncrypted ) {
if ( !EncryptionUtils.deletePlaintextFiles(instanceXml) ) {
Log.e(t, "Error deleting plaintext files for " + instanceXml.getAbsolutePath());
}
}
}
return true;
}
/**
* This method actually writes the xml to disk.
* @param payload
* @param path
* @return
*/
private static boolean exportXmlFile(ByteArrayPayload payload, String path) {
// create data stream
InputStream is = payload.getPayloadStream();
int len = (int) payload.getLength();
// read from data stream
byte[] data = new byte[len];
try {
int read = is.read(data, 0, len);
if (read > 0) {
// write xml file
try {
// String filename = path + File.separator +
// path.substring(path.lastIndexOf(File.separator) + 1) + ".xml";
FileWriter fw = new FileWriter(path);
fw.write(new String(data, "UTF-8"));
fw.flush();
fw.close();
return true;
} catch (IOException e) {
Log.e(t, "Error writing XML file");
e.printStackTrace();
return false;
}
}
} catch (IOException e) {
Log.e(t, "Error reading from payload data stream");
e.printStackTrace();
return false;
}
return false;
}
@Override
protected void onPostExecute(Integer result) {
synchronized (this) {
if (mSavedListener != null)
mSavedListener.savingComplete(result);
}
}
public void setFormSavedListener(FormSavedListener fsl) {
synchronized (this) {
mSavedListener = fsl;
}
}
}
| Java |
/*
* 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.tasks;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.DeleteFormsListener;
import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns;
import android.content.ContentResolver;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
/**
* Task responsible for deleting selected forms.
* @author norman86@gmail.com
* @author mitchellsundt@gmail.com
*
*/
public class DeleteFormsTask extends AsyncTask<Long, Void, Integer> {
private static final String t = "DeleteFormsTask";
private ContentResolver cr;
private DeleteFormsListener dl;
private int successCount = 0;
@Override
protected Integer doInBackground(Long... params) {
int deleted = 0;
if (params == null ||cr == null || dl == null) {
return deleted;
}
// delete files from database and then from file system
for (int i = 0; i < params.length; i++) {
if ( isCancelled() ) {
break;
}
try {
Uri deleteForm =
Uri.withAppendedPath(FormsColumns.CONTENT_URI, params[i].toString());
int wasDeleted = cr.delete(deleteForm, null, null);
deleted += wasDeleted;
if (wasDeleted > 0) {
Collect.getInstance().getActivityLogger().logAction(this, "delete", deleteForm.toString());
}
} catch ( Exception ex ) {
Log.e(t,"Exception during delete of: " + params[i].toString() + " exception: " + ex.toString());
}
}
successCount = deleted;
return deleted;
}
@Override
protected void onPostExecute(Integer result) {
cr = null;
if (dl != null) {
dl.deleteComplete(result);
}
super.onPostExecute(result);
}
@Override
protected void onCancelled() {
cr = null;
if (dl != null) {
dl.deleteComplete(successCount);
}
}
public void setDeleteListener(DeleteFormsListener listener) {
dl = listener;
}
public void setContentResolver(ContentResolver resolver){
cr = resolver;
}
public int getDeleteCount() {
return successCount;
}
}
| Java |
/*
* 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.tasks;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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.logic.PropertyManager;
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.WebUtils;
import org.opendatakit.httpclientandroidlib.Header;
import org.opendatakit.httpclientandroidlib.HttpResponse;
import org.opendatakit.httpclientandroidlib.HttpStatus;
import org.opendatakit.httpclientandroidlib.client.ClientProtocolException;
import org.opendatakit.httpclientandroidlib.client.HttpClient;
import org.opendatakit.httpclientandroidlib.client.methods.HttpHead;
import org.opendatakit.httpclientandroidlib.client.methods.HttpPost;
import org.opendatakit.httpclientandroidlib.conn.ConnectTimeoutException;
import org.opendatakit.httpclientandroidlib.conn.HttpHostConnectException;
import org.opendatakit.httpclientandroidlib.entity.mime.MultipartEntity;
import org.opendatakit.httpclientandroidlib.entity.mime.content.FileBody;
import org.opendatakit.httpclientandroidlib.entity.mime.content.StringBody;
import org.opendatakit.httpclientandroidlib.protocol.HttpContext;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import android.webkit.MimeTypeMap;
/**
* Background task for uploading completed forms.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class InstanceUploaderTask extends AsyncTask<Long, Integer, InstanceUploaderTask.Outcome> {
private static final String t = "InstanceUploaderTask";
// it can take up to 27 seconds to spin up Aggregate
private static final int CONNECTION_TIMEOUT = 60000;
private static final String fail = "Error: ";
private InstanceUploaderListener mStateListener;
public static class Outcome {
public Uri mAuthRequestingServer = null;
public HashMap<String, String> mResults = new HashMap<String,String>();
}
/**
* Uploads to urlString the submission identified by id with filepath of instance
* @param urlString destination URL
* @param id
* @param instanceFilePath
* @param toUpdate - Instance URL for recording status update.
* @param httpclient - client connection
* @param localContext - context (e.g., credentials, cookies) for client connection
* @param uriRemap - mapping of Uris to avoid redirects on subsequent invocations
* @return false if credentials are required and we should terminate immediately.
*/
private boolean uploadOneSubmission(String urlString, String id, String instanceFilePath,
Uri toUpdate, HttpContext localContext, Map<Uri, Uri> uriRemap, Outcome outcome) {
Collect.getInstance().getActivityLogger().logAction(this, urlString, instanceFilePath);
ContentValues cv = new ContentValues();
Uri u = Uri.parse(urlString);
HttpClient httpclient = WebUtils.createHttpClient(CONNECTION_TIMEOUT);
boolean openRosaServer = false;
if (uriRemap.containsKey(u)) {
// we already issued a head request and got a response,
// so we know the proper URL to send the submission to
// and the proper scheme. We also know that it was an
// OpenRosa compliant server.
openRosaServer = true;
u = uriRemap.get(u);
// if https then enable preemptive basic auth...
if ( u.getScheme().equals("https") ) {
WebUtils.enablePreemptiveBasicAuth(localContext, u.getHost());
}
Log.i(t, "Using Uri remap for submission " + id + ". Now: " + u.toString());
} else {
// if https then enable preemptive basic auth...
if ( u.getScheme().equals("https") ) {
WebUtils.enablePreemptiveBasicAuth(localContext, u.getHost());
}
// we need to issue a head request
HttpHead httpHead = WebUtils.createOpenRosaHttpHead(u);
// prepare response
HttpResponse response = null;
try {
Log.i(t, "Issuing HEAD request for " + id + " to: " + u.toString());
response = httpclient.execute(httpHead, localContext);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
// clear the cookies -- should not be necessary?
Collect.getInstance().getCookieStore().clear();
WebUtils.discardEntityBytes(response);
// we need authentication, so stop and return what we've
// done so far.
outcome.mAuthRequestingServer = u;
return false;
} else if (statusCode == 204) {
Header[] locations = response.getHeaders("Location");
WebUtils.discardEntityBytes(response);
if (locations != null && locations.length == 1) {
try {
Uri uNew = Uri.parse(URLDecoder.decode(locations[0].getValue(), "utf-8"));
if (u.getHost().equalsIgnoreCase(uNew.getHost())) {
openRosaServer = true;
// trust the server to tell us a new location
// ... and possibly to use https instead.
uriRemap.put(u, uNew);
u = uNew;
} else {
// Don't follow a redirection attempt to a different host.
// We can't tell if this is a spoof or not.
outcome.mResults.put(
id,
fail
+ "Unexpected redirection attempt to a different host: "
+ uNew.toString());
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
return true;
}
} catch (Exception e) {
e.printStackTrace();
outcome.mResults.put(id, fail + urlString + " " + e.toString());
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
return true;
}
}
} else {
// may be a server that does not handle
WebUtils.discardEntityBytes(response);
Log.w(t, "Status code on Head request: " + statusCode);
if (statusCode >= HttpStatus.SC_OK && statusCode < HttpStatus.SC_MULTIPLE_CHOICES) {
outcome.mResults.put(
id,
fail
+ "Invalid status code on Head request. If you have a web proxy, you may need to login to your network. ");
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
return true;
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e(t, e.toString());
WebUtils.clearHttpConnectionManager();
outcome.mResults.put(id, fail + "Client Protocol Exception");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
return true;
} catch (ConnectTimeoutException e) {
e.printStackTrace();
Log.e(t, e.toString());
WebUtils.clearHttpConnectionManager();
outcome.mResults.put(id, fail + "Connection Timeout");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
return true;
} catch (UnknownHostException e) {
e.printStackTrace();
Log.e(t, e.toString());
WebUtils.clearHttpConnectionManager();
outcome.mResults.put(id, fail + e.toString() + " :: Network Connection Failed");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
return true;
} catch (SocketTimeoutException e) {
e.printStackTrace();
Log.e(t, e.toString());
WebUtils.clearHttpConnectionManager();
outcome.mResults.put(id, fail + "Connection Timeout");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
return true;
} catch (HttpHostConnectException e) {
e.printStackTrace();
Log.e(t, e.toString());
WebUtils.clearHttpConnectionManager();
outcome.mResults.put(id, fail + "Network Connection Refused");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
return true;
} catch (Exception e) {
e.printStackTrace();
Log.e(t, e.toString());
WebUtils.clearHttpConnectionManager();
outcome.mResults.put(id, fail + "Generic Exception");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
return true;
}
}
// At this point, we may have updated the uri to use https.
// This occurs only if the Location header keeps the host name
// the same. If it specifies a different host name, we error
// out.
//
// And we may have set authentication cookies in our
// cookiestore (referenced by localContext) that will enable
// authenticated publication to the server.
//
// get instance file
File instanceFile = new File(instanceFilePath);
// Under normal operations, we upload the instanceFile to
// the server. However, during the save, there is a failure
// window that may mark the submission as complete but leave
// the file-to-be-uploaded with the name "submission.xml" and
// the plaintext submission files on disk. In this case,
// upload the submission.xml and all the files in the directory.
// This means the plaintext files and the encrypted files
// will be sent to the server and the server will have to
// figure out what to do with them.
File submissionFile = new File(instanceFile.getParentFile(), "submission.xml");
if ( submissionFile.exists() ) {
Log.w(t, "submission.xml will be uploaded instead of " + instanceFile.getAbsolutePath());
} else {
submissionFile = instanceFile;
}
if (!instanceFile.exists() && !submissionFile.exists()) {
outcome.mResults.put(id, fail + "instance XML file does not exist!");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
return true;
}
// find all files in parent directory
File[] allFiles = instanceFile.getParentFile().listFiles();
// add media files
List<File> files = new ArrayList<File>();
for (File f : allFiles) {
String fileName = f.getName();
int dotIndex = fileName.lastIndexOf(".");
String extension = "";
if (dotIndex != -1) {
extension = fileName.substring(dotIndex + 1);
}
if (fileName.startsWith(".")) {
// ignore invisible files
continue;
}
if (fileName.equals(instanceFile.getName())) {
continue; // the xml file has already been added
} else if (fileName.equals(submissionFile.getName())) {
continue; // the xml file has already been added
} else if (openRosaServer) {
files.add(f);
} else if (extension.equals("jpg")) { // legacy 0.9x
files.add(f);
} else if (extension.equals("3gpp")) { // legacy 0.9x
files.add(f);
} else if (extension.equals("3gp")) { // legacy 0.9x
files.add(f);
} else if (extension.equals("mp4")) { // legacy 0.9x
files.add(f);
} else {
Log.w(t, "unrecognized file type " + f.getName());
}
}
boolean first = true;
int j = 0;
int lastJ;
while (j < files.size() || first) {
lastJ = j;
first = false;
HttpPost httppost = WebUtils.createOpenRosaHttpPost(u);
MimeTypeMap m = MimeTypeMap.getSingleton();
long byteCount = 0L;
// mime post
MultipartEntity entity = new MultipartEntity();
// add the submission file first...
FileBody fb = new FileBody(submissionFile, "text/xml");
entity.addPart("xml_submission_file", fb);
Log.i(t, "added xml_submission_file: " + submissionFile.getName());
byteCount += submissionFile.length();
for (; j < files.size(); j++) {
File f = files.get(j);
String fileName = f.getName();
int idx = fileName.lastIndexOf(".");
String extension = "";
if (idx != -1) {
extension = fileName.substring(idx + 1);
}
String contentType = m.getMimeTypeFromExtension(extension);
// we will be processing every one of these, so
// we only need to deal with the content type determination...
if (extension.equals("xml")) {
fb = new FileBody(f, "text/xml");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added xml file " + f.getName());
} else if (extension.equals("jpg")) {
fb = new FileBody(f, "image/jpeg");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added image file " + f.getName());
} else if (extension.equals("3gpp")) {
fb = new FileBody(f, "audio/3gpp");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added audio file " + f.getName());
} else if (extension.equals("3gp")) {
fb = new FileBody(f, "video/3gpp");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added video file " + f.getName());
} else if (extension.equals("mp4")) {
fb = new FileBody(f, "video/mp4");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added video file " + f.getName());
} else if (extension.equals("csv")) {
fb = new FileBody(f, "text/csv");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added csv file " + f.getName());
} else if (f.getName().endsWith(".amr")) {
fb = new FileBody(f, "audio/amr");
entity.addPart(f.getName(), fb);
Log.i(t, "added audio file " + f.getName());
} else if (extension.equals("xls")) {
fb = new FileBody(f, "application/vnd.ms-excel");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added xls file " + f.getName());
} else if (contentType != null) {
fb = new FileBody(f, contentType);
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t,
"added recognized filetype (" + contentType + ") " + f.getName());
} else {
contentType = "application/octet-stream";
fb = new FileBody(f, contentType);
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.w(t, "added unrecognized file (" + contentType + ") " + f.getName());
}
// we've added at least one attachment to the request...
if (j + 1 < files.size()) {
if ((j-lastJ+1 > 100) || (byteCount + files.get(j + 1).length() > 10000000L)) {
// the next file would exceed the 10MB threshold...
Log.i(t, "Extremely long post is being split into multiple posts");
try {
StringBody sb = new StringBody("yes", Charset.forName("UTF-8"));
entity.addPart("*isIncomplete*", sb);
} catch (Exception e) {
e.printStackTrace(); // never happens...
}
++j; // advance over the last attachment added...
break;
}
}
}
httppost.setEntity(entity);
// prepare response and return uploaded
HttpResponse response = null;
try {
Log.i(t, "Issuing POST request for " + id + " to: " + u.toString());
response = httpclient.execute(httppost, localContext);
int responseCode = response.getStatusLine().getStatusCode();
WebUtils.discardEntityBytes(response);
Log.i(t, "Response code:" + responseCode);
// verify that the response was a 201 or 202.
// If it wasn't, the submission has failed.
if (responseCode != HttpStatus.SC_CREATED && responseCode != HttpStatus.SC_ACCEPTED) {
if (responseCode == HttpStatus.SC_OK) {
outcome.mResults.put(id, fail + "Network login failure? Again?");
} else if (responseCode == HttpStatus.SC_UNAUTHORIZED) {
// clear the cookies -- should not be necessary?
Collect.getInstance().getCookieStore().clear();
outcome.mResults.put(id, fail + response.getStatusLine().getReasonPhrase()
+ " (" + responseCode + ") at " + urlString);
} else {
outcome.mResults.put(id, fail + response.getStatusLine().getReasonPhrase()
+ " (" + responseCode + ") at " + urlString);
}
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
return true;
}
} catch (Exception e) {
e.printStackTrace();
Log.e(t, e.toString());
WebUtils.clearHttpConnectionManager();
outcome.mResults.put(id, fail + "Generic Exception. " + e.toString());
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
return true;
}
}
// if it got here, it must have worked
outcome.mResults.put(id, Collect.getInstance().getString(R.string.success));
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMITTED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
return true;
}
// TODO: This method is like 350 lines long, down from 400.
// still. ridiculous. make it smaller.
protected Outcome doInBackground(Long... values) {
Outcome outcome = new Outcome();
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 deviceId = new PropertyManager(Collect.getInstance().getApplicationContext())
.getSingularProperty(PropertyManager.OR_DEVICE_ID_PROPERTY);
// get shared HttpContext so that authentication and cookies are retained.
HttpContext localContext = Collect.getInstance().getHttpContext();
Map<Uri, Uri> uriRemap = new HashMap<Uri, Uri>();
Cursor c = null;
try {
c = Collect.getInstance().getContentResolver()
.query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null);
if (c.getCount() > 0) {
c.moveToPosition(-1);
while (c.moveToNext()) {
if (isCancelled()) {
return outcome;
}
publishProgress(c.getPosition() + 1, c.getCount());
String instance = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
String id = c.getString(c.getColumnIndex(InstanceColumns._ID));
Uri toUpdate = Uri.withAppendedPath(InstanceColumns.CONTENT_URI, id);
int subIdx = c.getColumnIndex(InstanceColumns.SUBMISSION_URI);
String urlString = c.isNull(subIdx) ? null : c.getString(subIdx);
if (urlString == null) {
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(Collect.getInstance());
urlString = settings.getString(PreferencesActivity.KEY_SERVER_URL,
Collect.getInstance().getString(R.string.default_server_url));
if ( urlString.charAt(urlString.length()-1) == '/') {
urlString = urlString.substring(0, urlString.length()-1);
}
// NOTE: /submission must not be translated! It is the well-known path on the server.
String submissionUrl =
settings.getString(PreferencesActivity.KEY_SUBMISSION_URL,
Collect.getInstance().getString(R.string.default_odk_submission));
if ( submissionUrl.charAt(0) != '/') {
submissionUrl = "/" + submissionUrl;
}
urlString = urlString + submissionUrl;
}
// add the deviceID to the request...
try {
urlString += "?deviceID=" + URLEncoder.encode(deviceId, "UTF-8");
} catch (UnsupportedEncodingException e) {
// unreachable...
}
if ( !uploadOneSubmission(urlString, id, instance, toUpdate, localContext, uriRemap, outcome) ) {
return outcome; // get credentials...
}
}
}
} finally {
if (c != null) {
c.close();
}
}
return outcome;
}
@Override
protected void onPostExecute(Outcome outcome) {
synchronized (this) {
if (mStateListener != null) {
if (outcome.mAuthRequestingServer != null) {
mStateListener.authRequest(outcome.mAuthRequestingServer, outcome.mResults);
} else {
mStateListener.uploadingComplete(outcome.mResults);
}
}
}
}
@Override
protected void onProgressUpdate(Integer... values) {
synchronized (this) {
if (mStateListener != null) {
// update progress and total
mStateListener.progressUpdate(values[0].intValue(), values[1].intValue());
}
}
}
public void setUploaderListener(InstanceUploaderListener sl) {
synchronized (this) {
mStateListener = sl;
}
}
}
| Java |
package org.odk.collect.android.receivers;
import java.util.ArrayList;
import java.util.HashMap;
import org.odk.collect.android.R;
import org.odk.collect.android.listeners.InstanceUploaderListener;
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.tasks.InstanceUploaderTask;
import org.odk.collect.android.utilities.WebUtils;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.preference.PreferenceManager;
public class NetworkReceiver extends BroadcastReceiver implements InstanceUploaderListener {
// turning on wifi often gets two CONNECTED events. we only want to run one thread at a time
public static boolean running = false;
InstanceUploaderTask mInstanceUploaderTask;
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
NetworkInfo currentNetworkInfo = (NetworkInfo) intent
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
if (currentNetworkInfo.getState() == NetworkInfo.State.CONNECTED) {
if (interfaceIsEnabled(context, currentNetworkInfo)) {
uploadForms(context);
}
}
} else if (action.equals("org.odk.collect.android.FormSaved")) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
if (ni == null || !ni.isConnected()) {
// not connected, do nothing
} else {
if (interfaceIsEnabled(context, ni)) {
uploadForms(context);
}
}
}
}
private boolean interfaceIsEnabled(Context context,
NetworkInfo currentNetworkInfo) {
// make sure autosend is enabled on the given connected interface
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
boolean sendwifi = sharedPreferences.getBoolean(
PreferencesActivity.KEY_AUTOSEND_WIFI, false);
boolean sendnetwork = sharedPreferences.getBoolean(
PreferencesActivity.KEY_AUTOSEND_NETWORK, false);
return (currentNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI
&& sendwifi || currentNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE
&& sendnetwork);
}
private void uploadForms(Context context) {
if (!running) {
running = true;
String selection = InstanceColumns.STATUS + "=? or " + InstanceColumns.STATUS + "=?";
String selectionArgs[] =
{
InstanceProviderAPI.STATUS_COMPLETE,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED
};
Cursor c =
context.getContentResolver().query(InstanceColumns.CONTENT_URI, null, selection,
selectionArgs, null);
ArrayList<Long> toUpload = new ArrayList<Long>();
if (c != null && c.getCount() > 0) {
c.move(-1);
while (c.moveToNext()) {
Long l = c.getLong(c.getColumnIndex(InstanceColumns._ID));
toUpload.add(Long.valueOf(l));
}
// get the username, password, and server from preferences
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(context);
String storedUsername = settings.getString(PreferencesActivity.KEY_USERNAME, null);
String storedPassword = settings.getString(PreferencesActivity.KEY_PASSWORD, null);
String server = settings.getString(PreferencesActivity.KEY_SERVER_URL,
context.getString(R.string.default_server_url));
String url = server
+ settings.getString(PreferencesActivity.KEY_FORMLIST_URL,
context.getString(R.string.default_odk_formlist));
Uri u = Uri.parse(url);
WebUtils.addCredentials(storedUsername, storedPassword, u.getHost());
mInstanceUploaderTask = new InstanceUploaderTask();
mInstanceUploaderTask.setUploaderListener(this);
Long[] toSendArray = new Long[toUpload.size()];
toUpload.toArray(toSendArray);
mInstanceUploaderTask.execute(toSendArray);
} else {
running = false;
}
}
}
@Override
public void uploadingComplete(HashMap<String, String> result) {
// task is done
mInstanceUploaderTask.setUploaderListener(null);
running = false;
}
@Override
public void progressUpdate(int progress, int total) {
// do nothing
}
@Override
public void authRequest(Uri url, HashMap<String, String> doneSoFar) {
// if we get an auth request, just fail
mInstanceUploaderTask.setUploaderListener(null);
running = false;
}
} | Java |
/*
* 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.application;
import android.app.Application;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Environment;
import android.preference.PreferenceManager;
import org.odk.collect.android.R;
import org.odk.collect.android.database.ActivityLogger;
import org.odk.collect.android.logic.FormController;
import org.odk.collect.android.logic.PropertyManager;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.odk.collect.android.utilities.AgingCredentialsProvider;
import org.opendatakit.httpclientandroidlib.client.CookieStore;
import org.opendatakit.httpclientandroidlib.client.CredentialsProvider;
import org.opendatakit.httpclientandroidlib.client.protocol.ClientContext;
import org.opendatakit.httpclientandroidlib.impl.client.BasicCookieStore;
import org.opendatakit.httpclientandroidlib.protocol.BasicHttpContext;
import org.opendatakit.httpclientandroidlib.protocol.HttpContext;
import java.io.File;
/**
* Extends the Application class to implement
*
* @author carlhartung
*/
public class Collect extends Application {
// Storage paths
public static final String ODK_ROOT = Environment.getExternalStorageDirectory()
+ File.separator + "odk";
public static final String FORMS_PATH = ODK_ROOT + File.separator + "forms";
public static final String INSTANCES_PATH = ODK_ROOT + File.separator + "instances";
public static final String CACHE_PATH = ODK_ROOT + File.separator + ".cache";
public static final String METADATA_PATH = ODK_ROOT + File.separator + "metadata";
public static final String TMPFILE_PATH = CACHE_PATH + File.separator + "tmp.jpg";
public static final String TMPDRAWFILE_PATH = CACHE_PATH + File.separator + "tmpDraw.jpg";
public static final String TMPXML_PATH = CACHE_PATH + File.separator + "tmp.xml";
public static final String LOG_PATH = ODK_ROOT + File.separator + "log";
public static final String DEFAULT_FONTSIZE = "21";
// share all session cookies across all sessions...
private CookieStore cookieStore = new BasicCookieStore();
// retain credentials for 7 minutes...
private CredentialsProvider credsProvider = new AgingCredentialsProvider(7 * 60 * 1000);
private ActivityLogger mActivityLogger;
private FormController mFormController = null;
private static Collect singleton = null;
public static Collect getInstance() {
return singleton;
}
public ActivityLogger getActivityLogger() {
return mActivityLogger;
}
public FormController getFormController() {
return mFormController;
}
public void setFormController(FormController controller) {
mFormController = controller;
}
public static int getQuestionFontsize() {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(Collect
.getInstance());
String question_font = settings.getString(PreferencesActivity.KEY_FONT_SIZE,
Collect.DEFAULT_FONTSIZE);
int questionFontsize = Integer.valueOf(question_font);
return questionFontsize;
}
public String getVersionedAppName() {
String versionDetail = "";
try {
PackageInfo pinfo;
pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);
int versionNumber = pinfo.versionCode;
String versionName = pinfo.versionName;
versionDetail = " " + versionName + " (" + versionNumber + ")";
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return getString(R.string.app_name) + versionDetail;
}
/**
* Creates required directories on the SDCard (or other external storage)
*
* @throws RuntimeException if there is no SDCard or the directory exists as a non directory
*/
public static void createODKDirs() throws RuntimeException {
String cardstatus = Environment.getExternalStorageState();
if (!cardstatus.equals(Environment.MEDIA_MOUNTED)) {
RuntimeException e =
new RuntimeException("ODK reports :: SDCard error: "
+ Environment.getExternalStorageState());
throw e;
}
String[] dirs = {
ODK_ROOT, FORMS_PATH, INSTANCES_PATH, CACHE_PATH, METADATA_PATH
};
for (String dirName : dirs) {
File dir = new File(dirName);
if (!dir.exists()) {
if (!dir.mkdirs()) {
RuntimeException e =
new RuntimeException("ODK reports :: Cannot create directory: "
+ dirName);
throw e;
}
} else {
if (!dir.isDirectory()) {
RuntimeException e =
new RuntimeException("ODK reports :: " + dirName
+ " exists, but is not a directory");
throw e;
}
}
}
}
/**
* Construct and return a session context with shared cookieStore and credsProvider so a user
* does not have to re-enter login information.
*
* @return
*/
public synchronized HttpContext getHttpContext() {
// context holds authentication state machine, so it cannot be
// shared across independent activities.
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
localContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);
return localContext;
}
public CredentialsProvider getCredentialsProvider() {
return credsProvider;
}
public CookieStore getCookieStore() {
return cookieStore;
}
@Override
public void onCreate() {
singleton = this;
// // set up logging defaults for apache http component stack
// Log log;
// log = LogFactory.getLog("org.opendatakit.httpclientandroidlib");
// log.enableError(true);
// log.enableWarn(true);
// log.enableInfo(true);
// log.enableDebug(true);
// log = LogFactory.getLog("org.opendatakit.httpclientandroidlib.wire");
// log.enableError(true);
// log.enableWarn(false);
// log.enableInfo(false);
// log.enableDebug(false);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
super.onCreate();
PropertyManager mgr = new PropertyManager(this);
mActivityLogger = new ActivityLogger(
mgr.getSingularProperty(PropertyManager.DEVICE_ID_PROPERTY));
}
}
| Java |
/*
* 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.preferences;
import java.util.ArrayList;
import org.odk.collect.android.R;
import org.odk.collect.android.utilities.UrlUtils;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.provider.MediaStore.Images;
import android.text.InputFilter;
import android.text.Spanned;
import android.widget.Toast;
public class PreferencesActivity extends PreferenceActivity implements
OnPreferenceChangeListener {
protected static final int IMAGE_CHOOSER = 0;
public static final String KEY_INFO = "info";
public static final String KEY_LAST_VERSION = "lastVersion";
public static final String KEY_FIRST_RUN = "firstRun";
public static final String KEY_SHOW_SPLASH = "showSplash";
public static final String KEY_SPLASH_PATH = "splashPath";
public static final String KEY_FONT_SIZE = "font_size";
public static final String KEY_SELECTED_GOOGLE_ACCOUNT = "selected_google_account";
public static final String KEY_GOOGLE_SUBMISSION = "google_submission_id";
public static final String KEY_SERVER_URL = "server_url";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_PROTOCOL = "protocol";
// must match /res/arrays.xml
public static final String PROTOCOL_ODK_DEFAULT = "odk_default";
public static final String PROTOCOL_GOOGLE = "google";
public static final String PROTOCOL_OTHER = "";
public static final String NAVIGATION_SWIPE = "swipe";
public static final String NAVIGATION_BUTTONS = "buttons";
public static final String NAVIGATION_SWIPE_BUTTONS = "swipe_buttons";
public static final String KEY_FORMLIST_URL = "formlist_url";
public static final String KEY_SUBMISSION_URL = "submission_url";
public static final String KEY_COMPLETED_DEFAULT = "default_completed";
public static final String KEY_AUTH = "auth";
public static final String KEY_AUTOSEND_WIFI = "autosend_wifi";
public static final String KEY_AUTOSEND_NETWORK = "autosend_network";
public static final String KEY_NAVIGATION = "navigation";
private PreferenceScreen mSplashPathPreference;
private EditTextPreference mSubmissionUrlPreference;
private EditTextPreference mFormListUrlPreference;
private EditTextPreference mServerUrlPreference;
private EditTextPreference mUsernamePreference;
private EditTextPreference mPasswordPreference;
private ListPreference mSelectedGoogleAccountPreference;
private ListPreference mFontSizePreference;
private ListPreference mNavigationPreference;
private CheckBoxPreference mAutosendWifiPreference;
private CheckBoxPreference mAutosendNetworkPreference;
private ListPreference mProtocolPreference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
setTitle(getString(R.string.app_name) + " > "
+ getString(R.string.general_preferences));
// not super safe, but we're just putting in this mode to help
// administrate
// would require code to access it
boolean adminMode = getIntent().getBooleanExtra("adminMode", false);
SharedPreferences adminPreferences = getSharedPreferences(
AdminPreferencesActivity.ADMIN_PREFERENCES, 0);
boolean serverAvailable = adminPreferences.getBoolean(
AdminPreferencesActivity.KEY_CHANGE_SERVER, true);
boolean urlAvailable = adminPreferences.getBoolean(
AdminPreferencesActivity.KEY_CHANGE_URL, true);
PreferenceCategory autosendCategory = (PreferenceCategory) findPreference(getString(R.string.autosend));
mAutosendWifiPreference = (CheckBoxPreference) findPreference(KEY_AUTOSEND_WIFI);
boolean autosendWifiAvailable = adminPreferences.getBoolean(
AdminPreferencesActivity.KEY_AUTOSEND_WIFI, true);
if (!(autosendWifiAvailable || adminMode)) {
autosendCategory.removePreference(mAutosendWifiPreference);
}
mAutosendNetworkPreference = (CheckBoxPreference) findPreference(KEY_AUTOSEND_NETWORK);
boolean autosendNetworkAvailable = adminPreferences.getBoolean(
AdminPreferencesActivity.KEY_AUTOSEND_NETWORK, true);
if (!(autosendNetworkAvailable || adminMode)) {
autosendCategory.removePreference(mAutosendNetworkPreference);
}
if (!(autosendNetworkAvailable || autosendWifiAvailable || adminMode)) {
getPreferenceScreen().removePreference(autosendCategory);
}
PreferenceCategory serverCategory = (PreferenceCategory) findPreference(getString(R.string.server_preferences));
// declared early to prevent NPE in toggleServerPaths
mFormListUrlPreference = (EditTextPreference) findPreference(KEY_FORMLIST_URL);
mSubmissionUrlPreference = (EditTextPreference) findPreference(KEY_SUBMISSION_URL);
mProtocolPreference = (ListPreference) findPreference(KEY_PROTOCOL);
mProtocolPreference.setSummary(mProtocolPreference.getEntry());
if (mProtocolPreference.getValue().equals("odk_default")) {
mFormListUrlPreference.setEnabled(false);
mSubmissionUrlPreference.setEnabled(false);
} else {
mFormListUrlPreference.setEnabled(true);
mSubmissionUrlPreference.setEnabled(true);
}
mProtocolPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
int index = ((ListPreference) preference)
.findIndexOfValue(newValue.toString());
String entry = (String) ((ListPreference) preference)
.getEntries()[index];
String value = (String) ((ListPreference) preference)
.getEntryValues()[index];
((ListPreference) preference).setSummary(entry);
if (value.equals("odk_default")) {
mFormListUrlPreference.setEnabled(false);
mFormListUrlPreference.setText(getString(R.string.default_odk_formlist));
mFormListUrlPreference.setSummary(mFormListUrlPreference.getText());
mSubmissionUrlPreference.setEnabled(false);
mSubmissionUrlPreference.setText(getString(R.string.default_odk_submission));
mSubmissionUrlPreference.setSummary(mSubmissionUrlPreference.getText());
} else {
mFormListUrlPreference.setEnabled(true);
mSubmissionUrlPreference.setEnabled(true);
}
return true;
}
});
mServerUrlPreference = (EditTextPreference) findPreference(KEY_SERVER_URL);
mServerUrlPreference
.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
String url = newValue.toString();
// remove all trailing "/"s
while (url.endsWith("/")) {
url = url.substring(0, url.length() - 1);
}
if (UrlUtils.isValidUrl(url)) {
preference.setSummary(newValue.toString());
return true;
} else {
Toast.makeText(getApplicationContext(),
R.string.url_error, Toast.LENGTH_SHORT)
.show();
return false;
}
}
});
mServerUrlPreference.setSummary(mServerUrlPreference.getText());
mServerUrlPreference.getEditText().setFilters(
new InputFilter[] { getReturnFilter() });
if (!(serverAvailable || adminMode)) {
Preference protocol = findPreference(KEY_PROTOCOL);
serverCategory.removePreference(protocol);
} else {
// this just removes the value from protocol, but protocol doesn't
// exist if we take away access
disableFeaturesInDevelopment();
}
if (!(urlAvailable || adminMode)) {
serverCategory.removePreference(mServerUrlPreference);
}
mUsernamePreference = (EditTextPreference) findPreference(KEY_USERNAME);
mUsernamePreference.setOnPreferenceChangeListener(this);
mUsernamePreference.setSummary(mUsernamePreference.getText());
mUsernamePreference.getEditText().setFilters(
new InputFilter[] { getReturnFilter() });
boolean usernameAvailable = adminPreferences.getBoolean(
AdminPreferencesActivity.KEY_CHANGE_USERNAME, true);
if (!(usernameAvailable || adminMode)) {
serverCategory.removePreference(mUsernamePreference);
}
mPasswordPreference = (EditTextPreference) findPreference(KEY_PASSWORD);
mPasswordPreference
.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
String pw = newValue.toString();
if (pw.length() > 0) {
mPasswordPreference.setSummary("********");
} else {
mPasswordPreference.setSummary("");
}
return true;
}
});
if (mPasswordPreference.getText() != null
&& mPasswordPreference.getText().length() > 0) {
mPasswordPreference.setSummary("********");
}
mUsernamePreference.getEditText().setFilters(
new InputFilter[] { getReturnFilter() });
boolean passwordAvailable = adminPreferences.getBoolean(
AdminPreferencesActivity.KEY_CHANGE_PASSWORD, true);
if (!(passwordAvailable || adminMode)) {
serverCategory.removePreference(mPasswordPreference);
}
// get list of google accounts
final Account[] accounts = AccountManager.get(getApplicationContext())
.getAccountsByType("com.google");
ArrayList<String> accountEntries = new ArrayList<String>();
ArrayList<String> accountValues = new ArrayList<String>();
for (int i = 0; i < accounts.length; i++) {
accountEntries.add(accounts[i].name);
accountValues.add(accounts[i].name);
}
accountEntries.add(getString(R.string.no_account));
accountValues.add("");
mSelectedGoogleAccountPreference = (ListPreference) findPreference(KEY_SELECTED_GOOGLE_ACCOUNT);
mSelectedGoogleAccountPreference.setEntries(accountEntries
.toArray(new String[accountEntries.size()]));
mSelectedGoogleAccountPreference.setEntryValues(accountValues
.toArray(new String[accountValues.size()]));
mSelectedGoogleAccountPreference
.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
int index = ((ListPreference) preference)
.findIndexOfValue(newValue.toString());
String value = (String) ((ListPreference) preference)
.getEntryValues()[index];
((ListPreference) preference).setSummary(value);
return true;
}
});
mSelectedGoogleAccountPreference
.setSummary(mSelectedGoogleAccountPreference.getValue());
boolean googleAccountAvailable = adminPreferences.getBoolean(
AdminPreferencesActivity.KEY_CHANGE_GOOGLE_ACCOUNT, true);
if (!(googleAccountAvailable || adminMode)) {
serverCategory.removePreference(mSelectedGoogleAccountPreference);
}
mFormListUrlPreference.setOnPreferenceChangeListener(this);
mFormListUrlPreference.setSummary(mFormListUrlPreference.getText());
mServerUrlPreference.getEditText().setFilters(
new InputFilter[] { getReturnFilter(), getWhitespaceFilter() });
if (!(serverAvailable || adminMode)) {
serverCategory.removePreference(mFormListUrlPreference);
}
mSubmissionUrlPreference.setOnPreferenceChangeListener(this);
mSubmissionUrlPreference.setSummary(mSubmissionUrlPreference.getText());
mServerUrlPreference.getEditText().setFilters(
new InputFilter[] { getReturnFilter(), getWhitespaceFilter() });
if (!(serverAvailable || adminMode)) {
serverCategory.removePreference(mSubmissionUrlPreference);
}
if (!(serverAvailable || urlAvailable || usernameAvailable || passwordAvailable
|| googleAccountAvailable || adminMode)) {
getPreferenceScreen().removePreference(serverCategory);
}
PreferenceCategory clientCategory = (PreferenceCategory) findPreference(getString(R.string.client));
boolean navigationAvailable = adminPreferences.getBoolean(
AdminPreferencesActivity.KEY_NAVIGATION, true);
mNavigationPreference = (ListPreference) findPreference(KEY_NAVIGATION);
mNavigationPreference.setSummary(mNavigationPreference.getEntry());
mNavigationPreference
.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
int index = ((ListPreference) preference)
.findIndexOfValue(newValue.toString());
String entry = (String) ((ListPreference) preference)
.getEntries()[index];
((ListPreference) preference).setSummary(entry);
return true;
}
});
if (!(navigationAvailable || adminMode)) {
clientCategory.removePreference(mNavigationPreference);
}
boolean fontAvailable = adminPreferences.getBoolean(
AdminPreferencesActivity.KEY_CHANGE_FONT_SIZE, true);
mFontSizePreference = (ListPreference) findPreference(KEY_FONT_SIZE);
mFontSizePreference.setSummary(mFontSizePreference.getEntry());
mFontSizePreference
.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
int index = ((ListPreference) preference)
.findIndexOfValue(newValue.toString());
String entry = (String) ((ListPreference) preference)
.getEntries()[index];
((ListPreference) preference).setSummary(entry);
return true;
}
});
if (!(fontAvailable || adminMode)) {
clientCategory.removePreference(mFontSizePreference);
}
boolean defaultAvailable = adminPreferences.getBoolean(
AdminPreferencesActivity.KEY_DEFAULT_TO_FINALIZED, true);
Preference defaultFinalized = findPreference(KEY_COMPLETED_DEFAULT);
if (!(defaultAvailable || adminMode)) {
clientCategory.removePreference(defaultFinalized);
}
mSplashPathPreference = (PreferenceScreen) findPreference(KEY_SPLASH_PATH);
mSplashPathPreference
.setOnPreferenceClickListener(new OnPreferenceClickListener() {
private void launchImageChooser() {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("image/*");
startActivityForResult(i,
PreferencesActivity.IMAGE_CHOOSER);
}
@Override
public boolean onPreferenceClick(Preference preference) {
// if you have a value, you can clear it or select new.
CharSequence cs = mSplashPathPreference.getSummary();
if (cs != null && cs.toString().contains("/")) {
final CharSequence[] items = {
getString(R.string.select_another_image),
getString(R.string.use_odk_default) };
AlertDialog.Builder builder = new AlertDialog.Builder(
PreferencesActivity.this);
builder.setTitle(getString(R.string.change_splash_path));
builder.setNeutralButton(
getString(R.string.cancel),
new DialogInterface.OnClickListener() {
@Override
public void onClick(
DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.setItems(items,
new DialogInterface.OnClickListener() {
@Override
public void onClick(
DialogInterface dialog, int item) {
if (items[item]
.equals(getString(R.string.select_another_image))) {
launchImageChooser();
} else {
setSplashPath(getString(R.string.default_splash_path));
}
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
launchImageChooser();
}
return true;
}
});
mSplashPathPreference.setSummary(mSplashPathPreference
.getSharedPreferences().getString(KEY_SPLASH_PATH,
getString(R.string.default_splash_path)));
boolean showSplashAvailable = adminPreferences.getBoolean(
AdminPreferencesActivity.KEY_SHOW_SPLASH_SCREEN, true);
CheckBoxPreference showSplashPreference = (CheckBoxPreference) findPreference(KEY_SHOW_SPLASH);
if (!(showSplashAvailable || adminMode)) {
clientCategory.removePreference(showSplashPreference);
clientCategory.removePreference(mSplashPathPreference);
}
if (!(fontAvailable || defaultAvailable
|| showSplashAvailable || navigationAvailable || adminMode)) {
getPreferenceScreen().removePreference(clientCategory);
}
}
private void disableFeaturesInDevelopment() {
// remove Google Collections from protocol choices in preferences
ListPreference protocols = (ListPreference) findPreference(KEY_PROTOCOL);
int i = protocols.findIndexOfValue(PROTOCOL_GOOGLE);
if (i != -1) {
CharSequence[] entries = protocols.getEntries();
CharSequence[] entryValues = protocols.getEntryValues();
CharSequence[] newEntries = new CharSequence[entryValues.length - 1];
CharSequence[] newEntryValues = new CharSequence[entryValues.length - 1];
for (int k = 0, j = 0; j < entryValues.length; ++j) {
if (j == i)
continue;
newEntries[k] = entries[j];
newEntryValues[k] = entryValues[j];
++k;
}
protocols.setEntries(newEntries);
protocols.setEntryValues(newEntryValues);
}
}
private void setSplashPath(String path) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putString(KEY_SPLASH_PATH, path);
editor.commit();
mSplashPathPreference = (PreferenceScreen) findPreference(KEY_SPLASH_PATH);
mSplashPathPreference.setSummary(mSplashPathPreference
.getSharedPreferences().getString(KEY_SPLASH_PATH,
getString(R.string.default_splash_path)));
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_CANCELED) {
// request was canceled, so do nothing
return;
}
switch (requestCode) {
case IMAGE_CHOOSER:
String sourceImagePath = null;
// get gp of chosen file
Uri uri = intent.getData();
if (uri.toString().startsWith("file")) {
sourceImagePath = uri.toString().substring(6);
} else {
String[] projection = { Images.Media.DATA };
Cursor c = null;
try {
c = getContentResolver().query(uri, projection, null, null,
null);
int i = c.getColumnIndexOrThrow(Images.Media.DATA);
c.moveToFirst();
sourceImagePath = c.getString(i);
} finally {
if (c != null) {
c.close();
}
}
}
// setting image path
setSplashPath(sourceImagePath);
break;
}
}
/**
* Disallows whitespace from user entry
*
* @return
*/
private InputFilter getWhitespaceFilter() {
InputFilter whitespaceFilter = 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.isWhitespace(source.charAt(i))) {
return "";
}
}
return null;
}
};
return whitespaceFilter;
}
/**
* Disallows carriage returns from user entry
*
* @return
*/
private InputFilter getReturnFilter() {
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;
}
};
return returnFilter;
}
/**
* Generic listener that sets the summary to the newly selected/entered
* value
*/
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
preference.setSummary((CharSequence) newValue);
return true;
}
}
| Java |
package org.odk.collect.android.preferences;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
public class PasswordDialogPreference extends DialogPreference implements
OnClickListener {
private EditText passwordEditText;
private EditText verifyEditText;
public PasswordDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setDialogLayoutResource(R.layout.password_dialog_layout);
}
@Override
public void onBindDialogView(View view) {
passwordEditText = (EditText) view.findViewById(R.id.pwd_field);
verifyEditText = (EditText) view.findViewById(R.id.verify_field);
final String adminPW = getPersistedString("");
// populate the fields if a pw exists
if (!adminPW.equalsIgnoreCase("")) {
passwordEditText.setText(adminPW);
passwordEditText.setSelection(passwordEditText.getText().length());
verifyEditText.setText(adminPW);
}
Button positiveButton = (Button) view
.findViewById(R.id.positive_button);
positiveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String pw = passwordEditText.getText().toString();
String ver = verifyEditText.getText().toString();
if (!pw.equalsIgnoreCase("") && !ver.equalsIgnoreCase("") && pw.equals(ver)) {
// passwords are the same
persistString(pw);
Toast.makeText(PasswordDialogPreference.this.getContext(),
R.string.admin_password_changed, Toast.LENGTH_SHORT).show();
PasswordDialogPreference.this.getDialog().dismiss();
Collect.getInstance().getActivityLogger()
.logAction(this, "AdminPasswordDialog", "CHANGED");
} else if (pw.equalsIgnoreCase("") && ver.equalsIgnoreCase("")) {
persistString("");
Toast.makeText(PasswordDialogPreference.this.getContext(),
R.string.admin_password_disabled, Toast.LENGTH_SHORT).show();
PasswordDialogPreference.this.getDialog().dismiss();
Collect.getInstance().getActivityLogger()
.logAction(this, "AdminPasswordDialog", "DISABLED");
} else {
Toast.makeText(PasswordDialogPreference.this.getContext(),
R.string.admin_password_mismatch, Toast.LENGTH_SHORT).show();
Collect.getInstance().getActivityLogger()
.logAction(this, "AdminPasswordDialog", "MISMATCH");
}
}
});
Button negativeButton = (Button) view.findViewById(R.id.negative_button);
negativeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PasswordDialogPreference.this.getDialog().dismiss();
Collect.getInstance().getActivityLogger()
.logAction(this, "AdminPasswordDialog", "CANCELLED");
}
});
super.onBindDialogView(view);
}
@Override
protected void onClick() {
super.onClick();
// this seems to work to pop the keyboard when the dialog appears
// i hope this isn't a race condition
getDialog().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
@Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
// we get rid of the default buttons (that close the dialog every time)
builder.setPositiveButton(null, null);
builder.setNegativeButton(null, null);
super.onPrepareDialogBuilder(builder);
}
}
| Java |
/*
* 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.preferences;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class AdminPreferencesActivity extends PreferenceActivity {
public static String ADMIN_PREFERENCES = "admin_prefs";
// key for this preference screen
public static String KEY_ADMIN_PW = "admin_pw";
// keys for each preference
// main menu
public static String KEY_EDIT_SAVED = "edit_saved";
public static String KEY_SEND_FINALIZED = "send_finalized";
public static String KEY_GET_BLANK = "get_blank";
public static String KEY_DELETE_SAVED = "delete_saved";
// server
public static String KEY_CHANGE_URL = "change_url";
public static String KEY_CHANGE_SERVER = "change_server";
public static String KEY_CHANGE_USERNAME = "change_username";
public static String KEY_CHANGE_PASSWORD = "change_password";
public static String KEY_CHANGE_GOOGLE_ACCOUNT = "change_google_account";
// client
public static String KEY_CHANGE_FONT_SIZE = "change_font_size";
public static String KEY_DEFAULT_TO_FINALIZED = "default_to_finalized";
public static String KEY_SHOW_SPLASH_SCREEN = "show_splash_screen";
public static String KEY_SELECT_SPLASH_SCREEN = "select_splash_screen";
// form entry
public static String KEY_SAVE_MID = "save_mid";
public static String KEY_JUMP_TO = "jump_to";
public static String KEY_CHANGE_LANGUAGE = "change_language";
public static String KEY_ACCESS_SETTINGS = "access_settings";
public static String KEY_SAVE_AS = "save_as";
public static String KEY_MARK_AS_FINALIZED = "mark_as_finalized";
public static String KEY_AUTOSEND_WIFI = "autosend_wifi";
public static String KEY_AUTOSEND_NETWORK = "autosend_network";
public static String KEY_NAVIGATION = "navigation";
private static final int SAVE_PREFS_MENU = Menu.FIRST;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(getString(R.string.app_name) + " > "
+ getString(R.string.admin_preferences));
PreferenceManager prefMgr = getPreferenceManager();
prefMgr.setSharedPreferencesName(ADMIN_PREFERENCES);
prefMgr.setSharedPreferencesMode(MODE_WORLD_READABLE);
addPreferencesFromResource(R.xml.admin_preferences);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, SAVE_PREFS_MENU, 0, getString(R.string.save_preferences))
.setIcon(R.drawable.ic_menu_save);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case SAVE_PREFS_MENU:
File writeDir = new File(Collect.ODK_ROOT + "/settings");
if (!writeDir.exists()) {
if (!writeDir.mkdirs()) {
Toast.makeText(
this,
"Error creating directory "
+ writeDir.getAbsolutePath(),
Toast.LENGTH_SHORT).show();
return false;
}
}
File dst = new File(writeDir.getAbsolutePath()
+ "/collect.settings");
boolean success = AdminPreferencesActivity.saveSharedPreferencesToFile(dst, this);
if (success) {
Toast.makeText(
this,
"Settings successfully written to "
+ dst.getAbsolutePath(), Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(this,
"Error writing settings to " + dst.getAbsolutePath(),
Toast.LENGTH_LONG).show();
}
return true;
}
return super.onOptionsItemSelected(item);
}
public static boolean saveSharedPreferencesToFile(File dst, Context context) {
// this should be in a thread if it gets big, but for now it's tiny
boolean res = false;
ObjectOutputStream output = null;
try {
output = new ObjectOutputStream(new FileOutputStream(dst));
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(context);
SharedPreferences adminPreferences = context.getSharedPreferences(
AdminPreferencesActivity.ADMIN_PREFERENCES, 0);
output.writeObject(pref.getAll());
output.writeObject(adminPreferences.getAll());
res = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (output != null) {
output.flush();
output.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return res;
}
}
| Java |
/*
* 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.logic;
import org.javarosa.core.model.FormIndex;
import android.graphics.drawable.Drawable;
import java.util.ArrayList;
public class HierarchyElement {
private String mPrimaryText = "";
private String mSecondaryText = "";
private Drawable mIcon;
private int mColor;
int mType;
FormIndex mFormIndex;
ArrayList<HierarchyElement> mChildren;
public HierarchyElement(String text1, String text2, Drawable bullet, int color, int type,
FormIndex f) {
mIcon = bullet;
mPrimaryText = text1;
mSecondaryText = text2;
mColor = color;
mFormIndex = f;
mType = type;
mChildren = new ArrayList<HierarchyElement>();
}
public String getPrimaryText() {
return mPrimaryText;
}
public String getSecondaryText() {
return mSecondaryText;
}
public void setPrimaryText(String text) {
mPrimaryText = text;
}
public void setSecondaryText(String text) {
mSecondaryText = text;
}
public void setIcon(Drawable icon) {
mIcon = icon;
}
public Drawable getIcon() {
return mIcon;
}
public FormIndex getFormIndex() {
return mFormIndex;
}
public int getType() {
return mType;
}
public void setType(int newType) {
mType = newType;
}
public ArrayList<HierarchyElement> getChildren() {
return mChildren;
}
public void addChild(HierarchyElement h) {
mChildren.add(h);
}
public void setChildren(ArrayList<HierarchyElement> children) {
mChildren = children;
}
public void setColor(int color) {
mColor = color;
}
public int getColor() {
return mColor;
}
}
| Java |
/**
*
*/
package org.odk.collect.android.logic;
import org.javarosa.core.reference.PrefixedRootFactory;
import org.javarosa.core.reference.Reference;
/**
* @author ctsims
*/
public class FileReferenceFactory extends PrefixedRootFactory {
String localRoot;
public FileReferenceFactory(String localRoot) {
super(new String[] {
"file"
});
this.localRoot = localRoot;
}
@Override
protected Reference factory(String terminal, String URI) {
return new FileReference(localRoot, terminal);
}
}
| Java |
/*
* 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.logic;
import java.io.Serializable;
public class FormDetails implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public final String errorStr;
public final String formName;
public final String downloadUrl;
public final String manifestUrl;
public final String formID;
public final String formVersion;
public FormDetails(String error) {
manifestUrl = null;
downloadUrl = null;
formName = null;
formID = null;
formVersion = null;
errorStr = error;
}
public FormDetails(String name, String url, String manifest, String id, String version) {
manifestUrl = manifest;
downloadUrl = url;
formName = name;
formID = id;
formVersion = version;
errorStr = null;
}
}
| Java |
/**
*
*/
package org.odk.collect.android.logic;
import org.javarosa.core.reference.Reference;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* @author ctsims
*/
public class FileReference implements Reference {
String localPart;
String referencePart;
public FileReference(String localPart, String referencePart) {
this.localPart = localPart;
this.referencePart = referencePart;
}
private String getInternalURI() {
return "/" + localPart + referencePart;
}
@Override
public boolean doesBinaryExist() {
return new File(getInternalURI()).exists();
}
@Override
public InputStream getStream() throws IOException {
return new FileInputStream(getInternalURI());
}
@Override
public String getURI() {
return "jr://file" + referencePart;
}
@Override
public boolean isReadOnly() {
return false;
}
@Override
public OutputStream getOutputStream() throws IOException {
return new FileOutputStream(getInternalURI());
}
@Override
public void remove() {
// TODO bad practice to ignore return values
new File(getInternalURI()).delete();
}
@Override
public String getLocalURI() {
return getInternalURI();
}
@Override
public Reference[] probeAlternativeReferences() {
//We can't poll the JAR for resources, unfortunately. It's possible
//we could try to figure out something about the file and poll alternatives
//based on type (PNG-> JPG, etc)
return new Reference [0];
}
}
| Java |
/*
* 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.logic;
import java.util.HashMap;
import java.util.Locale;
import java.util.Vector;
import org.javarosa.core.services.IPropertyManager;
import org.javarosa.core.services.properties.IPropertyRules;
import org.odk.collect.android.preferences.PreferencesActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
/**
* Used to return device properties to JavaRosa
*
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class PropertyManager implements IPropertyManager {
private String t = "PropertyManager";
private Context mContext;
private TelephonyManager mTelephonyManager;
private HashMap<String, String> mProperties;
public final static String DEVICE_ID_PROPERTY = "deviceid"; // imei
private final static String SUBSCRIBER_ID_PROPERTY = "subscriberid"; // imsi
private final static String SIM_SERIAL_PROPERTY = "simserial";
private final static String PHONE_NUMBER_PROPERTY = "phonenumber";
private final static String USERNAME = "username";
private final static String EMAIL = "email";
public final static String OR_DEVICE_ID_PROPERTY = "uri:deviceid"; // imei
public final static String OR_SUBSCRIBER_ID_PROPERTY = "uri:subscriberid"; // imsi
public final static String OR_SIM_SERIAL_PROPERTY = "uri:simserial";
public final static String OR_PHONE_NUMBER_PROPERTY = "uri:phonenumber";
public final static String OR_USERNAME = "uri:username";
public final static String OR_EMAIL = "uri:email";
public String getName() {
return "Property Manager";
}
public PropertyManager(Context context) {
Log.i(t, "calling constructor");
mContext = context;
mProperties = new HashMap<String, String>();
mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
String deviceId = mTelephonyManager.getDeviceId();
String orDeviceId = null;
if (deviceId != null ) {
if ((deviceId.contains("*") || deviceId.contains("000000000000000"))) {
deviceId =
Settings.Secure
.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID);
orDeviceId = Settings.Secure.ANDROID_ID + ":" + deviceId;
} else {
orDeviceId = "imei:" + deviceId;
}
}
if ( deviceId == null ) {
// no SIM -- WiFi only
// Retrieve WiFiManager
WifiManager wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
// Get WiFi status
WifiInfo info = wifi.getConnectionInfo();
if ( info != null ) {
deviceId = info.getMacAddress();
orDeviceId = "mac:" + deviceId;
}
}
// if it is still null, use ANDROID_ID
if ( deviceId == null ) {
deviceId =
Settings.Secure
.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID);
orDeviceId = Settings.Secure.ANDROID_ID + ":" + deviceId;
}
mProperties.put(DEVICE_ID_PROPERTY, deviceId);
mProperties.put(OR_DEVICE_ID_PROPERTY, orDeviceId);
String value;
value = mTelephonyManager.getSubscriberId();
if ( value != null ) {
mProperties.put(SUBSCRIBER_ID_PROPERTY, value);
mProperties.put(OR_SUBSCRIBER_ID_PROPERTY, "imsi:" + value);
}
value = mTelephonyManager.getSimSerialNumber();
if ( value != null ) {
mProperties.put(SIM_SERIAL_PROPERTY, value);
mProperties.put(OR_SIM_SERIAL_PROPERTY, "simserial:" + value);
}
value = mTelephonyManager.getLine1Number();
if ( value != null ) {
mProperties.put(PHONE_NUMBER_PROPERTY, value);
mProperties.put(OR_PHONE_NUMBER_PROPERTY, "tel:" + value);
}
// Get the username from the settings
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext);
value = settings.getString(PreferencesActivity.KEY_USERNAME, null);
if ( value != null ) {
mProperties.put(USERNAME, value);
mProperties.put(OR_USERNAME, "username:" + value);
}
value = settings.getString(PreferencesActivity.KEY_SELECTED_GOOGLE_ACCOUNT, null);
if ( value != null ) {
mProperties.put(EMAIL, value);
mProperties.put(OR_EMAIL, "mailto:" + value);
}
}
@Override
public Vector<String> getProperty(String propertyName) {
return null;
}
@Override
public String getSingularProperty(String propertyName) {
// for now, all property names are in english...
return mProperties.get(propertyName.toLowerCase(Locale.ENGLISH));
}
@Override
public void setProperty(String propertyName, String propertyValue) {
}
@Override
public void setProperty(String propertyName, @SuppressWarnings("rawtypes") Vector propertyValue) {
}
@Override
public void addRules(IPropertyRules rules) {
}
@Override
public Vector<IPropertyRules> getRules() {
return null;
}
}
| Java |
/*
* Copyright (C) 2009 JavaRosa
*
* 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.logic;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Vector;
import org.javarosa.core.model.FormDef;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.model.GroupDef;
import org.javarosa.core.model.IDataReference;
import org.javarosa.core.model.IFormElement;
import org.javarosa.core.model.SubmissionProfile;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.core.model.instance.FormInstance;
import org.javarosa.core.model.instance.TreeElement;
import org.javarosa.core.services.transport.payload.ByteArrayPayload;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryController;
import org.javarosa.form.api.FormEntryPrompt;
import org.javarosa.model.xform.XFormSerializingVisitor;
import org.javarosa.model.xform.XPathReference;
import org.odk.collect.android.views.ODKView;
import android.util.Log;
/**
* This class is a wrapper for Javarosa's FormEntryController. In theory, if you wanted to replace
* javarosa as the form engine, you should only need to replace the methods in this file. Also, we
* haven't wrapped every method provided by FormEntryController, only the ones we've needed so far.
* Feel free to add more as necessary.
*
* @author carlhartung
*/
public class FormController {
private static final String t = "FormController";
private File mMediaFolder;
private File mInstancePath;
private FormEntryController mFormEntryController;
private FormIndex mIndexWaitingForData = null;
public static final boolean STEP_INTO_GROUP = true;
public static final boolean STEP_OVER_GROUP = false;
/**
* OpenRosa metadata tag names.
*/
private static final String INSTANCE_ID = "instanceID";
private static final String INSTANCE_NAME = "instanceName";
/**
* OpenRosa metadata of a form instance.
*
* Contains the values for the required metadata
* fields and nothing else.
*
* @author mitchellsundt@gmail.com
*
*/
public static final class InstanceMetadata {
public final String instanceId;
public final String instanceName;
InstanceMetadata( String instanceId, String instanceName ) {
this.instanceId = instanceId;
this.instanceName = instanceName;
}
};
public FormController(File mediaFolder, FormEntryController fec, File instancePath) {
mMediaFolder = mediaFolder;
mFormEntryController = fec;
mInstancePath = instancePath;
}
public File getMediaFolder() {
return mMediaFolder;
}
public File getInstancePath() {
return mInstancePath;
}
public void setInstancePath(File instancePath) {
mInstancePath = instancePath;
}
public void setIndexWaitingForData(FormIndex index) {
mIndexWaitingForData = index;
}
public FormIndex getIndexWaitingForData() {
return mIndexWaitingForData;
}
/**
* For logging purposes...
*
* @param index
* @return xpath value for this index
*/
public String getXPath(FormIndex index) {
String value;
switch ( getEvent() ) {
case FormEntryController.EVENT_BEGINNING_OF_FORM:
value = "beginningOfForm";
break;
case FormEntryController.EVENT_END_OF_FORM:
value = "endOfForm";
break;
case FormEntryController.EVENT_GROUP:
value = "group." + index.getReference().toString();
break;
case FormEntryController.EVENT_QUESTION:
value = "question." + index.getReference().toString();
break;
case FormEntryController.EVENT_PROMPT_NEW_REPEAT:
value = "promptNewRepeat." + index.getReference().toString();
break;
case FormEntryController.EVENT_REPEAT:
value = "repeat." + index.getReference().toString();
break;
case FormEntryController.EVENT_REPEAT_JUNCTURE:
value = "repeatJuncture." + index.getReference().toString();
break;
default:
value = "unexpected";
break;
}
return value;
}
public FormIndex getIndexFromXPath(String xPath) {
if ( xPath.equals("beginningOfForm") ) {
return FormIndex.createBeginningOfFormIndex();
} else if ( xPath.equals("endOfForm") ) {
return FormIndex.createEndOfFormIndex();
} else if ( xPath.equals("unexpected") ) {
Log.e(t, "Unexpected string from XPath");
throw new IllegalArgumentException("unexpected string from XPath");
} else {
FormIndex returned = null;
FormIndex saved = getFormIndex();
// the only way I know how to do this is to step through the entire form
// until the XPath of a form entry matches that of the supplied XPath
try {
jumpToIndex(FormIndex.createBeginningOfFormIndex());
int event = stepToNextEvent(true);
while ( event != FormEntryController.EVENT_END_OF_FORM ) {
String candidateXPath = getXPath(getFormIndex());
// Log.i(t, "xpath: " + candidateXPath);
if ( candidateXPath.equals(xPath) ) {
returned = getFormIndex();
break;
}
event = stepToNextEvent(true);
}
} finally {
jumpToIndex(saved);
}
return returned;
}
}
/**
* returns the event for the current FormIndex.
*
* @return
*/
public int getEvent() {
return mFormEntryController.getModel().getEvent();
}
/**
* returns the event for the given FormIndex.
*
* @param index
* @return
*/
public int getEvent(FormIndex index) {
return mFormEntryController.getModel().getEvent(index);
}
/**
* @return current FormIndex.
*/
public FormIndex getFormIndex() {
return mFormEntryController.getModel().getFormIndex();
}
/**
* Return the langauges supported by the currently loaded form.
*
* @return Array of Strings containing the languages embedded in the XForm.
*/
public String[] getLanguages() {
return mFormEntryController.getModel().getLanguages();
}
/**
* @return A String containing the title of the current form.
*/
public String getFormTitle() {
return mFormEntryController.getModel().getFormTitle();
}
/**
* @return the currently selected language.
*/
public String getLanguage() {
return mFormEntryController.getModel().getLanguage();
}
public String getBindAttribute( String attributeNamespace, String attributeName) {
return getBindAttribute( getFormIndex(), attributeNamespace, attributeName );
}
public String getBindAttribute(FormIndex idx, String attributeNamespace, String attributeName) {
return mFormEntryController.getModel().getForm().getMainInstance().resolveReference(
idx.getReference()).getBindAttributeValue(attributeNamespace, attributeName);
}
/**
* @return an array of FormEntryCaptions for the current FormIndex. This is how we get group
* information Group 1 > Group 2> etc... The element at [size-1] is the current question
* text, with group names decreasing in hierarchy until array element at [0] is the root
*/
private FormEntryCaption[] getCaptionHierarchy() {
return mFormEntryController.getModel().getCaptionHierarchy();
}
/**
* @param index
* @return an array of FormEntryCaptions for the supplied FormIndex. This is how we get group
* information Group 1 > Group 2> etc... The element at [size-1] is the current question
* text, with group names decreasing in hierarchy until array element at [0] is the root
*/
private FormEntryCaption[] getCaptionHierarchy(FormIndex index) {
return mFormEntryController.getModel().getCaptionHierarchy(index);
}
/**
* Returns a caption prompt for the given index. This is used to create a multi-question per
* screen view.
*
* @param index
* @return
*/
public FormEntryCaption getCaptionPrompt(FormIndex index) {
return mFormEntryController.getModel().getCaptionPrompt(index);
}
/**
* Return the caption for the current FormIndex. This is usually used for a repeat prompt.
*
* @return
*/
public FormEntryCaption getCaptionPrompt() {
return mFormEntryController.getModel().getCaptionPrompt();
}
/**
* This fires off the jr:preload actions and events to save values like the
* end time of a form.
*
* @return
*/
public boolean postProcessInstance() {
return mFormEntryController.getModel().getForm().postProcessInstance();
}
/**
* TODO: We need a good description of what this does, exactly, and why.
*
* @return
*/
private FormInstance getInstance() {
return mFormEntryController.getModel().getForm().getInstance();
}
/**
* A convenience method for determining if the current FormIndex is in a group that is/should be
* displayed as a multi-question view. This is useful for returning from the formhierarchy view
* to a selected index.
*
* @param index
* @return
*/
private boolean groupIsFieldList(FormIndex index) {
// if this isn't a group, return right away
IFormElement element = mFormEntryController.getModel().getForm().getChild(index);
if (!(element instanceof GroupDef)) {
return false;
}
GroupDef gd = (GroupDef) element; // exceptions?
return (ODKView.FIELD_LIST.equalsIgnoreCase(gd.getAppearanceAttr()));
}
private boolean repeatIsFieldList(FormIndex index) {
// if this isn't a group, return right away
IFormElement element = mFormEntryController.getModel().getForm().getChild(index);
if (!(element instanceof GroupDef)) {
return false;
}
GroupDef gd = (GroupDef) element; // exceptions?
return (ODKView.FIELD_LIST.equalsIgnoreCase(gd.getAppearanceAttr()));
}
/**
* Tests if the FormIndex 'index' is located inside a group that is marked as a "field-list"
*
* @param index
* @return true if index is in a "field-list". False otherwise.
*/
private boolean indexIsInFieldList(FormIndex index) {
int event = getEvent(index);
if (event == FormEntryController.EVENT_QUESTION) {
// caption[0..len-1]
// caption[len-1] == the question itself
// caption[len-2] == the first group it is contained in.
FormEntryCaption[] captions = getCaptionHierarchy(index);
if (captions.length < 2) {
// no group
return false;
}
FormEntryCaption grp = captions[captions.length - 2];
return groupIsFieldList(grp.getIndex());
} else if (event == FormEntryController.EVENT_GROUP) {
return groupIsFieldList(index);
} else if (event == FormEntryController.EVENT_REPEAT) {
return repeatIsFieldList(index);
} else {
// right now we only test Questions and Groups. Should we also handle
// repeats?
return false;
}
}
public boolean currentPromptIsQuestion() {
return (getEvent() == FormEntryController.EVENT_QUESTION
|| ((getEvent() == FormEntryController.EVENT_GROUP ||
getEvent() == FormEntryController.EVENT_REPEAT)
&& indexIsInFieldList()));
}
/**
* Tests if the current FormIndex is located inside a group that is marked as a "field-list"
*
* @return true if index is in a "field-list". False otherwise.
*/
public boolean indexIsInFieldList() {
return indexIsInFieldList(getFormIndex());
}
/**
* Attempts to save answer at the current FormIndex into the data model.
*
* @param data
* @return
*/
private int answerQuestion(IAnswerData data) {
return mFormEntryController.answerQuestion(data);
}
/**
* Attempts to save answer into the given FormIndex into the data model.
*
* @param index
* @param data
* @return
*/
public int answerQuestion(FormIndex index, IAnswerData data) {
return mFormEntryController.answerQuestion(index, data);
}
/**
* Goes through the entire form to make sure all entered answers comply with their constraints.
* Constraints are ignored on 'jump to', so answers can be outside of constraints. We don't
* allow saving to disk, though, until all answers conform to their constraints/requirements.
*
* @param markCompleted
* @return ANSWER_OK and leave index unchanged or change index to bad value and return error type.
*/
public int validateAnswers(Boolean markCompleted) {
FormIndex i = getFormIndex();
jumpToIndex(FormIndex.createBeginningOfFormIndex());
int event;
while ((event =
stepToNextEvent(FormController.STEP_INTO_GROUP)) != FormEntryController.EVENT_END_OF_FORM) {
if (event != FormEntryController.EVENT_QUESTION) {
continue;
} else {
int saveStatus = answerQuestion(getQuestionPrompt().getAnswerValue());
if (markCompleted && saveStatus != FormEntryController.ANSWER_OK) {
return saveStatus;
}
}
}
jumpToIndex(i);
return FormEntryController.ANSWER_OK;
}
/**
* saveAnswer attempts to save the current answer into the data model without doing any
* constraint checking. Only use this if you know what you're doing. For normal form filling you
* should always use answerQuestion or answerCurrentQuestion.
*
* @param index
* @param data
* @return true if saved successfully, false otherwise.
*/
public boolean saveAnswer(FormIndex index, IAnswerData data) {
return mFormEntryController.saveAnswer(index, data);
}
/**
* saveAnswer attempts to save the current answer into the data model without doing any
* constraint checking. Only use this if you know what you're doing. For normal form filling you
* should always use answerQuestion().
*
* @param index
* @param data
* @return true if saved successfully, false otherwise.
*/
public boolean saveAnswer(IAnswerData data) {
return mFormEntryController.saveAnswer(data);
}
/**
* Navigates forward in the form.
*
* @return the next event that should be handled by a view.
*/
public int stepToNextEvent(boolean stepIntoGroup) {
if ((getEvent() == FormEntryController.EVENT_GROUP ||
getEvent() == FormEntryController.EVENT_REPEAT)
&& indexIsInFieldList() && !stepIntoGroup) {
return stepOverGroup();
} else {
return mFormEntryController.stepToNextEvent();
}
}
/**
* If using a view like HierarchyView that doesn't support multi-question per screen, step over
* the group represented by the FormIndex.
*
* @return
*/
private int stepOverGroup() {
ArrayList<FormIndex> indicies = new ArrayList<FormIndex>();
GroupDef gd =
(GroupDef) mFormEntryController.getModel().getForm()
.getChild(getFormIndex());
FormIndex idxChild =
mFormEntryController.getModel().incrementIndex(
getFormIndex(), true); // descend into group
for (int i = 0; i < gd.getChildren().size(); i++) {
indicies.add(idxChild);
// don't descend
idxChild = mFormEntryController.getModel().incrementIndex(idxChild, false);
}
// jump to the end of the group
mFormEntryController.jumpToIndex(indicies.get(indicies.size() - 1));
return stepToNextEvent(STEP_OVER_GROUP);
}
/**
* used to go up one level in the formIndex. That is, if you're at 5_0, 1 (the second question
* in a repeating group), this method will return a FormInex of 5_0 (the start of the repeating
* group). If your at index 16 or 5_0, this will return null;
*
* @param index
* @return index
*/
public FormIndex stepIndexOut(FormIndex index) {
if (index.isTerminal()) {
return null;
} else {
return new FormIndex(stepIndexOut(index.getNextLevel()), index);
}
}
/**
* Move the current form index to the index of the previous question in the form.
* Step backward out of repeats and groups as needed. If the resulting question
* is itself within a field-list, move upward to the group or repeat defining that
* field-list.
*
* @return
*/
public int stepToPreviousScreenEvent() {
if (getEvent() != FormEntryController.EVENT_BEGINNING_OF_FORM) {
int event = stepToPreviousEvent();
while (event == FormEntryController.EVENT_REPEAT_JUNCTURE ||
event == FormEntryController.EVENT_PROMPT_NEW_REPEAT ||
(event == FormEntryController.EVENT_QUESTION && indexIsInFieldList()) ||
((event == FormEntryController.EVENT_GROUP
|| event == FormEntryController.EVENT_REPEAT) && !indexIsInFieldList())) {
event = stepToPreviousEvent();
}
// Work-around for broken field-list handling from 1.1.7 which breaks either
// build-generated forms or XLSForm-generated forms. If the current group
// is a GROUP with field-list and it is nested within a group or repeat with just
// this containing group, and that is also a field-list, then return the parent group.
if ( getEvent() == FormEntryController.EVENT_GROUP ) {
FormIndex currentIndex = getFormIndex();
IFormElement element = mFormEntryController.getModel().getForm().getChild(currentIndex);
if (element instanceof GroupDef) {
GroupDef gd = (GroupDef) element;
if ( ODKView.FIELD_LIST.equalsIgnoreCase(gd.getAppearanceAttr()) ) {
// OK this group is a field-list... see what the parent is...
FormEntryCaption[] fclist = this.getCaptionHierarchy(currentIndex);
if ( fclist.length > 1) {
FormEntryCaption fc = fclist[fclist.length-2];
GroupDef pd = (GroupDef) fc.getFormElement();
if ( pd.getChildren().size() == 1 &&
ODKView.FIELD_LIST.equalsIgnoreCase(pd.getAppearanceAttr()) ) {
mFormEntryController.jumpToIndex(fc.getIndex());
}
}
}
}
}
}
return getEvent();
}
/**
* Move the current form index to the index of the next question in the form.
* Stop if we should ask to create a new repeat group or if we reach the end of the form.
* If we enter a group or repeat, return that if it is a field-list definition.
* Otherwise, descend into the group or repeat searching for the first question.
*
* @return
*/
public int stepToNextScreenEvent() {
if (getEvent() != FormEntryController.EVENT_END_OF_FORM) {
int event;
group_skip: do {
event = stepToNextEvent(FormController.STEP_OVER_GROUP);
switch (event) {
case FormEntryController.EVENT_QUESTION:
case FormEntryController.EVENT_END_OF_FORM:
break group_skip;
case FormEntryController.EVENT_PROMPT_NEW_REPEAT:
break group_skip;
case FormEntryController.EVENT_GROUP:
case FormEntryController.EVENT_REPEAT:
if (indexIsInFieldList()
&& getQuestionPrompts().length != 0) {
break group_skip;
}
// otherwise it's not a field-list group, so just skip it
break;
case FormEntryController.EVENT_REPEAT_JUNCTURE:
Log.i(t, "repeat juncture: "
+ 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;
}
} while (event != FormEntryController.EVENT_END_OF_FORM);
}
return getEvent();
}
/**
* Move the current form index to the index of the first enclosing repeat
* or to the start of the form.
*
* @return
*/
public int stepToOuterScreenEvent() {
FormIndex index = stepIndexOut(getFormIndex());
int currentEvent = getEvent();
// Step out of any group indexes that are present.
while (index != null
&& getEvent(index) == FormEntryController.EVENT_GROUP) {
index = stepIndexOut(index);
}
if (index == null) {
jumpToIndex(FormIndex.createBeginningOfFormIndex());
} else {
if (currentEvent == FormEntryController.EVENT_REPEAT) {
// We were at a repeat, so stepping back brought us to then previous level
jumpToIndex(index);
} else {
// We were at a question, so stepping back brought us to either:
// The beginning. or The start of a repeat. So we need to step
// out again to go passed the repeat.
index = stepIndexOut(index);
if (index == null) {
jumpToIndex(FormIndex.createBeginningOfFormIndex());
} else {
jumpToIndex(index);
}
}
}
return getEvent();
}
public static class FailedConstraint {
public final FormIndex index;
public final int status;
FailedConstraint(FormIndex index, int status) {
this.index = index;
this.status = status;
}
}
/**
*
* @param answers
* @param evaluateConstraints
* @return FailedConstraint of first failed constraint or null if all questions were saved.
*/
public FailedConstraint saveAllScreenAnswers(LinkedHashMap<FormIndex,IAnswerData> answers, boolean evaluateConstraints) {
if (currentPromptIsQuestion()) {
Iterator<FormIndex> it = answers.keySet().iterator();
while (it.hasNext()) {
FormIndex index = it.next();
// Within a group, you can only save for question events
if (getEvent(index) == FormEntryController.EVENT_QUESTION) {
int saveStatus;
IAnswerData answer = answers.get(index);
if (evaluateConstraints) {
saveStatus = answerQuestion(index, answer);
if (saveStatus != FormEntryController.ANSWER_OK) {
return new FailedConstraint(index, saveStatus);
}
} else {
saveAnswer(index, answer);
}
} else {
Log.w(t,
"Attempted to save an index referencing something other than a question: "
+ index.getReference());
}
}
}
return null;
}
/**
* Navigates backward in the form.
*
* @return the event that should be handled by a view.
*/
public int stepToPreviousEvent() {
/*
* Right now this will always skip to the beginning of a group if that group is represented
* as a 'field-list'. Should a need ever arise to step backwards by only one step in a
* 'field-list', this method will have to be updated.
*/
mFormEntryController.stepToPreviousEvent();
// If after we've stepped, we're in a field-list, jump back to the beginning of the group
//
if (indexIsInFieldList()
&& getEvent() == FormEntryController.EVENT_QUESTION) {
// caption[0..len-1]
// caption[len-1] == the question itself
// caption[len-2] == the first group it is contained in.
FormEntryCaption[] captions = getCaptionHierarchy();
FormEntryCaption grp = captions[captions.length - 2];
int event = mFormEntryController.jumpToIndex(grp.getIndex());
// and test if this group or at least one of its children is relevant...
FormIndex idx = grp.getIndex();
if ( !mFormEntryController.getModel().isIndexRelevant(idx) ) {
return stepToPreviousEvent();
}
idx = mFormEntryController.getModel().incrementIndex(idx, true);
while ( FormIndex.isSubElement(grp.getIndex(), idx) ) {
if ( mFormEntryController.getModel().isIndexRelevant(idx) ) {
return event;
}
idx = mFormEntryController.getModel().incrementIndex(idx, true);
}
return stepToPreviousEvent();
} else if ( indexIsInFieldList() && getEvent() == FormEntryController.EVENT_GROUP) {
FormIndex grpidx = mFormEntryController.getModel().getFormIndex();
int event = mFormEntryController.getModel().getEvent();
// and test if this group or at least one of its children is relevant...
if ( !mFormEntryController.getModel().isIndexRelevant(grpidx) ) {
return stepToPreviousEvent(); // shouldn't happen?
}
FormIndex idx = mFormEntryController.getModel().incrementIndex(grpidx, true);
while ( FormIndex.isSubElement(grpidx, idx) ) {
if ( mFormEntryController.getModel().isIndexRelevant(idx) ) {
return event;
}
idx = mFormEntryController.getModel().incrementIndex(idx, true);
}
return stepToPreviousEvent();
}
return getEvent();
}
/**
* Jumps to a given FormIndex.
*
* @param index
* @return EVENT for the specified Index.
*/
public int jumpToIndex(FormIndex index) {
return mFormEntryController.jumpToIndex(index);
}
/**
* Creates a new repeated instance of the group referenced by the current FormIndex.
*
* @param questionIndex
*/
public void newRepeat() {
mFormEntryController.newRepeat();
}
/**
* If the current FormIndex is within a repeated group, will find the innermost repeat, delete
* it, and jump the FormEntryController to the previous valid index. That is, if you have group1
* (2) > group2 (3) and you call deleteRepeat, it will delete the 3rd instance of group2.
*/
public void deleteRepeat() {
FormIndex fi = mFormEntryController.deleteRepeat();
mFormEntryController.jumpToIndex(fi);
}
/**
* Sets the current language.
*
* @param language
*/
public void setLanguage(String language) {
mFormEntryController.setLanguage(language);
}
/**
* Returns an array of question promps.
*
* @return
*/
public FormEntryPrompt[] getQuestionPrompts() throws RuntimeException {
ArrayList<FormIndex> indicies = new ArrayList<FormIndex>();
FormIndex currentIndex = getFormIndex();
// For questions, there is only one.
// For groups, there could be many, but we set that below
FormEntryPrompt[] questions = new FormEntryPrompt[1];
IFormElement element = mFormEntryController.getModel().getForm().getChild(currentIndex);
if (element instanceof GroupDef) {
GroupDef gd = (GroupDef) element;
// descend into group
FormIndex idxChild = mFormEntryController.getModel().incrementIndex(currentIndex, true);
if ( gd.getChildren().size() == 1 && getEvent(idxChild) == FormEntryController.EVENT_GROUP ) {
// if we have a group definition within a field-list attribute group, and this is the
// only child in the group, check to see if it is also a field-list appearance.
// If it is, then silently recurse into it to pick up its elements.
// Work-around for the inconsistent treatment of field-list groups and repeats in 1.1.7 that
// either breaks forms generated by build or breaks forms generated by XLSForm.
IFormElement nestedElement = mFormEntryController.getModel().getForm().getChild(idxChild);
if (nestedElement instanceof GroupDef) {
GroupDef nestedGd = (GroupDef) nestedElement;
if ( ODKView.FIELD_LIST.equalsIgnoreCase(nestedGd.getAppearanceAttr()) ) {
gd = nestedGd;
idxChild = mFormEntryController.getModel().incrementIndex(idxChild, true);
}
}
}
for (int i = 0; i < gd.getChildren().size(); i++) {
indicies.add(idxChild);
// don't descend
idxChild = mFormEntryController.getModel().incrementIndex(idxChild, false);
}
// we only display relevant questions
ArrayList<FormEntryPrompt> questionList = new ArrayList<FormEntryPrompt>();
for (int i = 0; i < indicies.size(); i++) {
FormIndex index = indicies.get(i);
if (getEvent(index) != FormEntryController.EVENT_QUESTION) {
String errorMsg =
"Only questions are allowed in 'field-list'. Bad node is: "
+ index.getReference().toString(false);
RuntimeException e = new RuntimeException(errorMsg);
Log.e(t, errorMsg);
throw e;
}
// we only display relevant questions
if (mFormEntryController.getModel().isIndexRelevant(index)) {
questionList.add(getQuestionPrompt(index));
}
questions = new FormEntryPrompt[questionList.size()];
questionList.toArray(questions);
}
} else {
// We have a quesion, so just get the one prompt
questions[0] = getQuestionPrompt();
}
return questions;
}
public FormEntryPrompt getQuestionPrompt(FormIndex index) {
return mFormEntryController.getModel().getQuestionPrompt(index);
}
public FormEntryPrompt getQuestionPrompt() {
return mFormEntryController.getModel().getQuestionPrompt();
}
/**
* Returns an array of FormEntryCaptions for current FormIndex.
*
* @return
*/
public FormEntryCaption[] getGroupsForCurrentIndex() {
// return an empty array if you ask for something impossible
if (!(getEvent() == FormEntryController.EVENT_QUESTION
|| getEvent() == FormEntryController.EVENT_PROMPT_NEW_REPEAT
|| getEvent() == FormEntryController.EVENT_GROUP
|| getEvent() == FormEntryController.EVENT_REPEAT)) {
return new FormEntryCaption[0];
}
// the first caption is the question, so we skip it if it's an EVENT_QUESTION
// otherwise, the first caption is a group so we start at index 0
int lastquestion = 1;
if (getEvent() == FormEntryController.EVENT_PROMPT_NEW_REPEAT
|| getEvent() == FormEntryController.EVENT_GROUP
|| getEvent() == FormEntryController.EVENT_REPEAT) {
lastquestion = 0;
}
FormEntryCaption[] v = getCaptionHierarchy();
FormEntryCaption[] groups = new FormEntryCaption[v.length - lastquestion];
for (int i = 0; i < v.length - lastquestion; i++) {
groups[i] = v[i];
}
return groups;
}
/**
* This is used to enable/disable the "Delete Repeat" menu option.
*
* @return
*/
public boolean indexContainsRepeatableGroup() {
FormEntryCaption[] groups = getCaptionHierarchy();
if (groups.length == 0) {
return false;
}
for (int i = 0; i < groups.length; i++) {
if (groups[i].repeats())
return true;
}
return false;
}
/**
* The count of the closest group that repeats or -1.
*/
public int getLastRepeatedGroupRepeatCount() {
FormEntryCaption[] groups = getCaptionHierarchy();
if (groups.length > 0) {
for (int i = groups.length - 1; i > -1; i--) {
if (groups[i].repeats()) {
return groups[i].getMultiplicity();
}
}
}
return -1;
}
/**
* The name of the closest group that repeats or null.
*/
public String getLastRepeatedGroupName() {
FormEntryCaption[] groups = getCaptionHierarchy();
// no change
if (groups.length > 0) {
for (int i = groups.length - 1; i > -1; i--) {
if (groups[i].repeats()) {
return groups[i].getLongText();
}
}
}
return null;
}
/**
* The closest group the prompt belongs to.
*
* @return FormEntryCaption
*/
private FormEntryCaption getLastGroup() {
FormEntryCaption[] groups = getCaptionHierarchy();
if (groups == null || groups.length == 0)
return null;
else
return groups[groups.length - 1];
}
/**
* The repeat count of closest group the prompt belongs to.
*/
public int getLastRepeatCount() {
if (getLastGroup() != null) {
return getLastGroup().getMultiplicity();
}
return -1;
}
/**
* The text of closest group the prompt belongs to.
*/
public String getLastGroupText() {
if (getLastGroup() != null) {
return getLastGroup().getLongText();
}
return null;
}
/**
* Find the portion of the form that is to be submitted
*
* @return
*/
private IDataReference getSubmissionDataReference() {
FormDef formDef = mFormEntryController.getModel().getForm();
// Determine the information about the submission...
SubmissionProfile p = formDef.getSubmissionProfile();
if (p == null || p.getRef() == null) {
return new XPathReference("/");
} else {
return p.getRef();
}
}
/**
* Once a submission is marked as complete, it is saved in the
* submission format, which might be a fragment of the original
* form or might be a SMS text string, etc.
*
* @return true if the submission is the entire form. If it is,
* then the submission can be re-opened for editing
* after it was marked-as-complete (provided it has
* not been encrypted).
*/
public boolean isSubmissionEntireForm() {
IDataReference sub = getSubmissionDataReference();
return ( getInstance().resolveReference(sub) == null );
}
/**
* Constructs the XML payload for a filled-in form instance. This payload
* enables a filled-in form to be re-opened and edited.
*
* @return
* @throws IOException
*/
public ByteArrayPayload getFilledInFormXml() throws IOException {
// assume no binary data inside the model.
FormInstance datamodel = getInstance();
XFormSerializingVisitor serializer = new XFormSerializingVisitor();
ByteArrayPayload payload =
(ByteArrayPayload) serializer.createSerializedPayload(datamodel);
return payload;
}
/**
* Extract the portion of the form that should be uploaded to the server.
*
* @return
* @throws IOException
*/
public ByteArrayPayload getSubmissionXml() throws IOException {
FormInstance instance = getInstance();
XFormSerializingVisitor serializer = new XFormSerializingVisitor();
ByteArrayPayload payload =
(ByteArrayPayload) serializer.createSerializedPayload(instance,
getSubmissionDataReference());
return payload;
}
/**
* Traverse the submission looking for the first matching tag in depth-first order.
*
* @param parent
* @param name
* @return
*/
private TreeElement findDepthFirst(TreeElement parent, String name) {
int len = parent.getNumChildren();
for ( int i = 0; i < len ; ++i ) {
TreeElement e = parent.getChildAt(i);
if ( name.equals(e.getName()) ) {
return e;
} else if ( e.getNumChildren() != 0 ) {
TreeElement v = findDepthFirst(e, name);
if ( v != null ) return v;
}
}
return null;
}
/**
* Get the OpenRosa required metadata of the portion of the form beng submitted
* @return
*/
public InstanceMetadata getSubmissionMetadata() {
FormDef formDef = mFormEntryController.getModel().getForm();
TreeElement rootElement = formDef.getInstance().getRoot();
TreeElement trueSubmissionElement;
// Determine the information about the submission...
SubmissionProfile p = formDef.getSubmissionProfile();
if ( p == null || p.getRef() == null ) {
trueSubmissionElement = rootElement;
} else {
IDataReference ref = p.getRef();
trueSubmissionElement = formDef.getInstance().resolveReference(ref);
// resolveReference returns null if the reference is to the root element...
if ( trueSubmissionElement == null ) {
trueSubmissionElement = rootElement;
}
}
// and find the depth-first meta block in this...
TreeElement e = findDepthFirst(trueSubmissionElement, "meta");
String instanceId = null;
String instanceName = null;
if ( e != null ) {
Vector<TreeElement> v;
// instance id...
v = e.getChildrenWithName(INSTANCE_ID);
if ( v.size() == 1 ) {
StringData sa = (StringData) v.get(0).getValue();
instanceId = (String) sa.getValue();
}
// instance name...
v = e.getChildrenWithName(INSTANCE_NAME);
if ( v.size() == 1 ) {
StringData sa = (StringData) v.get(0).getValue();
instanceName = (String) sa.getValue();
}
}
return new InstanceMetadata(instanceId,instanceName);
}
}
| Java |
/*
* 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.listeners;
import java.util.HashMap;
import android.net.Uri;
/**
* @author Carl Hartung (carlhartung@gmail.com)
*/
public interface InstanceUploaderListener {
void uploadingComplete(HashMap<String, String> result);
void progressUpdate(int progress, int total);
void authRequest(Uri url, HashMap<String, String> doneSoFar);
}
| Java |
/*
* 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.listeners;
/**
* @author Carl Hartung (carlhartung@gmail.com)
*/
public interface FormSavedListener {
void savingComplete(int saveStatus);
}
| Java |
/*
* 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.listeners;
/**
* @author Carl Hartung (carlhartung@gmail.com)
*/
public interface DiskSyncListener {
void SyncComplete(String result);
}
| Java |
/*
* 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.listeners;
/**
* Callback interface invoked upon completion of a DeleteFormsTask
*
* @author norman86@gmail.com
* @author mitchellsundt@gmail.com
*/
public interface DeleteFormsListener {
void deleteComplete(int deletedForms);
}
| Java |
/*
* 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.listeners;
/**
* Callback interface invoked upon the completion of a DeleteInstancesTask
*
* @author norman86@gmail.com
* @author mitchellsundt@gmail.com
*/
public interface DeleteInstancesListener {
void deleteComplete(int deletedInstances);
}
| Java |
/*
* 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.listeners;
import java.util.HashMap;
import org.odk.collect.android.logic.FormDetails;
/**
* @author Carl Hartung (carlhartung@gmail.com)
*/
public interface FormDownloaderListener {
void formsDownloadingComplete(HashMap<FormDetails, String> result);
void progressUpdate(String currentFile, int progress, int total);
}
| Java |
/*
* 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.listeners;
public interface AdvanceToNextListener {
void advance(); //Move on to the next question
} | Java |
/*
* 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.listeners;
import org.odk.collect.android.logic.FormDetails;
import java.util.HashMap;
/**
* @author Carl Hartung (carlhartung@gmail.com)
*/
public interface FormListDownloaderListener {
void formListDownloadingComplete(HashMap<String, FormDetails> value);
}
| Java |
/*
* 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.listeners;
import org.odk.collect.android.tasks.FormLoaderTask;
/**
* @author Carl Hartung (carlhartung@gmail.com)
*/
public interface FormLoaderListener {
void loadingComplete(FormLoaderTask task);
void loadingError(String errorMsg);
}
| Java |
package org.anddev.andengine.sensor.accelerometer;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 16:58:38 - 10.03.2010
*/
public interface IAccelerometerListener {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void onAccelerometerChanged(final AccelerometerData pAccelerometerData);
}
| Java |
package org.anddev.andengine.sensor.accelerometer;
import java.util.Arrays;
import org.anddev.andengine.sensor.BaseSensorData;
import android.hardware.SensorManager;
import android.view.Surface;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 16:50:44 - 10.03.2010
*/
public class AccelerometerData extends BaseSensorData {
// ===========================================================
// Constants
// ===========================================================
private static final IAxisSwap AXISSWAPS[] = new IAxisSwap[4];
static {
AXISSWAPS[Surface.ROTATION_0] = new IAxisSwap() {
@Override
public void swapAxis(final float[] pValues) {
final float x = -pValues[SensorManager.DATA_X];
final float y = pValues[SensorManager.DATA_Y];
pValues[SensorManager.DATA_X] = x;
pValues[SensorManager.DATA_Y] = y;
}
};
AXISSWAPS[Surface.ROTATION_90] = new IAxisSwap() {
@Override
public void swapAxis(final float[] pValues) {
final float x = pValues[SensorManager.DATA_Y];
final float y = pValues[SensorManager.DATA_X];
pValues[SensorManager.DATA_X] = x;
pValues[SensorManager.DATA_Y] = y;
}
};
AXISSWAPS[Surface.ROTATION_180] = new IAxisSwap() {
@Override
public void swapAxis(final float[] pValues) {
final float x = pValues[SensorManager.DATA_X];
final float y = -pValues[SensorManager.DATA_Y];
pValues[SensorManager.DATA_X] = x;
pValues[SensorManager.DATA_Y] = y;
}
};
AXISSWAPS[Surface.ROTATION_270] = new IAxisSwap() {
@Override
public void swapAxis(final float[] pValues) {
final float x = -pValues[SensorManager.DATA_Y];
final float y = -pValues[SensorManager.DATA_X];
pValues[SensorManager.DATA_X] = x;
pValues[SensorManager.DATA_Y] = y;
}
};
}
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
public AccelerometerData(final int pDisplayOrientation) {
super(3, pDisplayOrientation);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public float getX() {
return this.mValues[SensorManager.DATA_X];
}
public float getY() {
return this.mValues[SensorManager.DATA_Y];
}
public float getZ() {
return this.mValues[SensorManager.DATA_Z];
}
public void setX(final float pX) {
this.mValues[SensorManager.DATA_X] = pX;
}
public void setY(final float pY) {
this.mValues[SensorManager.DATA_Y] = pY;
}
public void setZ(final float pZ) {
this.mValues[SensorManager.DATA_Z] = pZ;
}
@Override
public void setValues(final float[] pValues) {
super.setValues(pValues);
AccelerometerData.AXISSWAPS[this.mDisplayRotation].swapAxis(this.mValues);
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public String toString() {
return "Accelerometer: " + Arrays.toString(this.mValues);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
private static interface IAxisSwap {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void swapAxis(final float[] pValues);
}
}
| Java |
package org.anddev.andengine.sensor.accelerometer;
import org.anddev.andengine.sensor.SensorDelay;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:10:34 - 31.10.2010
*/
public class AccelerometerSensorOptions {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
final SensorDelay mSensorDelay;
// ===========================================================
// Constructors
// ===========================================================
public AccelerometerSensorOptions(final SensorDelay pSensorDelay) {
this.mSensorDelay = pSensorDelay;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public SensorDelay getSensorDelay() {
return this.mSensorDelay;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.sensor.orientation;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:30:42 - 25.05.2010
*/
public interface IOrientationListener {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void onOrientationChanged(final OrientationData pOrientationData);
}
| Java |
package org.anddev.andengine.sensor.orientation;
import java.util.Arrays;
import org.anddev.andengine.sensor.BaseSensorData;
import org.anddev.andengine.util.constants.MathConstants;
import android.hardware.SensorManager;
import android.view.Surface;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:30:33 - 25.05.2010
*/
public class OrientationData extends BaseSensorData {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final float[] mAccelerometerValues = new float[3];
private final float[] mMagneticFieldValues = new float[3];
private final float[] mRotationMatrix = new float[16];
private int mMagneticFieldAccuracy;
// ===========================================================
// Constructors
// ===========================================================
public OrientationData(final int pDisplayRotation) {
super(3, pDisplayRotation);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public float getRoll() {
return super.mValues[SensorManager.DATA_Z];
}
public float getPitch() {
return super.mValues[SensorManager.DATA_Y];
}
public float getYaw() {
return super.mValues[SensorManager.DATA_X];
}
@Override
@Deprecated
public void setValues(final float[] pValues) {
super.setValues(pValues);
}
@Override
@Deprecated
public void setAccuracy(final int pAccuracy) {
super.setAccuracy(pAccuracy);
}
public void setAccelerometerValues(final float[] pValues) {
System.arraycopy(pValues, 0, this.mAccelerometerValues, 0, pValues.length);
this.updateOrientation();
}
public void setMagneticFieldValues(final float[] pValues) {
System.arraycopy(pValues, 0, this.mMagneticFieldValues, 0, pValues.length);
this.updateOrientation();
}
private void updateOrientation() {
SensorManager.getRotationMatrix(this.mRotationMatrix, null, this.mAccelerometerValues, this.mMagneticFieldValues);
// TODO Use dont't use identical matrixes in remapCoordinateSystem, due to performance reasons.
switch(this.mDisplayRotation) {
case Surface.ROTATION_0:
/* Nothing. */
break;
case Surface.ROTATION_90:
SensorManager.remapCoordinateSystem(this.mRotationMatrix, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, this.mRotationMatrix);
break;
// case Surface.ROTATION_180:
// SensorManager.remapCoordinateSystem(this.mRotationMatrix, SensorManager.AXIS_?, SensorManager.AXIS_?, this.mRotationMatrix);
// break;
// case Surface.ROTATION_270:
// SensorManager.remapCoordinateSystem(this.mRotationMatrix, SensorManager.AXIS_?, SensorManager.AXIS_?, this.mRotationMatrix);
// break;
}
final float[] values = this.mValues;
SensorManager.getOrientation(this.mRotationMatrix, values);
for(int i = values.length - 1; i >= 0; i--) {
values[i] = values[i] * MathConstants.RAD_TO_DEG;
}
}
public int getAccelerometerAccuracy() {
return this.getAccuracy();
}
public void setAccelerometerAccuracy(final int pAccelerometerAccuracy) {
super.setAccuracy(pAccelerometerAccuracy);
}
public int getMagneticFieldAccuracy() {
return this.mMagneticFieldAccuracy;
}
public void setMagneticFieldAccuracy(final int pMagneticFieldAccuracy) {
this.mMagneticFieldAccuracy = pMagneticFieldAccuracy;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public String toString() {
return "Orientation: " + Arrays.toString(this.mValues);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.sensor.orientation;
import org.anddev.andengine.sensor.SensorDelay;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:12:36 - 31.10.2010
*/
public class OrientationSensorOptions {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
final SensorDelay mSensorDelay;
// ===========================================================
// Constructors
// ===========================================================
public OrientationSensorOptions(final SensorDelay pSensorDelay) {
this.mSensorDelay = pSensorDelay;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public SensorDelay getSensorDelay() {
return this.mSensorDelay;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.sensor.location;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:39:23 - 31.10.2010
*/
public interface ILocationListener {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
/**
* @see {@link LocationListener#onProviderEnabled(String)}
*/
public void onLocationProviderEnabled();
/**
* @see {@link LocationListener#onLocationChanged(Location)}
*/
public void onLocationChanged(final Location pLocation);
public void onLocationLost();
/**
* @see {@link LocationListener#onProviderDisabled(String)}
*/
public void onLocationProviderDisabled();
/**
* @see {@link LocationListener#onStatusChanged(String, int, android.os.Bundle)}
*/
public void onLocationProviderStatusChanged(final LocationProviderStatus pLocationProviderStatus, final Bundle pBundle);
}
| Java |
package org.anddev.andengine.sensor.location;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:55:57 - 31.10.2010
*/
public enum LocationProviderStatus {
// ===========================================================
// Elements
// ===========================================================
AVAILABLE,
OUT_OF_SERVICE,
TEMPORARILY_UNAVAILABLE;
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.sensor.location;
import org.anddev.andengine.util.constants.TimeConstants;
import android.location.Criteria;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:02:12 - 31.10.2010
*/
public class LocationSensorOptions extends Criteria {
// ===========================================================
// Constants
// ===========================================================
private static final long MINIMUMTRIGGERTIME_DEFAULT = 1 * TimeConstants.MILLISECONDSPERSECOND;
private static final long MINIMUMTRIGGERDISTANCE_DEFAULT = 10;
// ===========================================================
// Fields
// ===========================================================
private boolean mEnabledOnly = true;
private long mMinimumTriggerTime = MINIMUMTRIGGERTIME_DEFAULT;
private long mMinimumTriggerDistance = MINIMUMTRIGGERDISTANCE_DEFAULT;
// ===========================================================
// Constructors
// ===========================================================
/**
* @see {@link LocationSensorOptions#setAccuracy(int)},
* {@link LocationSensorOptions#setAltitudeRequired(boolean)},
* {@link LocationSensorOptions#setBearingRequired(boolean)},
* {@link LocationSensorOptions#setCostAllowed(boolean)},
* {@link LocationSensorOptions#setEnabledOnly(boolean)},
* {@link LocationSensorOptions#setMinimumTriggerDistance(long)},
* {@link LocationSensorOptions#setMinimumTriggerTime(long)},
* {@link LocationSensorOptions#setPowerRequirement(int)},
* {@link LocationSensorOptions#setSpeedRequired(boolean)}.
*/
public LocationSensorOptions() {
}
/**
* @param pAccuracy
* @param pAltitudeRequired
* @param pBearingRequired
* @param pCostAllowed
* @param pPowerRequirement
* @param pSpeedRequired
* @param pEnabledOnly
* @param pMinimumTriggerTime
* @param pMinimumTriggerDistance
*/
public LocationSensorOptions(final int pAccuracy, final boolean pAltitudeRequired, final boolean pBearingRequired, final boolean pCostAllowed, final int pPowerRequirement, final boolean pSpeedRequired, final boolean pEnabledOnly, final long pMinimumTriggerTime, final long pMinimumTriggerDistance) {
this.mEnabledOnly = pEnabledOnly;
this.mMinimumTriggerTime = pMinimumTriggerTime;
this.mMinimumTriggerDistance = pMinimumTriggerDistance;
this.setAccuracy(pAccuracy);
this.setAltitudeRequired(pAltitudeRequired);
this.setBearingRequired(pBearingRequired);
this.setCostAllowed(pCostAllowed);
this.setPowerRequirement(pPowerRequirement);
this.setSpeedRequired(pSpeedRequired);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public void setEnabledOnly(final boolean pEnabledOnly) {
this.mEnabledOnly = pEnabledOnly;
}
public boolean isEnabledOnly() {
return this.mEnabledOnly;
}
public long getMinimumTriggerTime() {
return this.mMinimumTriggerTime;
}
public void setMinimumTriggerTime(final long pMinimumTriggerTime) {
this.mMinimumTriggerTime = pMinimumTriggerTime;
}
public long getMinimumTriggerDistance() {
return this.mMinimumTriggerDistance;
}
public void setMinimumTriggerDistance(final long pMinimumTriggerDistance) {
this.mMinimumTriggerDistance = pMinimumTriggerDistance;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.sensor;
import java.util.Arrays;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 16:50:44 - 10.03.2010
*/
public class BaseSensorData {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
protected final float[] mValues;
protected int mAccuracy;
protected int mDisplayRotation;
// ===========================================================
// Constructors
// ===========================================================
public BaseSensorData(final int pValueCount, int pDisplayRotation) {
this.mValues = new float[pValueCount];
this.mDisplayRotation = pDisplayRotation;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public float[] getValues() {
return this.mValues;
}
public void setValues(final float[] pValues) {
System.arraycopy(pValues, 0, this.mValues, 0, pValues.length);
}
public void setAccuracy(final int pAccuracy) {
this.mAccuracy = pAccuracy;
}
public int getAccuracy() {
return this.mAccuracy;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public String toString() {
return "Values: " + Arrays.toString(this.mValues);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.sensor;
import android.hardware.SensorManager;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:14:38 - 31.10.2010
*/
public enum SensorDelay {
// ===========================================================
// Elements
// ===========================================================
NORMAL(SensorManager.SENSOR_DELAY_NORMAL),
UI(SensorManager.SENSOR_DELAY_UI),
GAME(SensorManager.SENSOR_DELAY_GAME),
FASTEST(SensorManager.SENSOR_DELAY_FASTEST);
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final int mDelay;
// ===========================================================
// Constructors
// ===========================================================
private SensorDelay(final int pDelay) {
this.mDelay = pDelay;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public int getDelay() {
return this.mDelay;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.level.util.constants;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 14:23:27 - 11.10.2010
*/
public interface LevelConstants {
// ===========================================================
// Final Fields
// ===========================================================
public static final String TAG_LEVEL = "level";
public static final String TAG_LEVEL_ATTRIBUTE_NAME = "name";
public static final String TAG_LEVEL_ATTRIBUTE_UID = "uid";
public static final String TAG_LEVEL_ATTRIBUTE_WIDTH = "width";
public static final String TAG_LEVEL_ATTRIBUTE_HEIGHT = "height";
// ===========================================================
// Methods
// ===========================================================
}
| Java |
package org.anddev.andengine.level;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.anddev.andengine.level.util.constants.LevelConstants;
import org.anddev.andengine.util.Debug;
import org.anddev.andengine.util.StreamUtils;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import android.content.Context;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 14:16:19 - 11.10.2010
*/
public class LevelLoader implements LevelConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private String mAssetBasePath;
private IEntityLoader mDefaultEntityLoader;
private final HashMap<String, IEntityLoader> mEntityLoaders = new HashMap<String, IEntityLoader>();
// ===========================================================
// Constructors
// ===========================================================
public LevelLoader() {
this("");
}
public LevelLoader(final String pAssetBasePath) {
this.setAssetBasePath(pAssetBasePath);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public IEntityLoader getDefaultEntityLoader() {
return this.mDefaultEntityLoader;
}
public void setDefaultEntityLoader(IEntityLoader pDefaultEntityLoader) {
this.mDefaultEntityLoader = pDefaultEntityLoader;
}
/**
* @param pAssetBasePath must end with '<code>/</code>' or have <code>.length() == 0</code>.
*/
public void setAssetBasePath(final String pAssetBasePath) {
if(pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) {
this.mAssetBasePath = pAssetBasePath;
} else {
throw new IllegalStateException("pAssetBasePath must end with '/' or be lenght zero.");
}
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
protected void onAfterLoadLevel() {
}
protected void onBeforeLoadLevel() {
}
// ===========================================================
// Methods
// ===========================================================
public void registerEntityLoader(final String pEntityName, final IEntityLoader pEntityLoader) {
this.mEntityLoaders.put(pEntityName, pEntityLoader);
}
public void registerEntityLoader(final String[] pEntityNames, final IEntityLoader pEntityLoader) {
final HashMap<String, IEntityLoader> entityLoaders = this.mEntityLoaders;
for(int i = pEntityNames.length - 1; i >= 0; i--) {
entityLoaders.put(pEntityNames[i], pEntityLoader);
}
}
public void loadLevelFromAsset(final Context pContext, final String pAssetPath) throws IOException {
this.loadLevelFromStream(pContext.getAssets().open(this.mAssetBasePath + pAssetPath));
}
public void loadLevelFromResource(final Context pContext, final int pRawResourceID) throws IOException {
this.loadLevelFromStream(pContext.getResources().openRawResource(pRawResourceID));
}
public void loadLevelFromStream(final InputStream pInputStream) throws IOException {
try{
final SAXParserFactory spf = SAXParserFactory.newInstance();
final SAXParser sp = spf.newSAXParser();
final XMLReader xr = sp.getXMLReader();
this.onBeforeLoadLevel();
final LevelParser levelParser = new LevelParser(this.mDefaultEntityLoader, this.mEntityLoaders);
xr.setContentHandler(levelParser);
xr.parse(new InputSource(new BufferedInputStream(pInputStream)));
this.onAfterLoadLevel();
} catch (final SAXException se) {
Debug.e(se);
/* Doesn't happen. */
} catch (final ParserConfigurationException pe) {
Debug.e(pe);
/* Doesn't happen. */
} finally {
StreamUtils.close(pInputStream);
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public static interface IEntityLoader {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void onLoadEntity(final String pEntityName, final Attributes pAttributes);
}
}
| Java |
package org.anddev.andengine.level;
import java.util.HashMap;
import org.anddev.andengine.level.LevelLoader.IEntityLoader;
import org.anddev.andengine.level.util.constants.LevelConstants;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 14:35:32 - 11.10.2010
*/
public class LevelParser extends DefaultHandler implements LevelConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final IEntityLoader mDefaultEntityLoader;
private final HashMap<String, IEntityLoader> mEntityLoaders;
// ===========================================================
// Constructors
// ===========================================================
public LevelParser(final IEntityLoader pDefaultEntityLoader, final HashMap<String, IEntityLoader> pEntityLoaders) {
this.mDefaultEntityLoader = pDefaultEntityLoader;
this.mEntityLoaders = pEntityLoaders;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void startElement(final String pUri, final String pLocalName, final String pQualifiedName, final Attributes pAttributes) throws SAXException {
final IEntityLoader entityLoader = this.mEntityLoaders.get(pLocalName);
if(entityLoader != null) {
entityLoader.onLoadEntity(pLocalName, pAttributes);
} else {
if(this.mDefaultEntityLoader != null) {
this.mDefaultEntityLoader.onLoadEntity(pLocalName, pAttributes);
} else {
throw new IllegalArgumentException("Unexpected tag: '" + pLocalName + "'.");
}
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.pool;
import org.anddev.andengine.entity.IEntity;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 00:53:22 - 28.08.2010
*/
public class EntityDetachRunnablePoolItem extends RunnablePoolItem {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
protected IEntity mEntity;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
public void setEntity(final IEntity pEntity) {
this.mEntity = pEntity;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void run() {
this.mEntity.detachSelf();
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
} | Java |
package org.anddev.andengine.util.pool;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 23:46:50 - 27.08.2010
*/
public abstract class RunnablePoolItem extends PoolItem implements Runnable {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
} | Java |
package org.anddev.andengine.util.pool;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 23:16:25 - 31.08.2010
*/
public class EntityDetachRunnablePoolUpdateHandler extends RunnablePoolUpdateHandler<EntityDetachRunnablePoolItem> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
protected EntityDetachRunnablePoolItem onAllocatePoolItem() {
return new EntityDetachRunnablePoolItem();
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.pool;
/**
* @author Valentin Milea
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
*
* @since 23:00:21 - 21.08.2010
* @param <T>
*/
public abstract class Pool<T extends PoolItem> extends GenericPool<T>{
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
public Pool() {
super();
}
public Pool(final int pInitialSize) {
super(pInitialSize);
}
public Pool(final int pInitialSize, final int pGrowth) {
super(pInitialSize, pGrowth);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
protected T onHandleAllocatePoolItem() {
final T poolItem = super.onHandleAllocatePoolItem();
poolItem.mParent = this;
return poolItem;
}
@Override
protected void onHandleObtainItem(final T pPoolItem) {
pPoolItem.mRecycled = false;
pPoolItem.onObtain();
}
@Override
protected void onHandleRecycleItem(final T pPoolItem) {
pPoolItem.onRecycle();
pPoolItem.mRecycled = true;
}
@Override
public synchronized void recyclePoolItem(final T pPoolItem) {
if(pPoolItem.mParent == null) {
throw new IllegalArgumentException("PoolItem not assigned to a pool!");
} else if(!pPoolItem.isFromPool(this)) {
throw new IllegalArgumentException("PoolItem from another pool!");
} else if(pPoolItem.isRecycled()) {
throw new IllegalArgumentException("PoolItem already recycled!");
}
super.recyclePoolItem(pPoolItem);
}
// ===========================================================
// Methods
// ===========================================================
public synchronized boolean ownsPoolItem(final T pPoolItem) {
return pPoolItem.mParent == this;
}
@SuppressWarnings("unchecked")
void recycle(final PoolItem pPoolItem) {
this.recyclePoolItem((T) pPoolItem);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.pool;
import java.util.ArrayList;
import org.anddev.andengine.engine.handler.IUpdateHandler;
/**
* @author Valentin Milea
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
*
* @since 23:02:58 - 21.08.2010
* @param <T>
*/
public abstract class PoolUpdateHandler<T extends PoolItem> implements IUpdateHandler {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final Pool<T> mPool;
private final ArrayList<T> mScheduledPoolItems = new ArrayList<T>();
// ===========================================================
// Constructors
// ===========================================================
public PoolUpdateHandler() {
this.mPool = new Pool<T>() {
@Override
protected T onAllocatePoolItem() {
return PoolUpdateHandler.this.onAllocatePoolItem();
}
};
}
public PoolUpdateHandler(final int pInitialPoolSize) {
this.mPool = new Pool<T>(pInitialPoolSize) {
@Override
protected T onAllocatePoolItem() {
return PoolUpdateHandler.this.onAllocatePoolItem();
}
};
}
public PoolUpdateHandler(final int pInitialPoolSize, final int pGrowth) {
this.mPool = new Pool<T>(pInitialPoolSize, pGrowth) {
@Override
protected T onAllocatePoolItem() {
return PoolUpdateHandler.this.onAllocatePoolItem();
}
};
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
protected abstract T onAllocatePoolItem();
protected abstract void onHandlePoolItem(final T pPoolItem);
@Override
public void onUpdate(final float pSecondsElapsed) {
final ArrayList<T> scheduledPoolItems = this.mScheduledPoolItems;
synchronized (scheduledPoolItems) {
final int count = scheduledPoolItems.size();
if(count > 0) {
final Pool<T> pool = this.mPool;
T item;
for(int i = 0; i < count; i++) {
item = scheduledPoolItems.get(i);
this.onHandlePoolItem(item);
pool.recyclePoolItem(item);
}
scheduledPoolItems.clear();
}
}
}
@Override
public void reset() {
final ArrayList<T> scheduledPoolItems = this.mScheduledPoolItems;
synchronized (scheduledPoolItems) {
final int count = scheduledPoolItems.size();
final Pool<T> pool = this.mPool;
for(int i = count - 1; i >= 0; i--) {
pool.recyclePoolItem(scheduledPoolItems.get(i));
}
scheduledPoolItems.clear();
}
}
// ===========================================================
// Methods
// ===========================================================
public T obtainPoolItem() {
return this.mPool.obtainPoolItem();
}
public void postPoolItem(final T pPoolItem) {
synchronized (this.mScheduledPoolItems) {
if(pPoolItem == null) {
throw new IllegalArgumentException("PoolItem already recycled!");
} else if(!this.mPool.ownsPoolItem(pPoolItem)) {
throw new IllegalArgumentException("PoolItem from another pool!");
}
this.mScheduledPoolItems.add(pPoolItem);
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.pool;
/**
* @author Valentin Milea
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
*
* @since 23:02:47 - 21.08.2010
*/
public abstract class PoolItem {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
Pool<? extends PoolItem> mParent;
boolean mRecycled = true;
// ===========================================================
// Constructors
// ===========================================================
public Pool<? extends PoolItem> getParent() {
return this.mParent;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public boolean isRecycled() {
return this.mRecycled;
}
public boolean isFromPool(final Pool<? extends PoolItem> pPool) {
return pPool == this.mParent;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
protected void onRecycle() {
}
protected void onObtain() {
}
public void recycle() {
if(this.mParent == null) {
throw new IllegalStateException("Item already recycled!");
}
this.mParent.recycle(this);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
} | Java |
package org.anddev.andengine.util.pool;
import android.util.SparseArray;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:13:26 - 02.03.2011
*/
public class MultiPool<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final SparseArray<GenericPool<T>> mPools = new SparseArray<GenericPool<T>>();
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void registerPool(final int pID, final GenericPool<T> pPool) {
this.mPools.put(pID, pPool);
}
public T obtainPoolItem(final int pID) {
final GenericPool<T> pool = this.mPools.get(pID);
if(pool == null) {
return null;
} else {
return pool.obtainPoolItem();
}
}
public void recyclePoolItem(final int pID, final T pItem) {
final GenericPool<T> pool = this.mPools.get(pID);
if(pool != null) {
pool.recyclePoolItem(pItem);
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.pool;
import java.util.Collections;
import java.util.Stack;
import org.anddev.andengine.util.Debug;
/**
* @author Valentin Milea
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
*
* @since 22:19:55 - 31.08.2010
* @param <T>
*/
public abstract class GenericPool<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final Stack<T> mAvailableItems = new Stack<T>();
private int mUnrecycledCount;
private final int mGrowth;
// ===========================================================
// Constructors
// ===========================================================
public GenericPool() {
this(0);
}
public GenericPool(final int pInitialSize) {
this(pInitialSize, 1);
}
public GenericPool(final int pInitialSize, final int pGrowth) {
if(pGrowth < 0) {
throw new IllegalArgumentException("pGrowth must be at least 0!");
}
this.mGrowth = pGrowth;
if(pInitialSize > 0) {
this.batchAllocatePoolItems(pInitialSize);
}
}
// ===========================================================
// Getter & Setter
// ===========================================================
public synchronized int getUnrecycledCount() {
return this.mUnrecycledCount;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
protected abstract T onAllocatePoolItem();
// ===========================================================
// Methods
// ===========================================================
/**
* @param pItem every item passes this method just before it gets recycled.
*/
protected void onHandleRecycleItem(final T pItem) {
}
protected T onHandleAllocatePoolItem() {
return this.onAllocatePoolItem();
}
/**
* @param pItem every item that was just obtained from the pool, passes this method.
*/
protected void onHandleObtainItem(final T pItem) {
}
public synchronized void batchAllocatePoolItems(final int pCount) {
final Stack<T> availableItems = this.mAvailableItems;
for(int i = pCount - 1; i >= 0; i--) {
availableItems.push(this.onHandleAllocatePoolItem());
}
}
public synchronized T obtainPoolItem() {
final T item;
if(this.mAvailableItems.size() > 0) {
item = this.mAvailableItems.pop();
} else {
if(this.mGrowth == 1) {
item = this.onHandleAllocatePoolItem();
} else {
this.batchAllocatePoolItems(this.mGrowth);
item = this.mAvailableItems.pop();
}
Debug.i(this.getClass().getName() + "<" + item.getClass().getSimpleName() +"> was exhausted, with " + this.mUnrecycledCount + " item not yet recycled. Allocated " + this.mGrowth + " more.");
}
this.onHandleObtainItem(item);
this.mUnrecycledCount++;
return item;
}
public synchronized void recyclePoolItem(final T pItem) {
if(pItem == null) {
throw new IllegalArgumentException("Cannot recycle null item!");
}
this.onHandleRecycleItem(pItem);
this.mAvailableItems.push(pItem);
this.mUnrecycledCount--;
if(this.mUnrecycledCount < 0) {
Debug.e("More items recycled than obtained!");
}
}
public synchronized void shufflePoolItems() {
Collections.shuffle(this.mAvailableItems);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.pool;
/**
* @author Valentin Milea
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
*
* @since 23:03:58 - 21.08.2010
* @param <T>
*/
public abstract class RunnablePoolUpdateHandler<T extends RunnablePoolItem> extends PoolUpdateHandler<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
public RunnablePoolUpdateHandler() {
}
public RunnablePoolUpdateHandler(final int pInitialPoolSize) {
super(pInitialPoolSize);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
protected abstract T onAllocatePoolItem();
@Override
protected void onHandlePoolItem(final T pRunnablePoolItem) {
pRunnablePoolItem.run();
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import android.content.Context;
import android.os.Environment;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 13:53:33 - 20.06.2010
*/
public class FileUtils {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static void copyToExternalStorage(final Context pContext, final int pSourceResourceID, final String pFilename) throws FileNotFoundException {
FileUtils.copyToExternalStorage(pContext, pContext.getResources().openRawResource(pSourceResourceID), pFilename);
}
public static void copyToInternalStorage(final Context pContext, final int pSourceResourceID, final String pFilename) throws FileNotFoundException {
FileUtils.copyToInternalStorage(pContext, pContext.getResources().openRawResource(pSourceResourceID), pFilename);
}
public static void copyToExternalStorage(final Context pContext, final String pSourceAssetPath, final String pFilename) throws IOException {
FileUtils.copyToExternalStorage(pContext, pContext.getAssets().open(pSourceAssetPath), pFilename);
}
public static void copyToInternalStorage(final Context pContext, final String pSourceAssetPath, final String pFilename) throws IOException {
FileUtils.copyToInternalStorage(pContext, pContext.getAssets().open(pSourceAssetPath), pFilename);
}
private static void copyToInternalStorage(final Context pContext, final InputStream pInputStream, final String pFilename) throws FileNotFoundException {
StreamUtils.copyAndClose(pInputStream, new FileOutputStream(new File(pContext.getFilesDir(), pFilename)));
}
public static void copyToExternalStorage(final Context pContext, final InputStream pInputStream, final String pFilePath) throws FileNotFoundException {
if (FileUtils.isExternalStorageWriteable()) {
final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath);
StreamUtils.copyAndClose(pInputStream, new FileOutputStream(absoluteFilePath));
} else {
throw new IllegalStateException("External Storage is not writeable.");
}
}
public static boolean isFileExistingOnExternalStorage(final Context pContext, final String pFilePath) {
if (FileUtils.isExternalStorageReadable()) {
final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath);
final File file = new File(absoluteFilePath);
return file.exists()&& file.isFile();
} else {
throw new IllegalStateException("External Storage is not readable.");
}
}
public static boolean isDirectoryExistingOnExternalStorage(final Context pContext, final String pDirectory) {
if (FileUtils.isExternalStorageReadable()) {
final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pDirectory);
final File file = new File(absoluteFilePath);
return file.exists() && file.isDirectory();
} else {
throw new IllegalStateException("External Storage is not readable.");
}
}
public static boolean ensureDirectoriesExistOnExternalStorage(final Context pContext, final String pDirectory) {
if(FileUtils.isDirectoryExistingOnExternalStorage(pContext, pDirectory)) {
return true;
}
if (FileUtils.isExternalStorageWriteable()) {
final String absoluteDirectoryPath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pDirectory);
return new File(absoluteDirectoryPath).mkdirs();
} else {
throw new IllegalStateException("External Storage is not writeable.");
}
}
public static InputStream openOnExternalStorage(final Context pContext, final String pFilePath) throws FileNotFoundException {
final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath);
return new FileInputStream(absoluteFilePath);
}
public static String[] getDirectoryListOnExternalStorage(final Context pContext, final String pFilePath) throws FileNotFoundException {
final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath);
return new File(absoluteFilePath).list();
}
public static String[] getDirectoryListOnExternalStorage(final Context pContext, final String pFilePath, final FilenameFilter pFilenameFilter) throws FileNotFoundException {
final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath);
return new File(absoluteFilePath).list(pFilenameFilter);
}
public static String getAbsolutePathOnInternalStorage(final Context pContext, final String pFilePath) {
return pContext.getFilesDir().getAbsolutePath() + pFilePath;
}
public static String getAbsolutePathOnExternalStorage(final Context pContext, final String pFilePath) {
return Environment.getExternalStorageDirectory() + "/Android/data/" + pContext.getApplicationInfo().packageName + "/files/" + pFilePath;
}
public static boolean isExternalStorageWriteable() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
public static boolean isExternalStorageReadable() {
final String state = Environment.getExternalStorageState();
return state.equals(Environment.MEDIA_MOUNTED) || state.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
}
public static void copyFile(final File pIn, final File pOut) throws IOException {
final FileInputStream fis = new FileInputStream(pIn);
final FileOutputStream fos = new FileOutputStream(pOut);
try {
StreamUtils.copy(fis, fos);
} finally {
StreamUtils.close(fis);
StreamUtils.close(fos);
}
}
/**
* Deletes all files and sub-directories under <code>dir</code>. Returns
* true if all deletions were successful. If a deletion fails, the method
* stops attempting to delete and returns false.
*
* @param pFileOrDirectory
* @return
*/
public static boolean deleteDirectory(final File pFileOrDirectory) {
if(pFileOrDirectory.isDirectory()) {
final String[] children = pFileOrDirectory.list();
final int childrenCount = children.length;
for(int i = 0; i < childrenCount; i++) {
final boolean success = FileUtils.deleteDirectory(new File(pFileOrDirectory, children[i]));
if(!success) {
return false;
}
}
}
// The directory is now empty so delete it
return pFileOrDirectory.delete();
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util;
import org.anddev.andengine.util.constants.Constants;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 18:55:12 - 02.08.2010
*/
public class SimplePreferences implements Constants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static SharedPreferences INSTANCE;
private static Editor EDITORINSTANCE;
// ===========================================================
// Constructors
// ===========================================================
public static SharedPreferences getInstance(final Context pContext) {
if(SimplePreferences.INSTANCE == null) {
SimplePreferences.INSTANCE = PreferenceManager.getDefaultSharedPreferences(pContext);
}
return SimplePreferences.INSTANCE;
}
public static Editor getEditorInstance(final Context pContext) {
if(SimplePreferences.EDITORINSTANCE == null) {
SimplePreferences.EDITORINSTANCE = SimplePreferences.getInstance(pContext).edit();
}
return SimplePreferences.EDITORINSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static int incrementAccessCount(final Context pContext, final String pKey) {
return SimplePreferences.incrementAccessCount(pContext, pKey, 1);
}
public static int incrementAccessCount(final Context pContext, final String pKey, final int pIncrement) {
final SharedPreferences prefs = SimplePreferences.getInstance(pContext);
final int accessCount = prefs.getInt(pKey, 0);
final int newAccessCount = accessCount + pIncrement;
prefs.edit().putInt(pKey, newAccessCount).commit();
return newAccessCount;
}
public static int getAccessCount(final Context pCtx, final String pKey) {
return SimplePreferences.getInstance(pCtx).getInt(pKey, 0);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util;
import java.util.ArrayList;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 22:20:08 - 27.12.2010
*/
public class SmartList<T> extends ArrayList<T> {
// ===========================================================
// Constants
// ===========================================================
private static final long serialVersionUID = -8335986399182700102L;
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
public SmartList() {
}
public SmartList(final int pCapacity) {
super(pCapacity);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
/**
* @param pItem the item to remove.
* @param pParameterCallable to be called with the removed item, if it was removed.
*/
public boolean remove(final T pItem, final ParameterCallable<T> pParameterCallable) {
final boolean removed = this.remove(pItem);
if(removed) {
pParameterCallable.call(pItem);
}
return removed;
}
public T remove(final IMatcher<T> pMatcher) {
for(int i = 0; i < this.size(); i++) {
if(pMatcher.matches(this.get(i))) {
return this.remove(i);
}
}
return null;
}
public T remove(final IMatcher<T> pMatcher, final ParameterCallable<T> pParameterCallable) {
for(int i = this.size() - 1; i >= 0; i--) {
if(pMatcher.matches(this.get(i))) {
final T removed = this.remove(i);
pParameterCallable.call(removed);
return removed;
}
}
return null;
}
public boolean removeAll(final IMatcher<T> pMatcher) {
boolean result = false;
for(int i = this.size() - 1; i >= 0; i--) {
if(pMatcher.matches(this.get(i))) {
this.remove(i);
result = true;
}
}
return result;
}
/**
* @param pMatcher to find the items.
* @param pParameterCallable to be called with each matched item after it was removed.
*/
public boolean removeAll(final IMatcher<T> pMatcher, final ParameterCallable<T> pParameterCallable) {
boolean result = false;
for(int i = this.size() - 1; i >= 0; i--) {
if(pMatcher.matches(this.get(i))) {
final T removed = this.remove(i);
pParameterCallable.call(removed);
result = true;
}
}
return result;
}
public void clear(final ParameterCallable<T> pParameterCallable) {
for(int i = this.size() - 1; i >= 0; i--) {
final T removed = this.remove(i);
pParameterCallable.call(removed);
}
}
public T find(final IMatcher<T> pMatcher) {
for(int i = this.size() - 1; i >= 0; i--) {
final T item = this.get(i);
if(pMatcher.matches(item)) {
return item;
}
}
return null;
}
public void call(final ParameterCallable<T> pParameterCallable) {
for(int i = this.size() - 1; i >= 0; i--) {
final T item = this.get(i);
pParameterCallable.call(item);
}
}
public void call(final IMatcher<T> pMatcher, final ParameterCallable<T> pParameterCallable) {
for(int i = this.size() - 1; i >= 0; i--) {
final T item = this.get(i);
if(pMatcher.matches(item)) {
pParameterCallable.call(item);
}
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 20:55:35 - 08.09.2009
*/
public class ViewUtils {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static View inflate(final Context pContext, final int pLayoutID){
return LayoutInflater.from(pContext).inflate(pLayoutID, null);
}
public static View inflate(final Context pContext, final int pLayoutID, final ViewGroup pViewGroup){
return LayoutInflater.from(pContext).inflate(pLayoutID, pViewGroup, true);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 15:15:23 - 24.07.2010
*/
public enum VerticalAlign {
// ===========================================================
// Elements
// ===========================================================
TOP,
CENTER,
BOTTOM;
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.sort;
import java.util.Comparator;
import java.util.List;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 14:14:31 - 06.08.2010
* @param <T>
*/
public class InsertionSorter<T> extends Sorter<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void sort(final T[] pArray, final int pStart, final int pEnd, final Comparator<T> pComparator) {
for(int i = pStart + 1; i < pEnd; i++) {
final T current = pArray[i];
T prev = pArray[i - 1];
if(pComparator.compare(current, prev) < 0) {
int j = i;
do {
pArray[j--] = prev;
} while(j > pStart && pComparator.compare(current, prev = pArray[j - 1]) < 0);
pArray[j] = current;
}
}
return;
}
@Override
public void sort(final List<T> pList, final int pStart, final int pEnd, final Comparator<T> pComparator) {
for(int i = pStart + 1; i < pEnd; i++) {
final T current = pList.get(i);
T prev = pList.get(i - 1);
if(pComparator.compare(current, prev) < 0) {
int j = i;
do {
pList.set(j--, prev);
} while(j > pStart && pComparator.compare(current, prev = pList.get(j - 1)) < 0);
pList.set(j, current);
}
}
return;
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
} | Java |
package org.anddev.andengine.util.sort;
import java.util.Comparator;
import java.util.List;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 14:14:39 - 06.08.2010
* @param <T>
*/
public abstract class Sorter<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
public abstract void sort(final T[] pArray, final int pStart, final int pEnd, final Comparator<T> pComparator);
public abstract void sort(final List<T> pList, final int pStart, final int pEnd, final Comparator<T> pComparator);
// ===========================================================
// Methods
// ===========================================================
public final void sort(final T[] pArray, final Comparator<T> pComparator){
this.sort(pArray, 0, pArray.length, pComparator);
}
public final void sort(final List<T> pList, final Comparator<T> pComparator){
this.sort(pList, 0, pList.size(), pComparator);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:47:33 - 11.05.2010
*/
public enum HorizontalAlign {
// ===========================================================
// Elements
// ===========================================================
LEFT,
CENTER,
RIGHT;
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util;
import java.util.concurrent.Callable;
import org.anddev.andengine.ui.activity.BaseActivity.CancelledException;
import org.anddev.andengine.util.progress.IProgressListener;
import org.anddev.andengine.util.progress.ProgressCallable;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.view.Window;
import android.view.WindowManager;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 18:11:54 - 07.03.2011
*/
public class ActivityUtils {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static void requestFullscreen(final Activity pActivity) {
final Window window = pActivity.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
window.requestFeature(Window.FEATURE_NO_TITLE);
}
/**
* @param pActivity
* @param pScreenBrightness [0..1]
*/
public static void setScreenBrightness(final Activity pActivity, final float pScreenBrightness) {
final Window window = pActivity.getWindow();
final WindowManager.LayoutParams windowLayoutParams = window.getAttributes();
windowLayoutParams.screenBrightness = pScreenBrightness;
window.setAttributes(windowLayoutParams);
}
public static void keepScreenOn(final Activity pActivity) {
pActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
public static <T> void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final Callable<T> pCallable, final Callback<T> pCallback) {
ActivityUtils.doAsync(pContext, pTitleResID, pMessageResID, pCallable, pCallback, null, false);
}
public static <T> void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable<T> pCallable, final Callback<T> pCallback) {
ActivityUtils.doAsync(pContext, pTitle, pMessage, pCallable, pCallback, null, false);
}
public static <T> void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final Callable<T> pCallable, final Callback<T> pCallback, final boolean pCancelable) {
ActivityUtils.doAsync(pContext, pTitleResID, pMessageResID, pCallable, pCallback, null, pCancelable);
}
public static <T> void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable<T> pCallable, final Callback<T> pCallback, final boolean pCancelable) {
ActivityUtils.doAsync(pContext, pTitle, pMessage, pCallable, pCallback, null, pCancelable);
}
public static <T> void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final Callable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) {
ActivityUtils.doAsync(pContext, pTitleResID, pMessageResID, pCallable, pCallback, pExceptionCallback, false);
}
public static <T> void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) {
ActivityUtils.doAsync(pContext, pTitle, pMessage, pCallable, pCallback, pExceptionCallback, false);
}
public static <T> void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final Callable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback, final boolean pCancelable) {
ActivityUtils.doAsync(pContext, pContext.getString(pTitleResID), pContext.getString(pMessageResID), pCallable, pCallback, pExceptionCallback, pCancelable);
}
public static <T> void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback, final boolean pCancelable) {
new AsyncTask<Void, Void, T>() {
private ProgressDialog mPD;
private Exception mException = null;
@Override
public void onPreExecute() {
this.mPD = ProgressDialog.show(pContext, pTitle, pMessage, true, pCancelable);
if(pCancelable) {
this.mPD.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(final DialogInterface pDialogInterface) {
pExceptionCallback.onCallback(new CancelledException());
pDialogInterface.dismiss();
}
});
}
super.onPreExecute();
}
@Override
public T doInBackground(final Void... params) {
try {
return pCallable.call();
} catch (final Exception e) {
this.mException = e;
}
return null;
}
@Override
public void onPostExecute(final T result) {
try {
this.mPD.dismiss();
} catch (final Exception e) {
Debug.e("Error", e);
}
if(this.isCancelled()) {
this.mException = new CancelledException();
}
if(this.mException == null) {
pCallback.onCallback(result);
} else {
if(pExceptionCallback == null) {
Debug.e("Error", this.mException);
} else {
pExceptionCallback.onCallback(this.mException);
}
}
super.onPostExecute(result);
}
}.execute((Void[]) null);
}
public static <T> void doProgressAsync(final Context pContext, final int pTitleResID, final ProgressCallable<T> pCallable, final Callback<T> pCallback) {
ActivityUtils.doProgressAsync(pContext, pTitleResID, pCallable, pCallback, null);
}
public static <T> void doProgressAsync(final Context pContext, final int pTitleResID, final ProgressCallable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) {
new AsyncTask<Void, Integer, T>() {
private ProgressDialog mPD;
private Exception mException = null;
@Override
public void onPreExecute() {
this.mPD = new ProgressDialog(pContext);
this.mPD.setTitle(pTitleResID);
this.mPD.setIcon(android.R.drawable.ic_menu_save);
this.mPD.setIndeterminate(false);
this.mPD.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
this.mPD.show();
super.onPreExecute();
}
@Override
public T doInBackground(final Void... params) {
try {
return pCallable.call(new IProgressListener() {
@Override
public void onProgressChanged(final int pProgress) {
onProgressUpdate(pProgress);
}
});
} catch (final Exception e) {
this.mException = e;
}
return null;
}
@Override
public void onProgressUpdate(final Integer... values) {
this.mPD.setProgress(values[0]);
}
@Override
public void onPostExecute(final T result) {
try {
this.mPD.dismiss();
} catch (final Exception e) {
Debug.e("Error", e);
/* Nothing. */
}
if(this.isCancelled()) {
this.mException = new CancelledException();
}
if(this.mException == null) {
pCallback.onCallback(result);
} else {
if(pExceptionCallback == null) {
Debug.e("Error", this.mException);
} else {
pExceptionCallback.onCallback(this.mException);
}
}
super.onPostExecute(result);
}
}.execute((Void[]) null);
}
public static <T> void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final AsyncCallable<T> pAsyncCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) {
final ProgressDialog pd = ProgressDialog.show(pContext, pContext.getString(pTitleResID), pContext.getString(pMessageResID));
pAsyncCallable.call(new Callback<T>() {
@Override
public void onCallback(final T result) {
try {
pd.dismiss();
} catch (final Exception e) {
Debug.e("Error", e);
/* Nothing. */
}
pCallback.onCallback(result);
}
}, pExceptionCallback);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.path;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 23:00:24 - 16.08.2010
*/
public interface ITiledMap<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
public int getTileColumns();
public int getTileRows();
public void onTileVisitedByPathFinder(final int pTileColumn, int pTileRow);
public boolean isTileBlocked(final T pEntity, final int pTileColumn, final int pTileRow);
public float getStepCost(final T pEntity, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow);
}
| Java |
package org.anddev.andengine.util.path;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 15:19:11 - 17.08.2010
*/
public enum Direction {
// ===========================================================
// Elements
// ===========================================================
UP(0, -1), DOWN(0, 1), LEFT(-1, 0), RIGHT(1, 0);
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final int mDeltaX;
private final int mDeltaY;
// ===========================================================
// Constructors
// ===========================================================
private Direction(final int pDeltaX, final int pDeltaY) {
this.mDeltaX = pDeltaX;
this.mDeltaY = pDeltaY;
}
public static Direction fromDelta(final int pDeltaX, final int pDeltaY) {
if(pDeltaX == 0) {
if(pDeltaY == 1) {
return DOWN;
} else if(pDeltaY == -1) {
return UP;
}
} else if (pDeltaY == 0) {
if(pDeltaX == 1) {
return RIGHT;
} else if(pDeltaX == -1) {
return LEFT;
}
}
throw new IllegalArgumentException();
}
// ===========================================================
// Getter & Setter
// ===========================================================
public int getDeltaX() {
return this.mDeltaX;
}
public int getDeltaY() {
return this.mDeltaY;
}
// ===========================================================
// Methods from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.path;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 22:57:13 - 16.08.2010
*/
public interface IPathFinder<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
public Path findPath(final T pEntity, final int pMaxCost, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow);
}
| Java |
package org.anddev.andengine.util.path.astar;
import org.anddev.andengine.util.path.ITiledMap;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 22:58:01 - 16.08.2010
*/
public class ManhattanHeuristic<T> implements IAStarHeuristic<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getExpectedRestCost(final ITiledMap<T> pTiledMap, final T pEntity, final int pTileFromX, final int pTileFromY, final int pTileToX, final int pTileToY) {
return Math.abs(pTileFromX - pTileToX) + Math.abs(pTileToX - pTileToY);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.path.astar;
import org.anddev.andengine.util.path.ITiledMap;
import android.util.FloatMath;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 22:58:01 - 16.08.2010
*/
public class EuclideanHeuristic<T> implements IAStarHeuristic<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getExpectedRestCost(final ITiledMap<T> pTileMap, final T pEntity, final int pTileFromX, final int pTileFromY, final int pTileToX, final int pTileToY) {
final float dX = pTileToX - pTileFromX;
final float dY = pTileToY - pTileFromY;
return FloatMath.sqrt(dX * dX + dY * dY);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.path.astar;
import org.anddev.andengine.util.path.ITiledMap;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 22:58:01 - 16.08.2010
*/
public class NullHeuristic<T> implements IAStarHeuristic<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getExpectedRestCost(final ITiledMap<T> pTiledMap, final T pEntity, final int pTileFromX, final int pTileFromY, final int pTileToX, final int pTileToY) {
return 0;
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.path.astar;
import org.anddev.andengine.util.path.ITiledMap;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 22:59:20 - 16.08.2010
*/
public interface IAStarHeuristic<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
public float getExpectedRestCost(final ITiledMap<T> pTiledMap, final T pEntity, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow);
}
| Java |
package org.anddev.andengine.util.path.astar;
import java.util.ArrayList;
import java.util.Collections;
import org.anddev.andengine.util.path.IPathFinder;
import org.anddev.andengine.util.path.ITiledMap;
import org.anddev.andengine.util.path.Path;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 23:16:17 - 16.08.2010
*/
public class AStarPathFinder<T> implements IPathFinder<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final ArrayList<Node> mVisitedNodes = new ArrayList<Node>();
private final ArrayList<Node> mOpenNodes = new ArrayList<Node>();
private final ITiledMap<T> mTiledMap;
private final int mMaxSearchDepth;
private final Node[][] mNodes;
private final boolean mAllowDiagonalMovement;
private final IAStarHeuristic<T> mAStarHeuristic;
// ===========================================================
// Constructors
// ===========================================================
public AStarPathFinder(final ITiledMap<T> pTiledMap, final int pMaxSearchDepth, final boolean pAllowDiagonalMovement) {
this(pTiledMap, pMaxSearchDepth, pAllowDiagonalMovement, new EuclideanHeuristic<T>());
}
public AStarPathFinder(final ITiledMap<T> pTiledMap, final int pMaxSearchDepth, final boolean pAllowDiagonalMovement, final IAStarHeuristic<T> pAStarHeuristic) {
this.mAStarHeuristic = pAStarHeuristic;
this.mTiledMap = pTiledMap;
this.mMaxSearchDepth = pMaxSearchDepth;
this.mAllowDiagonalMovement = pAllowDiagonalMovement;
this.mNodes = new Node[pTiledMap.getTileRows()][pTiledMap.getTileColumns()];
final Node[][] nodes = this.mNodes;
for(int x = pTiledMap.getTileColumns() - 1; x >= 0; x--) {
for(int y = pTiledMap.getTileRows() - 1; y >= 0; y--) {
nodes[y][x] = new Node(x, y);
}
}
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public Path findPath(final T pEntity, final int pMaxCost, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow) {
final ITiledMap<T> tiledMap = this.mTiledMap;
if(tiledMap.isTileBlocked(pEntity, pToTileColumn, pToTileRow)) {
return null;
}
/* Drag some fields to local variables. */
final ArrayList<Node> openNodes = this.mOpenNodes;
final ArrayList<Node> visitedNodes = this.mVisitedNodes;
final Node[][] nodes = this.mNodes;
final Node fromNode = nodes[pFromTileRow][pFromTileColumn];
final Node toNode = nodes[pToTileRow][pToTileColumn];
final IAStarHeuristic<T> aStarHeuristic = this.mAStarHeuristic;
final boolean allowDiagonalMovement = this.mAllowDiagonalMovement;
final int maxSearchDepth = this.mMaxSearchDepth;
/* Initialize algorithm. */
fromNode.mCost = 0;
fromNode.mDepth = 0;
toNode.mParent = null;
visitedNodes.clear();
openNodes.clear();
openNodes.add(fromNode);
int currentDepth = 0;
while(currentDepth < maxSearchDepth && !openNodes.isEmpty()) {
/* The first Node in the open list is the one with the lowest cost. */
final Node current = openNodes.remove(0);
if(current == toNode) {
break;
}
visitedNodes.add(current);
/* Loop over all neighbors of this tile. */
for(int dX = -1; dX <= 1; dX++) {
for(int dY = -1; dY <= 1; dY++) {
if((dX == 0) && (dY == 0)) {
continue;
}
if(!allowDiagonalMovement) {
if((dX != 0) && (dY != 0)) {
continue;
}
}
final int neighborTileColumn = dX + current.mTileColumn;
final int neighborTileRow = dY + current.mTileRow;
if(!this.isTileBlocked(pEntity, pFromTileColumn, pFromTileRow, neighborTileColumn, neighborTileRow)) {
final float neighborCost = current.mCost + tiledMap.getStepCost(pEntity, current.mTileColumn, current.mTileRow, neighborTileColumn, neighborTileRow);
final Node neighbor = nodes[neighborTileRow][neighborTileColumn];
tiledMap.onTileVisitedByPathFinder(neighborTileColumn, neighborTileRow);
/* Re-evaluate if there is a better path. */
if(neighborCost < neighbor.mCost) {
// TODO Is this ever possible with AStar ??
if(openNodes.contains(neighbor)) {
openNodes.remove(neighbor);
}
if(visitedNodes.contains(neighbor)) {
visitedNodes.remove(neighbor);
}
}
if(!openNodes.contains(neighbor) && !(visitedNodes.contains(neighbor))) {
neighbor.mCost = neighborCost;
if(neighbor.mCost <= pMaxCost) {
neighbor.mExpectedRestCost = aStarHeuristic.getExpectedRestCost(tiledMap, pEntity, neighborTileColumn, neighborTileRow, pToTileColumn, pToTileRow);
currentDepth = Math.max(currentDepth, neighbor.setParent(current));
openNodes.add(neighbor);
/* Ensure always the node with the lowest cost+heuristic
* will be used next, simply by sorting. */
Collections.sort(openNodes);
}
}
}
}
}
}
/* Check if a path was found. */
if(toNode.mParent == null) {
return null;
}
/* Traceback path. */
final Path path = new Path();
Node tmp = nodes[pToTileRow][pToTileColumn];
while(tmp != fromNode) {
path.prepend(tmp.mTileColumn, tmp.mTileRow);
tmp = tmp.mParent;
}
path.prepend(pFromTileColumn, pFromTileRow);
return path;
}
// ===========================================================
// Methods
// ===========================================================
protected boolean isTileBlocked(final T pEntity, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow) {
if((pToTileColumn < 0) || (pToTileRow < 0) || (pToTileColumn >= this.mTiledMap.getTileColumns()) || (pToTileRow >= this.mTiledMap.getTileRows())) {
return true;
} else if((pFromTileColumn == pToTileColumn) && (pFromTileRow == pToTileRow)) {
return true;
}
return this.mTiledMap.isTileBlocked(pEntity, pToTileColumn, pToTileRow);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
private static class Node implements Comparable<Node> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
Node mParent;
int mDepth;
final int mTileColumn;
final int mTileRow;
float mCost;
float mExpectedRestCost;
// ===========================================================
// Constructors
// ===========================================================
public Node(final int pTileColumn, final int pTileRow) {
this.mTileColumn = pTileColumn;
this.mTileRow = pTileRow;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public int setParent(final Node parent) {
this.mDepth = parent.mDepth + 1;
this.mParent = parent;
return this.mDepth;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public int compareTo(final Node pOther) {
final float totalCost = this.mExpectedRestCost + this.mCost;
final float totalCostOther = pOther.mExpectedRestCost + pOther.mCost;
if (totalCost < totalCostOther) {
return -1;
} else if (totalCost > totalCostOther) {
return 1;
} else {
return 0;
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
}
| Java |
package org.anddev.andengine.util.path;
import java.util.ArrayList;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 23:00:24 - 16.08.2010
*/
public class Path {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final ArrayList<Step> mSteps = new ArrayList<Step>();
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
public int getLength() {
return this.mSteps.size();
}
public Step getStep(final int pIndex) {
return this.mSteps.get(pIndex);
}
public Direction getDirectionToPreviousStep(final int pIndex) {
if(pIndex == 0) {
return null;
} else {
final int dX = this.getTileColumn(pIndex - 1) - this.getTileColumn(pIndex);
final int dY = this.getTileRow(pIndex - 1) - this.getTileRow(pIndex);
return Direction.fromDelta(dX, dY);
}
}
public Direction getDirectionToNextStep(final int pIndex) {
if(pIndex == this.getLength() - 1) {
return null;
} else {
final int dX = this.getTileColumn(pIndex + 1) - this.getTileColumn(pIndex);
final int dY = this.getTileRow(pIndex + 1) - this.getTileRow(pIndex);
return Direction.fromDelta(dX, dY);
}
}
public int getTileColumn(final int pIndex) {
return this.getStep(pIndex).getTileColumn();
}
public int getTileRow(final int pIndex) {
return this.getStep(pIndex).getTileRow();
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void append(final int pTileColumn, final int pTileRow) {
this.append(new Step(pTileColumn, pTileRow));
}
public void append(final Step pStep) {
this.mSteps.add(pStep);
}
public void prepend(final int pTileColumn, final int pTileRow) {
this.prepend(new Step(pTileColumn, pTileRow));
}
public void prepend(final Step pStep) {
this.mSteps.add(0, pStep);
}
public boolean contains(final int pTileColumn, final int pTileRow) {
final ArrayList<Step> steps = this.mSteps;
for(int i = steps.size() - 1; i >= 0; i--) {
final Step step = steps.get(i);
if(step.getTileColumn() == pTileColumn && step.getTileRow() == pTileRow) {
return true;
}
}
return false;
}
public int getFromTileRow() {
return this.getTileRow(0);
}
public int getFromTileColumn() {
return this.getTileColumn(0);
}
public int getToTileRow() {
return this.getTileRow(this.mSteps.size() - 1);
}
public int getToTileColumn() {
return this.getTileColumn(this.mSteps.size() - 1);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public class Step {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final int mTileColumn;
private final int mTileRow;
// ===========================================================
// Constructors
// ===========================================================
public Step(final int pTileColumn, final int pTileRow) {
this.mTileColumn = pTileColumn;
this.mTileRow = pTileRow;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public int getTileColumn() {
return this.mTileColumn;
}
public int getTileRow() {
return this.mTileRow;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public int hashCode() {
return this.mTileColumn << 16 + this.mTileRow;
}
@Override
public boolean equals(final Object pOther) {
if(this == pOther) {
return true;
}
if(pOther == null) {
return false;
}
if(this.getClass() != pOther.getClass()) {
return false;
}
final Step other = (Step) pOther;
if(this.mTileColumn != other.mTileColumn) {
return false;
}
if(this.mTileRow != other.mTileRow) {
return false;
}
return true;
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
}
| Java |
package org.anddev.andengine.util;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.util.Scanner;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 15:48:56 - 03.09.2009
*/
public class StreamUtils {
// ===========================================================
// Constants
// ===========================================================
public static final int IO_BUFFER_SIZE = 8 * 1024;
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static final String readFully(final InputStream pInputStream) throws IOException {
final StringBuilder sb = new StringBuilder();
final Scanner sc = new Scanner(pInputStream);
while(sc.hasNextLine()) {
sb.append(sc.nextLine());
}
return sb.toString();
}
public static byte[] streamToBytes(final InputStream pInputStream) throws IOException {
return StreamUtils.streamToBytes(pInputStream, -1);
}
public static byte[] streamToBytes(final InputStream pInputStream, final int pReadLimit) throws IOException {
final ByteArrayOutputStream os = new ByteArrayOutputStream((pReadLimit == -1) ? IO_BUFFER_SIZE : pReadLimit);
StreamUtils.copy(pInputStream, os, pReadLimit);
return os.toByteArray();
}
public static void copy(final InputStream pInputStream, final OutputStream pOutputStream) throws IOException {
StreamUtils.copy(pInputStream, pOutputStream, -1);
}
public static void copy(final InputStream pInputStream, final byte[] pData) throws IOException {
int dataOffset = 0;
final byte[] buf = new byte[IO_BUFFER_SIZE];
int read;
while((read = pInputStream.read(buf)) != -1) {
System.arraycopy(buf, 0, pData, dataOffset, read);
dataOffset += read;
}
}
public static void copy(final InputStream pInputStream, final ByteBuffer pByteBuffer) throws IOException {
final byte[] buf = new byte[IO_BUFFER_SIZE];
int read;
while((read = pInputStream.read(buf)) != -1) {
pByteBuffer.put(buf, 0, read);
}
}
/**
* Copy the content of the input stream into the output stream, using a temporary
* byte array buffer whose size is defined by {@link #IO_BUFFER_SIZE}.
*
* @param pInputStream The input stream to copy from.
* @param pOutputStream The output stream to copy to.
* @param pByteLimit not more than so much bytes to read, or unlimited if smaller than 0.
*
* @throws IOException If any error occurs during the copy.
*/
public static void copy(final InputStream pInputStream, final OutputStream pOutputStream, final long pByteLimit) throws IOException {
if(pByteLimit < 0) {
final byte[] buf = new byte[IO_BUFFER_SIZE];
int read;
while((read = pInputStream.read(buf)) != -1) {
pOutputStream.write(buf, 0, read);
}
} else {
final byte[] buf = new byte[IO_BUFFER_SIZE];
final int bufferReadLimit = Math.min((int)pByteLimit, IO_BUFFER_SIZE);
long pBytesLeftToRead = pByteLimit;
int read;
while((read = pInputStream.read(buf, 0, bufferReadLimit)) != -1) {
if(pBytesLeftToRead > read) {
pOutputStream.write(buf, 0, read);
pBytesLeftToRead -= read;
} else {
pOutputStream.write(buf, 0, (int) pBytesLeftToRead);
break;
}
}
}
pOutputStream.flush();
}
public static boolean copyAndClose(final InputStream pInputStream, final OutputStream pOutputStream) {
try {
StreamUtils.copy(pInputStream, pOutputStream, -1);
return true;
} catch (final IOException e) {
return false;
} finally {
StreamUtils.close(pInputStream);
StreamUtils.close(pOutputStream);
}
}
/**
* Closes the specified stream.
*
* @param pCloseable The stream to close.
*/
public static void close(final Closeable pCloseable) {
if(pCloseable != null) {
try {
pCloseable.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
}
/**
* Flushes and closes the specified stream.
*
* @param pOutputStream The stream to close.
*/
public static void flushCloseStream(final OutputStream pOutputStream) {
if(pOutputStream != null) {
try {
pOutputStream.flush();
} catch (final IOException e) {
e.printStackTrace();
} finally {
StreamUtils.close(pOutputStream);
}
}
}
/**
* Flushes and closes the specified stream.
*
* @param pWriter The Writer to close.
*/
public static void flushCloseWriter(final Writer pWriter) {
if(pWriter != null) {
try {
pWriter.flush();
} catch (final IOException e) {
e.printStackTrace();
} finally {
StreamUtils.close(pWriter);
}
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util;
import android.util.FloatMath;
/**
* <p>This class is basically a java-space replacement for the native {@link android.graphics.Matrix} class.</p>
*
* <p>Math taken from <a href="http://www.senocular.com/flash/tutorials/transformmatrix/">senocular.com</a>.</p>
*
* This class represents an affine transformation with the following matrix:
* <pre> [ a , b , 0 ]
* [ c , d , 0 ]
* [ tx, ty, 1 ]</pre>
* where:
* <ul>
* <li><b>a</b> is the <b>x scale</b></li>
* <li><b>b</b> is the <b>y skew</b></li>
* <li><b>c</b> is the <b>x skew</b></li>
* <li><b>d</b> is the <b>y scale</b></li>
* <li><b>tx</b> is the <b>x translation</b></li>
* <li><b>ty</b> is the <b>y translation</b></li>
* </ul>
*
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 15:47:18 - 23.12.2010
*/
public class Transformation {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private float a = 1.0f; /* x scale */
private float b = 0.0f; /* y skew */
private float c = 0.0f; /* x skew */
private float d = 1.0f; /* y scale */
private float tx = 0.0f; /* x translation */
private float ty = 0.0f; /* y translation */
// ===========================================================
// Constructors
// ===========================================================
public Transformation() {
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public String toString() {
return "Transformation{[" + this.a + ", " + this.c + ", " + this.tx + "][" + this.b + ", " + this.d + ", " + this.ty + "][0.0, 0.0, 1.0]}";
}
// ===========================================================
// Methods
// ===========================================================
public void reset() {
this.setToIdentity();
}
public void setToIdentity() {
this.a = 1.0f;
this.d = 1.0f;
this.b = 0.0f;
this.c = 0.0f;
this.tx = 0.0f;
this.ty = 0.0f;
}
public void setTo(final Transformation pTransformation) {
this.a = pTransformation.a;
this.d = pTransformation.d;
this.b = pTransformation.b;
this.c = pTransformation.c;
this.tx = pTransformation.tx;
this.ty = pTransformation.ty;
}
public void preTranslate(final float pX, final float pY) {
this.tx += pX * this.a + pY * this.c;
this.ty += pX * this.b + pY * this.d;
}
public void postTranslate(final float pX, final float pY) {
this.tx += pX;
this.ty += pY;
}
public Transformation setToTranslate(final float pX, final float pY) {
this.a = 1.0f;
this.b = 0.0f;
this.c = 0.0f;
this.d = 1.0f;
this.tx = pX;
this.ty = pY;
return this;
}
public void preScale(final float pScaleX, final float pScaleY) {
this.a *= pScaleX;
this.b *= pScaleX;
this.c *= pScaleY;
this.d *= pScaleY;
}
public void postScale(final float pScaleX, final float pScaleY) {
this.a = this.a * pScaleX;
this.b = this.b * pScaleY;
this.c = this.c * pScaleX;
this.d = this.d * pScaleY;
this.tx = this.tx * pScaleX;
this.ty = this.ty * pScaleY;
}
public Transformation setToScale(final float pScaleX, final float pScaleY) {
this.a = pScaleX;
this.b = 0.0f;
this.c = 0.0f;
this.d = pScaleY;
this.tx = 0.0f;
this.ty = 0.0f;
return this;
}
public void preRotate(final float pAngle) {
final float angleRad = MathUtils.degToRad(pAngle);
final float sin = FloatMath.sin(angleRad);
final float cos = FloatMath.cos(angleRad);
final float a = this.a;
final float b = this.b;
final float c = this.c;
final float d = this.d;
this.a = cos * a + sin * c;
this.b = cos * b + sin * d;
this.c = cos * c - sin * a;
this.d = cos * d - sin * b;
}
public void postRotate(final float pAngle) {
final float angleRad = MathUtils.degToRad(pAngle);
final float sin = FloatMath.sin(angleRad);
final float cos = FloatMath.cos(angleRad);
final float a = this.a;
final float b = this.b;
final float c = this.c;
final float d = this.d;
final float tx = this.tx;
final float ty = this.ty;
this.a = a * cos - b * sin;
this.b = a * sin + b * cos;
this.c = c * cos - d * sin;
this.d = c * sin + d * cos;
this.tx = tx * cos - ty * sin;
this.ty = tx * sin + ty * cos;
}
public Transformation setToRotate(final float pAngle) {
final float angleRad = MathUtils.degToRad(pAngle);
final float sin = FloatMath.sin(angleRad);
final float cos = FloatMath.cos(angleRad);
this.a = cos;
this.b = sin;
this.c = -sin;
this.d = cos;
this.tx = 0.0f;
this.ty = 0.0f;
return this;
}
public void postConcat(final Transformation pTransformation) {
this.postConcat(pTransformation.a, pTransformation.b, pTransformation.c, pTransformation.d, pTransformation.tx, pTransformation.ty);
}
private void postConcat(final float pA, final float pB, final float pC, final float pD, final float pTX, final float pTY) {
final float a = this.a;
final float b = this.b;
final float c = this.c;
final float d = this.d;
final float tx = this.tx;
final float ty = this.ty;
this.a = a * pA + b * pC;
this.b = a * pB + b * pD;
this.c = c * pA + d * pC;
this.d = c * pB + d * pD;
this.tx = tx * pA + ty * pC + pTX;
this.ty = tx * pB + ty * pD + pTY;
}
public void preConcat(final Transformation pTransformation) {
this.preConcat(pTransformation.a, pTransformation.b, pTransformation.c, pTransformation.d, pTransformation.tx, pTransformation.ty);
}
private void preConcat(final float pA, final float pB, final float pC, final float pD, final float pTX, final float pTY) {
final float a = this.a;
final float b = this.b;
final float c = this.c;
final float d = this.d;
final float tx = this.tx;
final float ty = this.ty;
this.a = pA * a + pB * c;
this.b = pA * b + pB * d;
this.c = pC * a + pD * c;
this.d = pC * b + pD * d;
this.tx = pTX * a + pTY * c + tx;
this.ty = pTX * b + pTY * d + ty;
}
public void transform(final float[] pVertices) {
int count = pVertices.length >> 1;
int i = 0;
int j = 0;
while(--count >= 0) {
final float x = pVertices[i++];
final float y = pVertices[i++];
pVertices[j++] = x * this.a + y * this.c + this.tx;
pVertices[j++] = x * this.b + y * this.d + this.ty;
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
} | Java |
package org.anddev.andengine.util;
import android.graphics.Color;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:13:45 - 04.08.2010
*/
public class ColorUtils {
// ===========================================================
// Constants
// ===========================================================
private static final float[] HSV_TO_COLOR = new float[3];
private static final int HSV_TO_COLOR_HUE_INDEX = 0;
private static final int HSV_TO_COLOR_SATURATION_INDEX = 1;
private static final int HSV_TO_COLOR_VALUE_INDEX = 2;
private static final int COLOR_FLOAT_TO_INT_FACTOR = 255;
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
/**
* @param pHue [0 .. 360)
* @param pSaturation [0...1]
* @param pValue [0...1]
*/
public static int HSVToColor(final float pHue, final float pSaturation, final float pValue) {
HSV_TO_COLOR[HSV_TO_COLOR_HUE_INDEX] = pHue;
HSV_TO_COLOR[HSV_TO_COLOR_SATURATION_INDEX] = pSaturation;
HSV_TO_COLOR[HSV_TO_COLOR_VALUE_INDEX] = pValue;
return Color.HSVToColor(HSV_TO_COLOR);
}
public static int RGBToColor(final float pRed, final float pGreen, final float pBlue) {
return Color.rgb((int)(pRed * COLOR_FLOAT_TO_INT_FACTOR), (int)(pGreen * COLOR_FLOAT_TO_INT_FACTOR), (int)(pBlue * COLOR_FLOAT_TO_INT_FACTOR));
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.levelstats;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.anddev.andengine.util.Callback;
import org.anddev.andengine.util.Debug;
import org.anddev.andengine.util.MathUtils;
import org.anddev.andengine.util.SimplePreferences;
import org.anddev.andengine.util.StreamUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.content.Context;
import android.content.SharedPreferences;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 21:13:55 - 18.10.2010
*/
public class LevelStatsDBConnector {
// ===========================================================
// Constants
// ===========================================================
private static final String PREFERENCES_LEVELSTATSDBCONNECTOR_PLAYERID_ID = "preferences.levelstatsdbconnector.playerid";
// ===========================================================
// Fields
// ===========================================================
private final String mSecret;
private final String mSubmitURL;
private final int mPlayerID;
// ===========================================================
// Constructors
// ===========================================================
public LevelStatsDBConnector(final Context pContext, final String pSecret, final String pSubmitURL) {
this.mSecret = pSecret;
this.mSubmitURL = pSubmitURL;
final SharedPreferences simplePreferences = SimplePreferences.getInstance(pContext);
final int playerID = simplePreferences.getInt(PREFERENCES_LEVELSTATSDBCONNECTOR_PLAYERID_ID, -1);
if(playerID != -1) {
this.mPlayerID = playerID;
} else {
this.mPlayerID = MathUtils.random(1000000000, Integer.MAX_VALUE);
SimplePreferences.getEditorInstance(pContext).putInt(PREFERENCES_LEVELSTATSDBCONNECTOR_PLAYERID_ID, this.mPlayerID).commit();
}
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
public void submitAsync(final int pLevelID, final boolean pSolved, final int pSecondsElapsed) {
this.submitAsync(pLevelID, pSolved, pSecondsElapsed, null);
}
public void submitAsync(final int pLevelID, final boolean pSolved, final int pSecondsElapsed, final Callback<Boolean> pCallback) {
new Thread(new Runnable() {
@Override
public void run() {
try{
/* Create a new HttpClient and Post Header. */
final HttpClient httpClient = new DefaultHttpClient();
final HttpPost httpPost = new HttpPost(LevelStatsDBConnector.this.mSubmitURL);
/* Append POST data. */
final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("level_id", String.valueOf(pLevelID)));
nameValuePairs.add(new BasicNameValuePair("solved", (pSolved) ? "1" : "0"));
nameValuePairs.add(new BasicNameValuePair("secondsplayed", String.valueOf(pSecondsElapsed)));
nameValuePairs.add(new BasicNameValuePair("player_id", String.valueOf(LevelStatsDBConnector.this.mPlayerID)));
nameValuePairs.add(new BasicNameValuePair("secret", String.valueOf(LevelStatsDBConnector.this.mSecret)));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
/* Execute HTTP Post Request. */
final HttpResponse httpResponse = httpClient.execute(httpPost);
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if(statusCode == HttpStatus.SC_OK) {
final String response = StreamUtils.readFully(httpResponse.getEntity().getContent());
if(response.equals("<success/>")) {
if(pCallback != null) {
pCallback.onCallback(true);
}
} else {
if(pCallback != null) {
pCallback.onCallback(false);
}
}
} else {
if(pCallback != null) {
pCallback.onCallback(false);
}
}
}catch(final IOException e) {
Debug.e(e);
if(pCallback != null) {
pCallback.onCallback(false);
}
}
}
}).start();
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util;
import android.util.SparseArray;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:51:29 - 20.08.2010
* @param <T>
*/
public class Library<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
protected final SparseArray<T> mItems;
// ===========================================================
// Constructors
// ===========================================================
public Library() {
this.mItems = new SparseArray<T>();
}
public Library(final int pInitialCapacity) {
this.mItems = new SparseArray<T>(pInitialCapacity);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public void put(final int pID, final T pItem) {
final T existingItem = this.mItems.get(pID);
if(existingItem == null) {
this.mItems.put(pID, pItem);
} else {
throw new IllegalArgumentException("ID: '" + pID + "' is already associated with item: '" + existingItem.toString() + "'.");
}
}
public void remove(final int pID) {
this.mItems.remove(pID);
}
public T get(final int pID) {
return this.mItems.get(pID);
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
/*
* Copyright (C) 2010 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.anddev.andengine.util;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* An InputStream that does Base64 decoding on the data read through
* it.
*/
public class Base64InputStream extends FilterInputStream {
private final Base64.Coder coder;
private static byte[] EMPTY = new byte[0];
private static final int BUFFER_SIZE = 2048;
private boolean eof;
private byte[] inputBuffer;
private int outputStart;
private int outputEnd;
/**
* An InputStream that performs Base64 decoding on the data read
* from the wrapped stream.
*
* @param in the InputStream to read the source data from
* @param flags bit flags for controlling the decoder; see the
* constants in {@link Base64}
*/
public Base64InputStream(final InputStream in, final int flags) {
this(in, flags, false);
}
/**
* Performs Base64 encoding or decoding on the data read from the
* wrapped InputStream.
*
* @param in the InputStream to read the source data from
* @param flags bit flags for controlling the decoder; see the
* constants in {@link Base64}
* @param encode true to encode, false to decode
*
* @hide
*/
public Base64InputStream(final InputStream in, final int flags, final boolean encode) {
super(in);
this.eof = false;
this.inputBuffer = new byte[BUFFER_SIZE];
if (encode) {
this.coder = new Base64.Encoder(flags, null);
} else {
this.coder = new Base64.Decoder(flags, null);
}
this.coder.output = new byte[this.coder.maxOutputSize(BUFFER_SIZE)];
this.outputStart = 0;
this.outputEnd = 0;
}
@Override
public boolean markSupported() {
return false;
}
@Override
public void mark(final int readlimit) {
throw new UnsupportedOperationException();
}
@Override
public void reset() {
throw new UnsupportedOperationException();
}
@Override
public void close() throws IOException {
this.in.close();
this.inputBuffer = null;
}
@Override
public int available() {
return this.outputEnd - this.outputStart;
}
@Override
public long skip(final long n) throws IOException {
if (this.outputStart >= this.outputEnd) {
this.refill();
}
if (this.outputStart >= this.outputEnd) {
return 0;
}
final long bytes = Math.min(n, this.outputEnd-this.outputStart);
this.outputStart += bytes;
return bytes;
}
@Override
public int read() throws IOException {
if (this.outputStart >= this.outputEnd) {
this.refill();
}
if (this.outputStart >= this.outputEnd) {
return -1;
} else {
return this.coder.output[this.outputStart++];
}
}
@Override
public int read(final byte[] b, final int off, final int len) throws IOException {
if (this.outputStart >= this.outputEnd) {
this.refill();
}
if (this.outputStart >= this.outputEnd) {
return -1;
}
final int bytes = Math.min(len, this.outputEnd-this.outputStart);
System.arraycopy(this.coder.output, this.outputStart, b, off, bytes);
this.outputStart += bytes;
return bytes;
}
/**
* Read data from the input stream into inputBuffer, then
* decode/encode it into the empty coder.output, and reset the
* outputStart and outputEnd pointers.
*/
private void refill() throws IOException {
if (this.eof) {
return;
}
final int bytesRead = this.in.read(this.inputBuffer);
boolean success;
if (bytesRead == -1) {
this.eof = true;
success = this.coder.process(EMPTY, 0, 0, true);
} else {
success = this.coder.process(this.inputBuffer, 0, bytesRead, false);
}
if (!success) {
throw new IOException("bad base-64");
}
this.outputEnd = this.coder.op;
this.outputStart = 0;
}
}
| Java |
package org.anddev.andengine.util;
import org.anddev.andengine.util.pool.GenericPool;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 23:07:53 - 23.02.2011
*/
public class TransformationPool {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static final GenericPool<Transformation> POOL = new GenericPool<Transformation>() {
@Override
protected Transformation onAllocatePoolItem() {
return new Transformation();
}
};
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
public static Transformation obtain() {
return POOL.obtainPoolItem();
}
public static void recycle(final Transformation pTransformation) {
pTransformation.setToIdentity();
POOL.recyclePoolItem(pTransformation);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
} | Java |
package org.anddev.andengine.util;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.net.Socket;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 14:42:15 - 18.09.2009
*/
public class SocketUtils {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static void closeSocket(final DatagramSocket pDatagramSocket) {
if(pDatagramSocket != null && !pDatagramSocket.isClosed()) {
pDatagramSocket.close();
}
}
public static void closeSocket(final Socket pSocket) {
if(pSocket != null && !pSocket.isClosed()) {
try {
pSocket.close();
} catch (final IOException e) {
Debug.e(e);
}
}
}
public static void closeSocket(final ServerSocket pServerSocket) {
if(pServerSocket != null && !pServerSocket.isClosed()) {
try {
pServerSocket.close();
} catch (final IOException e) {
Debug.e(e);
}
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 20:52:44 - 03.01.2010
*/
public interface Callable<T> {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return the computed result.
* @throws Exception if unable to compute a result.
*/
public T call() throws Exception;
} | Java |
package org.anddev.andengine.util;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 22:35:42 - 01.05.2011
*/
public class ArrayUtils {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static <T> T random(final T[] pArray) {
return pArray[MathUtils.random(0, pArray.length - 1)];
}
public static void reverse(final byte[] pArray) {
if (pArray == null) {
return;
}
int i = 0;
int j = pArray.length - 1;
byte tmp;
while (j > i) {
tmp = pArray[j];
pArray[j] = pArray[i];
pArray[i] = tmp;
j--;
i++;
}
}
public static void reverse(final short[] pArray) {
if (pArray == null) {
return;
}
int i = 0;
int j = pArray.length - 1;
short tmp;
while (j > i) {
tmp = pArray[j];
pArray[j] = pArray[i];
pArray[i] = tmp;
j--;
i++;
}
}
public static void reverse(final int[] pArray) {
if (pArray == null) {
return;
}
int i = 0;
int j = pArray.length - 1;
int tmp;
while (j > i) {
tmp = pArray[j];
pArray[j] = pArray[i];
pArray[i] = tmp;
j--;
i++;
}
}
public static void reverse(final long[] pArray) {
if (pArray == null) {
return;
}
int i = 0;
int j = pArray.length - 1;
long tmp;
while (j > i) {
tmp = pArray[j];
pArray[j] = pArray[i];
pArray[i] = tmp;
j--;
i++;
}
}
public static void reverse(final float[] pArray) {
if (pArray == null) {
return;
}
int i = 0;
int j = pArray.length - 1;
float tmp;
while (j > i) {
tmp = pArray[j];
pArray[j] = pArray[i];
pArray[i] = tmp;
j--;
i++;
}
}
public static void reverse(final double[] pArray) {
if (pArray == null) {
return;
}
int i = 0;
int j = pArray.length - 1;
double tmp;
while (j > i) {
tmp = pArray[j];
pArray[j] = pArray[i];
pArray[i] = tmp;
j--;
i++;
}
}
public static void reverse(final Object[] pArray) {
if (pArray == null) {
return;
}
int i = 0;
int j = pArray.length - 1;
Object tmp;
while (j > i) {
tmp = pArray[j];
pArray[j] = pArray[i];
pArray[i] = tmp;
j--;
i++;
}
}
public static boolean equals(final byte[] pArrayA, final int pOffsetA, final byte[] pArrayB, final int pOffsetB, final int pLength) {
final int lastIndexA = pOffsetA + pLength;
if(lastIndexA > pArrayA.length) {
throw new ArrayIndexOutOfBoundsException(pArrayA.length);
}
final int lastIndexB = pOffsetB + pLength;
if(lastIndexB > pArrayB.length) {
throw new ArrayIndexOutOfBoundsException(pArrayB.length);
}
for(int a = pOffsetA, b = pOffsetB; a < lastIndexA; a++, b++) {
if(pArrayA[a] != pArrayB[b]) {
return false;
}
}
return true;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 19:01:08 - 03.04.2010
*/
public class StringUtils {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static String padFront(final String pString, final char pPadChar, final int pLength) {
final int padCount = pLength - pString.length();
if(padCount <= 0) {
return pString;
} else {
final StringBuilder sb = new StringBuilder();
for(int i = padCount - 1; i >= 0; i--) {
sb.append(pPadChar);
}
sb.append(pString);
return sb.toString();
}
}
public static int countOccurrences(final String pString, final char pCharacter) {
int count = 0;
int lastOccurrence = pString.indexOf(pCharacter, 0);
while (lastOccurrence != -1) {
count++;
lastOccurrence = pString.indexOf(pCharacter, lastOccurrence + 1);
}
return count;
}
/**
* Split a String by a Character, i.e. Split lines by using '\n'.<br/>
* Same behavior as <code>String.split("" + pCharacter);</code> .
*
* @param pString
* @param pCharacter
* @return
*/
public static String[] split(final String pString, final char pCharacter) {
return StringUtils.split(pString, pCharacter, null);
}
/**
* Split a String by a Character, i.e. Split lines by using '\n'.<br/>
* Same behavior as <code>String.split("" + pCharacter);</code> .
*
* @param pString
* @param pCharacter
* @param pReuse tries to reuse the String[] if the length is the same as the length needed.
* @return
*/
public static String[] split(final String pString, final char pCharacter, final String[] pReuse) {
final int partCount = StringUtils.countOccurrences(pString, pCharacter) + 1;
final boolean reuseable = pReuse != null && pReuse.length == partCount;
final String[] out = (reuseable) ? pReuse : new String[partCount];
if(partCount == 0) {
out[0] = pString;
} else {
int from = 0;
int to;
for (int i = 0; i < partCount - 1; i++) {
to = pString.indexOf(pCharacter, from);
out[i] = pString.substring(from, to);
from = to + 1;
}
out[partCount - 1] = pString.substring(from, pString.length());
}
return out;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:48:13 - 03.09.2010
* @param <T>
*/
public abstract class BaseDurationModifier<T> extends BaseModifier<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private float mSecondsElapsed;
protected final float mDuration;
// ===========================================================
// Constructors
// ===========================================================
public BaseDurationModifier(final float pDuration) {
this.mDuration = pDuration;
}
public BaseDurationModifier(final float pDuration, final IModifierListener<T> pModifierListener) {
super(pModifierListener);
this.mDuration = pDuration;
}
protected BaseDurationModifier(final BaseDurationModifier<T> pBaseModifier) {
this(pBaseModifier.mDuration);
}
// ===========================================================
// Getter & Setter
// ===========================================================
@Override
public float getSecondsElapsed() {
return this.mSecondsElapsed;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getDuration() {
return this.mDuration;
}
protected abstract void onManagedUpdate(final float pSecondsElapsed, final T pItem);
protected abstract void onManagedInitialize(final T pItem);
@Override
public final float onUpdate(final float pSecondsElapsed, final T pItem) {
if(this.mFinished){
return 0;
} else {
if(this.mSecondsElapsed == 0) {
this.onManagedInitialize(pItem);
this.onModifierStarted(pItem);
}
final float secondsElapsedUsed;
if(this.mSecondsElapsed + pSecondsElapsed < this.mDuration) {
secondsElapsedUsed = pSecondsElapsed;
} else {
secondsElapsedUsed = this.mDuration - this.mSecondsElapsed;
}
this.mSecondsElapsed += secondsElapsedUsed;
this.onManagedUpdate(secondsElapsedUsed, pItem);
if(this.mDuration != -1 && this.mSecondsElapsed >= this.mDuration) {
this.mSecondsElapsed = this.mDuration;
this.mFinished = true;
this.onModifierFinished(pItem);
}
return secondsElapsedUsed;
}
}
@Override
public void reset() {
this.mFinished = false;
this.mSecondsElapsed = 0;
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier;
import org.anddev.andengine.util.modifier.IModifier.IModifierListener;
import org.anddev.andengine.util.modifier.util.ModifierUtils;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 19:39:25 - 19.03.2010
*/
public class SequenceModifier<T> extends BaseModifier<T> implements IModifierListener<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private ISubSequenceModifierListener<T> mSubSequenceModifierListener;
private final IModifier<T>[] mSubSequenceModifiers;
private int mCurrentSubSequenceModifierIndex;
private float mSecondsElapsed;
private final float mDuration;
private boolean mFinishedCached;
// ===========================================================
// Constructors
// ===========================================================
public SequenceModifier(final IModifier<T> ... pModifiers) throws IllegalArgumentException {
this(null, null, pModifiers);
}
public SequenceModifier(final ISubSequenceModifierListener<T> pSubSequenceModifierListener, final IModifier<T> ... pModifiers) throws IllegalArgumentException {
this(pSubSequenceModifierListener, null, pModifiers);
}
public SequenceModifier(final IModifierListener<T> pModifierListener, final IModifier<T> ... pModifiers) throws IllegalArgumentException {
this(null, pModifierListener, pModifiers);
}
public SequenceModifier(final ISubSequenceModifierListener<T> pSubSequenceModifierListener, final IModifierListener<T> pModifierListener, final IModifier<T> ... pModifiers) throws IllegalArgumentException {
super(pModifierListener);
if (pModifiers.length == 0) {
throw new IllegalArgumentException("pModifiers must not be empty!");
}
this.mSubSequenceModifierListener = pSubSequenceModifierListener;
this.mSubSequenceModifiers = pModifiers;
this.mDuration = ModifierUtils.getSequenceDurationOfModifier(pModifiers);
pModifiers[0].addModifierListener(this);
}
@SuppressWarnings("unchecked")
protected SequenceModifier(final SequenceModifier<T> pSequenceModifier) throws DeepCopyNotSupportedException {
this.mDuration = pSequenceModifier.mDuration;
final IModifier<T>[] otherModifiers = pSequenceModifier.mSubSequenceModifiers;
this.mSubSequenceModifiers = new IModifier[otherModifiers.length];
final IModifier<T>[] shapeModifiers = this.mSubSequenceModifiers;
for(int i = shapeModifiers.length - 1; i >= 0; i--) {
shapeModifiers[i] = otherModifiers[i].deepCopy();
}
shapeModifiers[0].addModifierListener(this);
}
@Override
public SequenceModifier<T> deepCopy() throws DeepCopyNotSupportedException{
return new SequenceModifier<T>(this);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public ISubSequenceModifierListener<T> getSubSequenceModifierListener() {
return this.mSubSequenceModifierListener;
}
public void setSubSequenceModifierListener(final ISubSequenceModifierListener<T> pSubSequenceModifierListener) {
this.mSubSequenceModifierListener = pSubSequenceModifierListener;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getSecondsElapsed() {
return this.mSecondsElapsed;
}
@Override
public float getDuration() {
return this.mDuration;
}
@Override
public float onUpdate(final float pSecondsElapsed, final T pItem) {
if(this.mFinished){
return 0;
} else {
float secondsElapsedRemaining = pSecondsElapsed;
this.mFinishedCached = false;
while(secondsElapsedRemaining > 0 && !this.mFinishedCached) {
secondsElapsedRemaining -= this.mSubSequenceModifiers[this.mCurrentSubSequenceModifierIndex].onUpdate(secondsElapsedRemaining, pItem);
}
this.mFinishedCached = false;
final float secondsElapsedUsed = pSecondsElapsed - secondsElapsedRemaining;
this.mSecondsElapsed += secondsElapsedUsed;
return secondsElapsedUsed;
}
}
@Override
public void reset() {
if(this.isFinished()) {
this.mSubSequenceModifiers[this.mSubSequenceModifiers.length - 1].removeModifierListener(this);
} else {
this.mSubSequenceModifiers[this.mCurrentSubSequenceModifierIndex].removeModifierListener(this);
}
this.mCurrentSubSequenceModifierIndex = 0;
this.mFinished = false;
this.mSecondsElapsed = 0;
this.mSubSequenceModifiers[0].addModifierListener(this);
final IModifier<T>[] shapeModifiers = this.mSubSequenceModifiers;
for(int i = shapeModifiers.length - 1; i >= 0; i--) {
shapeModifiers[i].reset();
}
}
@Override
public void onModifierStarted(final IModifier<T> pModifier, final T pItem) {
if(this.mCurrentSubSequenceModifierIndex == 0) {
this.onModifierStarted(pItem);
}
if(this.mSubSequenceModifierListener != null) {
this.mSubSequenceModifierListener.onSubSequenceStarted(pModifier, pItem, this.mCurrentSubSequenceModifierIndex);
}
}
@Override
public void onModifierFinished(final IModifier<T> pModifier, final T pItem) {
if(this.mSubSequenceModifierListener != null) {
this.mSubSequenceModifierListener.onSubSequenceFinished(pModifier, pItem, this.mCurrentSubSequenceModifierIndex);
}
pModifier.removeModifierListener(this);
this.mCurrentSubSequenceModifierIndex++;
if(this.mCurrentSubSequenceModifierIndex < this.mSubSequenceModifiers.length) {
final IModifier<T> nextSubSequenceModifier = this.mSubSequenceModifiers[this.mCurrentSubSequenceModifierIndex];
nextSubSequenceModifier.addModifierListener(this);
} else {
this.mFinished = true;
this.mFinishedCached = true;
this.onModifierFinished(pItem);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public interface ISubSequenceModifierListener<T> {
public void onSubSequenceStarted(final IModifier<T> pModifier, final T pItem, final int pIndex);
public void onSubSequenceFinished(final IModifier<T> pModifier, final T pItem, final int pIndex);
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.