code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.activities;
import java.text.DecimalFormat;
import java.util.List;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.InfoLogger;
import org.odk.collect.android.widgets.GeoPointWidget;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.widget.Toast;
public class GeoPointActivity extends Activity implements LocationListener {
private static final String LOCATION_COUNT = "locationCount";
private ProgressDialog mLocationDialog;
private LocationManager mLocationManager;
private Location mLocation;
private boolean mGPSOn = false;
private boolean mNetworkOn = false;
private double mLocationAccuracy;
private int mLocationCount = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ( savedInstanceState != null ) {
mLocationCount = savedInstanceState.getInt(LOCATION_COUNT);
}
Intent intent = getIntent();
mLocationAccuracy = GeoPointWidget.DEFAULT_LOCATION_ACCURACY;
if (intent != null && intent.getExtras() != null) {
if ( intent.hasExtra(GeoPointWidget.ACCURACY_THRESHOLD) ) {
mLocationAccuracy = intent.getDoubleExtra(GeoPointWidget.ACCURACY_THRESHOLD, GeoPointWidget.DEFAULT_LOCATION_ACCURACY);
}
}
setTitle(getString(R.string.app_name) + " > " + getString(R.string.get_location));
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// make sure we have a good location provider before continuing
List<String> providers = mLocationManager.getProviders(true);
for (String provider : providers) {
if (provider.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) {
mGPSOn = true;
}
if (provider.equalsIgnoreCase(LocationManager.NETWORK_PROVIDER)) {
mNetworkOn = true;
}
}
if (!mGPSOn && !mNetworkOn) {
Toast.makeText(getBaseContext(), getString(R.string.provider_disabled_error),
Toast.LENGTH_SHORT).show();
finish();
}
if ( mGPSOn ) {
Location loc = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if ( loc != null ) {
InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() +
" lastKnownLocation(GPS) lat: " +
loc.getLatitude() + " long: " +
loc.getLongitude() + " acc: " +
loc.getAccuracy() );
} else {
InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() +
" lastKnownLocation(GPS) null location");
}
}
if ( mNetworkOn ) {
Location loc = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if ( loc != null ) {
InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() +
" lastKnownLocation(Network) lat: " +
loc.getLatitude() + " long: " +
loc.getLongitude() + " acc: " +
loc.getAccuracy() );
} else {
InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() +
" lastKnownLocation(Network) null location");
}
}
setupLocationDialog();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(LOCATION_COUNT, mLocationCount);
}
@Override
protected void onPause() {
super.onPause();
// stops the GPS. Note that this will turn off the GPS if the screen goes to sleep.
mLocationManager.removeUpdates(this);
// We're not using managed dialogs, so we have to dismiss the dialog to prevent it from
// leaking memory.
if (mLocationDialog != null && mLocationDialog.isShowing())
mLocationDialog.dismiss();
}
@Override
protected void onResume() {
super.onResume();
if (mGPSOn) {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
if (mNetworkOn) {
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
mLocationDialog.show();
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
/**
* Sets up the look and actions for the progress dialog while the GPS is searching.
*/
private void setupLocationDialog() {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "setupLocationDialog", "show");
// dialog displayed while fetching gps location
mLocationDialog = new ProgressDialog(this);
DialogInterface.OnClickListener geopointButtonListener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON1:
Collect.getInstance().getActivityLogger().logInstanceAction(this, "acceptLocation", "OK");
returnLocation();
break;
case DialogInterface.BUTTON2:
Collect.getInstance().getActivityLogger().logInstanceAction(this, "cancelLocation", "cancel");
mLocation = null;
finish();
break;
}
}
};
// back button doesn't cancel
mLocationDialog.setCancelable(false);
mLocationDialog.setIndeterminate(true);
mLocationDialog.setIcon(android.R.drawable.ic_dialog_info);
mLocationDialog.setTitle(getString(R.string.getting_location));
mLocationDialog.setMessage(getString(R.string.please_wait_long));
mLocationDialog.setButton(DialogInterface.BUTTON1, getString(R.string.accept_location),
geopointButtonListener);
mLocationDialog.setButton(DialogInterface.BUTTON2, getString(R.string.cancel_location),
geopointButtonListener);
}
private void returnLocation() {
if (mLocation != null) {
Intent i = new Intent();
i.putExtra(
FormEntryActivity.LOCATION_RESULT,
mLocation.getLatitude() + " " + mLocation.getLongitude() + " "
+ mLocation.getAltitude() + " " + mLocation.getAccuracy());
setResult(RESULT_OK, i);
}
finish();
}
@Override
public void onLocationChanged(Location location) {
mLocation = location;
if (mLocation != null) {
// Bug report: cached GeoPoint is being returned as the first value.
// Wait for the 2nd value to be returned, which is hopefully not cached?
++mLocationCount;
InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() +
" onLocationChanged(" + mLocationCount + ") lat: " +
mLocation.getLatitude() + " long: " +
mLocation.getLongitude() + " acc: " +
mLocation.getAccuracy() );
if (mLocationCount > 1) {
mLocationDialog.setMessage(getString(R.string.location_provider_accuracy,
mLocation.getProvider(), truncateDouble(mLocation.getAccuracy())));
if (mLocation.getAccuracy() <= mLocationAccuracy) {
returnLocation();
}
}
} else {
InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() +
" onLocationChanged(" + mLocationCount + ") null location");
}
}
private String truncateDouble(float number) {
DecimalFormat df = new DecimalFormat("#.##");
return df.format(number);
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case LocationProvider.AVAILABLE:
if (mLocation != null) {
mLocationDialog.setMessage(getString(R.string.location_accuracy,
mLocation.getAccuracy()));
}
break;
case LocationProvider.OUT_OF_SERVICE:
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
break;
}
}
}
| 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.activities;
import java.util.ArrayList;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.odk.collect.android.provider.InstanceProviderAPI;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import org.odk.collect.android.receivers.NetworkReceiver;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
/**
* Responsible for displaying all the valid forms in the forms directory. Stores
* the path to selected form for use by {@link MainMenuActivity}.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class InstanceUploaderList extends ListActivity implements
OnLongClickListener {
private static final String BUNDLE_SELECTED_ITEMS_KEY = "selected_items";
private static final String BUNDLE_TOGGLED_KEY = "toggled";
private static final int MENU_PREFERENCES = Menu.FIRST;
private static final int MENU_SHOW_UNSENT = Menu.FIRST + 1;
private static final int INSTANCE_UPLOADER = 0;
private Button mUploadButton;
private Button mToggleButton;
private boolean mShowUnsent = true;
private SimpleCursorAdapter mInstances;
private ArrayList<Long> mSelected = new ArrayList<Long>();
private boolean mRestored = false;
private boolean mToggled = false;
public Cursor getUnsentCursor() {
// get all complete or failed submission instances
String selection = InstanceColumns.STATUS + "=? or "
+ InstanceColumns.STATUS + "=?";
String selectionArgs[] = { InstanceProviderAPI.STATUS_COMPLETE,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED };
String sortOrder = InstanceColumns.DISPLAY_NAME + " ASC";
Cursor c = managedQuery(InstanceColumns.CONTENT_URI, null, selection,
selectionArgs, sortOrder);
return c;
}
public Cursor getAllCursor() {
// get all complete or failed submission instances
String selection = InstanceColumns.STATUS + "=? or "
+ InstanceColumns.STATUS + "=? or " + InstanceColumns.STATUS
+ "=?";
String selectionArgs[] = { InstanceProviderAPI.STATUS_COMPLETE,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED,
InstanceProviderAPI.STATUS_SUBMITTED };
String sortOrder = InstanceColumns.DISPLAY_NAME + " ASC";
Cursor c = managedQuery(InstanceColumns.CONTENT_URI, null, selection,
selectionArgs, sortOrder);
return c;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.instance_uploader_list);
// set up long click listener
mUploadButton = (Button) findViewById(R.id.upload_button);
mUploadButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
if (NetworkReceiver.running == true) {
Toast.makeText(
InstanceUploaderList.this,
"Background send running, please try again shortly",
Toast.LENGTH_SHORT).show();
} else if (ni == null || !ni.isConnected()) {
Collect.getInstance().getActivityLogger()
.logAction(this, "uploadButton", "noConnection");
Toast.makeText(InstanceUploaderList.this,
R.string.no_connection, Toast.LENGTH_SHORT).show();
} else {
Collect.getInstance()
.getActivityLogger()
.logAction(this, "uploadButton",
Integer.toString(mSelected.size()));
if (mSelected.size() > 0) {
// items selected
uploadSelectedFiles();
mToggled = false;
mSelected.clear();
InstanceUploaderList.this.getListView().clearChoices();
mUploadButton.setEnabled(false);
} else {
// no items selected
Toast.makeText(getApplicationContext(),
getString(R.string.noselect_error),
Toast.LENGTH_SHORT).show();
}
}
}
});
mToggleButton = (Button) findViewById(R.id.toggle_button);
mToggleButton.setLongClickable(true);
mToggleButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// toggle selections of items to all or none
ListView ls = getListView();
mToggled = !mToggled;
Collect.getInstance()
.getActivityLogger()
.logAction(this, "toggleButton",
Boolean.toString(mToggled));
// remove all items from selected list
mSelected.clear();
for (int pos = 0; pos < ls.getCount(); pos++) {
ls.setItemChecked(pos, mToggled);
// add all items if mToggled sets to select all
if (mToggled)
mSelected.add(ls.getItemIdAtPosition(pos));
}
mUploadButton.setEnabled(!(mSelected.size() == 0));
}
});
mToggleButton.setOnLongClickListener(this);
Cursor c = mShowUnsent ? getUnsentCursor() : getAllCursor();
String[] data = new String[] { InstanceColumns.DISPLAY_NAME,
InstanceColumns.DISPLAY_SUBTEXT };
int[] view = new int[] { R.id.text1, R.id.text2 };
// render total instance view
mInstances = new SimpleCursorAdapter(this,
R.layout.two_item_multiple_choice, c, data, view);
setListAdapter(mInstances);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
getListView().setItemsCanFocus(false);
mUploadButton.setEnabled(!(mSelected.size() == 0));
// set title
setTitle(getString(R.string.app_name) + " > "
+ getString(R.string.send_data));
// if current activity is being reinitialized due to changing
// orientation restore all check
// marks for ones selected
if (mRestored) {
ListView ls = getListView();
for (long id : mSelected) {
for (int pos = 0; pos < ls.getCount(); pos++) {
if (id == ls.getItemIdAtPosition(pos)) {
ls.setItemChecked(pos, true);
break;
}
}
}
mRestored = false;
}
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
private void uploadSelectedFiles() {
// send list of _IDs.
long[] instanceIDs = new long[mSelected.size()];
for (int i = 0; i < mSelected.size(); i++) {
instanceIDs[i] = mSelected.get(i);
}
Intent i = new Intent(this, InstanceUploaderActivity.class);
i.putExtra(FormEntryActivity.KEY_INSTANCES, instanceIDs);
startActivityForResult(i, INSTANCE_UPLOADER);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Collect.getInstance().getActivityLogger()
.logAction(this, "onCreateOptionsMenu", "show");
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_PREFERENCES, 0,
getString(R.string.general_preferences)).setIcon(
android.R.drawable.ic_menu_preferences);
menu.add(0, MENU_SHOW_UNSENT, 1, getString(R.string.change_view))
.setIcon(android.R.drawable.ic_menu_preferences);
return true;
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case MENU_PREFERENCES:
Collect.getInstance().getActivityLogger()
.logAction(this, "onMenuItemSelected", "MENU_PREFERENCES");
createPreferencesMenu();
return true;
case MENU_SHOW_UNSENT:
Collect.getInstance().getActivityLogger()
.logAction(this, "onMenuItemSelected", "MENU_SHOW_UNSENT");
showSentAndUnsentChoices();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
private void createPreferencesMenu() {
Intent i = new Intent(this, PreferencesActivity.class);
startActivity(i);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// get row id from db
Cursor c = (Cursor) getListAdapter().getItem(position);
long k = c.getLong(c.getColumnIndex(InstanceColumns._ID));
Collect.getInstance().getActivityLogger()
.logAction(this, "onListItemClick", Long.toString(k));
// add/remove from selected list
if (mSelected.contains(k))
mSelected.remove(k);
else
mSelected.add(k);
mUploadButton.setEnabled(!(mSelected.size() == 0));
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
long[] selectedArray = savedInstanceState
.getLongArray(BUNDLE_SELECTED_ITEMS_KEY);
for (int i = 0; i < selectedArray.length; i++)
mSelected.add(selectedArray[i]);
mToggled = savedInstanceState.getBoolean(BUNDLE_TOGGLED_KEY);
mRestored = true;
mUploadButton.setEnabled(selectedArray.length > 0);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
long[] selectedArray = new long[mSelected.size()];
for (int i = 0; i < mSelected.size(); i++)
selectedArray[i] = mSelected.get(i);
outState.putLongArray(BUNDLE_SELECTED_ITEMS_KEY, selectedArray);
outState.putBoolean(BUNDLE_TOGGLED_KEY, mToggled);
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (resultCode == RESULT_CANCELED) {
return;
}
switch (requestCode) {
// returns with a form path, start entry
case INSTANCE_UPLOADER:
if (intent.getBooleanExtra(FormEntryActivity.KEY_SUCCESS, false)) {
mSelected.clear();
getListView().clearChoices();
if (mInstances.isEmpty()) {
finish();
}
}
break;
default:
break;
}
super.onActivityResult(requestCode, resultCode, intent);
}
private void showUnsent() {
mShowUnsent = true;
Cursor c = mShowUnsent ? getUnsentCursor() : getAllCursor();
Cursor old = mInstances.getCursor();
try {
mInstances.changeCursor(c);
} finally {
if (old != null) {
old.close();
this.stopManagingCursor(old);
}
}
getListView().invalidate();
}
private void showAll() {
mShowUnsent = false;
Cursor c = mShowUnsent ? getUnsentCursor() : getAllCursor();
Cursor old = mInstances.getCursor();
try {
mInstances.changeCursor(c);
} finally {
if (old != null) {
old.close();
this.stopManagingCursor(old);
}
}
getListView().invalidate();
}
@Override
public boolean onLongClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logAction(this, "toggleButton.longClick",
Boolean.toString(mToggled));
return showSentAndUnsentChoices();
}
private boolean showSentAndUnsentChoices() {
/**
* Create a dialog with options to save and exit, save, or quit without
* saving
*/
String[] items = { getString(R.string.show_unsent_forms),
getString(R.string.show_sent_and_unsent_forms) };
Collect.getInstance().getActivityLogger()
.logAction(this, "changeView", "show");
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_info)
.setTitle(getString(R.string.change_view))
.setNeutralButton(getString(R.string.cancel),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
Collect.getInstance()
.getActivityLogger()
.logAction(this, "changeView", "cancel");
dialog.cancel();
}
})
.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0: // show unsent
Collect.getInstance()
.getActivityLogger()
.logAction(this, "changeView", "showUnsent");
InstanceUploaderList.this.showUnsent();
break;
case 1: // show all
Collect.getInstance().getActivityLogger()
.logAction(this, "changeView", "showAll");
InstanceUploaderList.this.showAll();
break;
case 2:// do nothing
break;
}
}
}).create();
alertDialog.show();
return true;
}
}
| Java |
/*
* Copyright (C) 2012 University of Washington
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.activities;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.ColorPickerDialog;
import org.odk.collect.android.utilities.FileUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
/**
* Modified from the FingerPaint example found in The Android Open Source
* Project.
*
* @author BehrAtherton@gmail.com
*
*/
public class DrawActivity extends Activity {
public static final String t = "DrawActivity";
public static final String OPTION = "option";
public static final String OPTION_SIGNATURE = "signature";
public static final String OPTION_ANNOTATE = "annotate";
public static final String OPTION_DRAW = "draw";
public static final String REF_IMAGE = "refImage";
public static final String EXTRA_OUTPUT = android.provider.MediaStore.EXTRA_OUTPUT;
public static final String SAVEPOINT_IMAGE = "savepointImage"; // during
// restore
// incoming options...
private String loadOption = null;
private File refImage = null;
private File output = null;
private File savepointImage = null;
private Button btnDrawColor;
private Button btnFinished;
private Button btnReset;
private Button btnCancel;
private Paint paint;
private Paint pointPaint;
private int currentColor = 0xFF000000;
private DrawView drawView;
private String alertTitleString;
private AlertDialog alertDialog;
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
try {
saveFile(savepointImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if ( savepointImage.exists() ) {
outState.putString(SAVEPOINT_IMAGE, savepointImage.getAbsolutePath());
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
Bundle extras = getIntent().getExtras();
if (extras == null) {
loadOption = OPTION_DRAW;
refImage = null;
savepointImage = new File(Collect.TMPDRAWFILE_PATH);
savepointImage.delete();
output = new File(Collect.TMPFILE_PATH);
} else {
loadOption = extras.getString(OPTION);
if (loadOption == null) {
loadOption = OPTION_DRAW;
}
// refImage can also be present if resuming a drawing
Uri uri = (Uri) extras.get(REF_IMAGE);
if (uri != null) {
refImage = new File(uri.getPath());
}
String savepoint = extras.getString(SAVEPOINT_IMAGE);
if (savepoint != null) {
savepointImage = new File(savepoint);
if (!savepointImage.exists() && refImage != null
&& refImage.exists()) {
FileUtils.copyFile(refImage, savepointImage);
}
} else {
savepointImage = new File(Collect.TMPDRAWFILE_PATH);
savepointImage.delete();
if (refImage != null && refImage.exists()) {
FileUtils.copyFile(refImage, savepointImage);
}
}
uri = (Uri) extras.get(EXTRA_OUTPUT);
if (uri != null) {
output = new File(uri.getPath());
} else {
output = new File(Collect.TMPFILE_PATH);
}
}
// At this point, we have:
// loadOption -- type of activity (draw, signature, annotate)
// refImage -- original image to work with
// savepointImage -- drawing to use as a starting point (may be copy of
// original)
// output -- where the output should be written
if (OPTION_SIGNATURE.equals(loadOption)) {
// set landscape
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
alertTitleString = getString(R.string.quit_application,
getString(R.string.sign_button));
} else if (OPTION_ANNOTATE.equals(loadOption)) {
alertTitleString = getString(R.string.quit_application,
getString(R.string.markup_image));
} else {
alertTitleString = getString(R.string.quit_application,
getString(R.string.draw_image));
}
setTitle(getString(R.string.app_name) + " > "
+ getString(R.string.draw_image));
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout v = (RelativeLayout) inflater.inflate(
R.layout.draw_layout, null);
LinearLayout ll = (LinearLayout) v.findViewById(R.id.drawViewLayout);
drawView = new DrawView(this, OPTION_SIGNATURE.equals(loadOption),
savepointImage);
ll.addView(drawView);
setContentView(v);
paint = new Paint();
paint.setAntiAlias(true);
paint.setDither(true);
paint.setColor(currentColor);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(10);
pointPaint = new Paint();
pointPaint.setAntiAlias(true);
pointPaint.setDither(true);
pointPaint.setColor(currentColor);
pointPaint.setStyle(Paint.Style.FILL_AND_STROKE);
pointPaint.setStrokeWidth(10);
btnDrawColor = (Button) findViewById(R.id.btnSelectColor);
btnDrawColor.setTextColor(getInverseColor(currentColor));
btnDrawColor.getBackground().setColorFilter(currentColor,
PorterDuff.Mode.SRC_ATOP);
btnDrawColor.setText(getString(R.string.set_color));
btnDrawColor.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(
DrawActivity.this,
"setColorButton",
"click",
Collect.getInstance().getFormController()
.getFormIndex());
ColorPickerDialog cpd = new ColorPickerDialog(
DrawActivity.this,
new ColorPickerDialog.OnColorChangedListener() {
public void colorChanged(String key, int color) {
btnDrawColor
.setTextColor(getInverseColor(color));
btnDrawColor.getBackground().setColorFilter(
color, PorterDuff.Mode.SRC_ATOP);
currentColor = color;
paint.setColor(color);
pointPaint.setColor(color);
}
}, "key", currentColor, currentColor,
getString(R.string.select_drawing_color));
cpd.show();
}
});
btnFinished = (Button) findViewById(R.id.btnFinishDraw);
btnFinished.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(
DrawActivity.this,
"saveAndCloseButton",
"click",
Collect.getInstance().getFormController()
.getFormIndex());
SaveAndClose();
}
});
btnReset = (Button) findViewById(R.id.btnResetDraw);
btnReset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(
DrawActivity.this,
"resetButton",
"click",
Collect.getInstance().getFormController()
.getFormIndex());
Reset();
}
});
btnCancel = (Button) findViewById(R.id.btnCancelDraw);
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(
DrawActivity.this,
"cancelAndCloseButton",
"click",
Collect.getInstance().getFormController()
.getFormIndex());
CancelAndClose();
}
});
}
private int getInverseColor(int color) {
int red = Color.red(color);
int green = Color.green(color);
int blue = Color.blue(color);
int alpha = Color.alpha(color);
return Color.argb(alpha, 255 - red, 255 - green, 255 - blue);
}
private void SaveAndClose() {
try {
saveFile(output);
setResult(Activity.RESULT_OK);
} catch (FileNotFoundException e) {
e.printStackTrace();
setResult(Activity.RESULT_CANCELED);
}
this.finish();
}
private void saveFile(File f) throws FileNotFoundException {
if ( drawView.getWidth() == 0 || drawView.getHeight() == 0 ) {
// apparently on 4.x, the orientation change notification can occur
// sometime before the view is rendered. In that case, the view
// dimensions will not be known.
Log.e(t,"view has zero width or zero height");
} else {
FileOutputStream fos;
fos = new FileOutputStream(f);
Bitmap bitmap = Bitmap.createBitmap(drawView.getWidth(),
drawView.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawView.draw(canvas);
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fos);
try {
if ( fos != null ) {
fos.flush();
fos.close();
}
} catch ( Exception e) {
}
}
}
private void Reset() {
savepointImage.delete();
if (!OPTION_SIGNATURE.equals(loadOption) && refImage != null
&& refImage.exists()) {
FileUtils.copyFile(refImage, savepointImage);
}
drawView.reset();
drawView.invalidate();
}
private void CancelAndClose() {
setResult(Activity.RESULT_CANCELED);
this.finish();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "onKeyDown.KEYCODE_BACK", "quit");
createQuitDrawDialog();
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (event.isAltPressed()) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"onKeyDown.KEYCODE_DPAD_RIGHT", "showNext");
createQuitDrawDialog();
return true;
}
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (event.isAltPressed()) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onKeyDown.KEYCODE_DPAD_LEFT",
"showPrevious");
createQuitDrawDialog();
return true;
}
break;
}
return super.onKeyDown(keyCode, event);
}
/**
* Create a dialog with options to save and exit, save, or quit without
* saving
*/
private void createQuitDrawDialog() {
String[] items = { getString(R.string.keep_changes),
getString(R.string.do_not_save) };
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "createQuitDrawDialog", "show");
alertDialog = new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_info)
.setTitle(alertTitleString)
.setNeutralButton(getString(R.string.do_not_exit),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createQuitDrawDialog",
"cancel");
dialog.cancel();
}
})
.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0: // save and exit
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createQuitDrawDialog",
"saveAndExit");
SaveAndClose();
break;
case 1: // discard changes and exit
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createQuitDrawDialog",
"discardAndExit");
CancelAndClose();
break;
case 2:// do nothing
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createQuitDrawDialog", "cancel");
break;
}
}
}).create();
alertDialog.show();
}
public class DrawView extends View {
private boolean isSignature;
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mCurrentPath;
private Paint mBitmapPaint;
private File mBackgroundBitmapFile;
public DrawView(final Context c) {
super(c);
isSignature = false;
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
mCurrentPath = new Path();
setBackgroundColor(0xFFFFFFFF);
mBackgroundBitmapFile = new File(Collect.TMPDRAWFILE_PATH);
}
public DrawView(Context c, boolean isSignature, File f) {
this(c);
this.isSignature = isSignature;
mBackgroundBitmapFile = f;
}
public void reset() {
Display display = ((WindowManager) getContext().getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
resetImage(screenWidth, screenHeight);
}
public void resetImage(int w, int h) {
if (mBackgroundBitmapFile.exists()) {
mBitmap = FileUtils.getBitmapScaledToDisplay(
mBackgroundBitmapFile, w, h).copy(
Bitmap.Config.ARGB_8888, true);
// mBitmap =
// Bitmap.createScaledBitmap(BitmapFactory.decodeFile(mBackgroundBitmapFile.getPath()),
// w, h, true);
mCanvas = new Canvas(mBitmap);
} else {
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
mCanvas.drawColor(0xFFFFFFFF);
if (isSignature)
drawSignLine();
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
resetImage(w, h);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(0xFFAAAAAA);
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mCurrentPath, paint);
}
private float mX, mY;
private void touch_start(float x, float y) {
mCurrentPath.reset();
mCurrentPath.moveTo(x, y);
mX = x;
mY = y;
}
public void drawSignLine() {
mCanvas.drawLine(0, (int) (mCanvas.getHeight() * .7),
mCanvas.getWidth(), (int) (mCanvas.getHeight() * .7), paint);
}
private void touch_move(float x, float y) {
mCurrentPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
private void touch_up() {
if (mCurrentPath.isEmpty()) {
mCanvas.drawPoint(mX, mY, pointPaint);
} else {
mCurrentPath.lineTo(mX, mY);
// commit the path to our offscreen
mCanvas.drawPath(mCurrentPath, paint);
}
// kill this so we don't double draw
mCurrentPath.reset();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
}
}
}
| 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.activities;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.Map.Entry;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.preferences.AdminPreferencesActivity;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.odk.collect.android.provider.InstanceProviderAPI;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**
* Responsible for displaying buttons to launch the major activities. Launches
* some activities based on returns of others.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class MainMenuActivity extends Activity {
private static final String t = "MainMenuActivity";
private static final int PASSWORD_DIALOG = 1;
// menu options
private static final int MENU_PREFERENCES = Menu.FIRST;
private static final int MENU_ADMIN = Menu.FIRST + 1;
// buttons
private Button mEnterDataButton;
private Button mManageFilesButton;
private Button mSendDataButton;
private Button mReviewDataButton;
private Button mGetFormsButton;
private View mReviewSpacer;
private View mGetFormsSpacer;
private AlertDialog mAlertDialog;
private SharedPreferences mAdminPreferences;
private int mCompletedCount;
private int mSavedCount;
private Cursor mFinalizedCursor;
private Cursor mSavedCursor;
private IncomingHandler mHandler = new IncomingHandler(this);
private MyContentObserver mContentObserver = new MyContentObserver();
private static boolean EXIT = true;
// private static boolean DO_NOT_EXIT = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// must be at the beginning of any activity that can be called from an
// external intent
Log.i(t, "Starting up, creating directories");
try {
Collect.createODKDirs();
} catch (RuntimeException e) {
createErrorDialog(e.getMessage(), EXIT);
return;
}
setContentView(R.layout.main_menu);
{
// dynamically construct the "ODK Collect vA.B" string
TextView mainMenuMessageLabel = (TextView) findViewById(R.id.main_menu_header);
mainMenuMessageLabel.setText(Collect.getInstance()
.getVersionedAppName());
}
setTitle(getString(R.string.app_name) + " > "
+ getString(R.string.main_menu));
File f = new File(Collect.ODK_ROOT + "/collect.settings");
if (f.exists()) {
boolean success = loadSharedPreferencesFromFile(f);
if (success) {
Toast.makeText(this,
"Settings successfully loaded from file",
Toast.LENGTH_LONG).show();
f.delete();
} else {
Toast.makeText(
this,
"Sorry, settings file is corrupt and should be deleted or replaced",
Toast.LENGTH_LONG).show();
}
}
mReviewSpacer = findViewById(R.id.review_spacer);
mGetFormsSpacer = findViewById(R.id.get_forms_spacer);
mAdminPreferences = this.getSharedPreferences(
AdminPreferencesActivity.ADMIN_PREFERENCES, 0);
// enter data button. expects a result.
mEnterDataButton = (Button) findViewById(R.id.enter_data);
mEnterDataButton.setText(getString(R.string.enter_data_button));
mEnterDataButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger()
.logAction(this, "fillBlankForm", "click");
Intent i = new Intent(getApplicationContext(),
FormChooserList.class);
startActivity(i);
}
});
// review data button. expects a result.
mReviewDataButton = (Button) findViewById(R.id.review_data);
mReviewDataButton.setText(getString(R.string.review_data_button));
mReviewDataButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger()
.logAction(this, "editSavedForm", "click");
Intent i = new Intent(getApplicationContext(),
InstanceChooserList.class);
startActivity(i);
}
});
// send data button. expects a result.
mSendDataButton = (Button) findViewById(R.id.send_data);
mSendDataButton.setText(getString(R.string.send_data_button));
mSendDataButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger()
.logAction(this, "uploadForms", "click");
Intent i = new Intent(getApplicationContext(),
InstanceUploaderList.class);
startActivity(i);
}
});
// manage forms button. no result expected.
mGetFormsButton = (Button) findViewById(R.id.get_forms);
mGetFormsButton.setText(getString(R.string.get_forms));
mGetFormsButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger()
.logAction(this, "downloadBlankForms", "click");
Intent i = new Intent(getApplicationContext(),
FormDownloadList.class);
startActivity(i);
}
});
// manage forms button. no result expected.
mManageFilesButton = (Button) findViewById(R.id.manage_forms);
mManageFilesButton.setText(getString(R.string.manage_files));
mManageFilesButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger()
.logAction(this, "deleteSavedForms", "click");
Intent i = new Intent(getApplicationContext(),
FileManagerTabs.class);
startActivity(i);
}
});
// count for finalized instances
String selection = InstanceColumns.STATUS + "=? or "
+ InstanceColumns.STATUS + "=?";
String selectionArgs[] = { InstanceProviderAPI.STATUS_COMPLETE,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED };
mFinalizedCursor = managedQuery(InstanceColumns.CONTENT_URI, null,
selection, selectionArgs, null);
startManagingCursor(mFinalizedCursor);
mCompletedCount = mFinalizedCursor.getCount();
mFinalizedCursor.registerContentObserver(mContentObserver);
// count for finalized instances
String selectionSaved = InstanceColumns.STATUS + "=?";
String selectionArgsSaved[] = { InstanceProviderAPI.STATUS_INCOMPLETE };
mSavedCursor = managedQuery(InstanceColumns.CONTENT_URI, null,
selectionSaved, selectionArgsSaved, null);
startManagingCursor(mSavedCursor);
mSavedCount = mFinalizedCursor.getCount();
// don't need to set a content observer because it can't change in the
// background
updateButtons();
}
@Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = this.getSharedPreferences(
AdminPreferencesActivity.ADMIN_PREFERENCES, 0);
boolean edit = sharedPreferences.getBoolean(
AdminPreferencesActivity.KEY_EDIT_SAVED, true);
if (!edit) {
mReviewDataButton.setVisibility(View.GONE);
mReviewSpacer.setVisibility(View.GONE);
} else {
mReviewDataButton.setVisibility(View.VISIBLE);
mReviewSpacer.setVisibility(View.VISIBLE);
}
boolean send = sharedPreferences.getBoolean(
AdminPreferencesActivity.KEY_SEND_FINALIZED, true);
if (!send) {
mSendDataButton.setVisibility(View.GONE);
} else {
mSendDataButton.setVisibility(View.VISIBLE);
}
boolean get_blank = sharedPreferences.getBoolean(
AdminPreferencesActivity.KEY_GET_BLANK, true);
if (!get_blank) {
mGetFormsButton.setVisibility(View.GONE);
mGetFormsSpacer.setVisibility(View.GONE);
} else {
mGetFormsButton.setVisibility(View.VISIBLE);
mGetFormsSpacer.setVisibility(View.VISIBLE);
}
boolean delete_saved = sharedPreferences.getBoolean(
AdminPreferencesActivity.KEY_DELETE_SAVED, true);
if (!delete_saved) {
mManageFilesButton.setVisibility(View.GONE);
} else {
mManageFilesButton.setVisibility(View.VISIBLE);
}
}
@Override
protected void onPause() {
super.onPause();
if (mAlertDialog != null && mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Collect.getInstance().getActivityLogger()
.logAction(this, "onCreateOptionsMenu", "show");
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_PREFERENCES, 0,
getString(R.string.general_preferences)).setIcon(
android.R.drawable.ic_menu_preferences);
menu.add(0, MENU_ADMIN, 0, getString(R.string.admin_preferences))
.setIcon(R.drawable.ic_menu_login);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_PREFERENCES:
Collect.getInstance()
.getActivityLogger()
.logAction(this, "onOptionsItemSelected",
"MENU_PREFERENCES");
Intent ig = new Intent(this, PreferencesActivity.class);
startActivity(ig);
return true;
case MENU_ADMIN:
Collect.getInstance().getActivityLogger()
.logAction(this, "onOptionsItemSelected", "MENU_ADMIN");
String pw = mAdminPreferences.getString(
AdminPreferencesActivity.KEY_ADMIN_PW, "");
if ("".equalsIgnoreCase(pw)) {
Intent i = new Intent(getApplicationContext(),
AdminPreferencesActivity.class);
startActivity(i);
} else {
showDialog(PASSWORD_DIALOG);
Collect.getInstance().getActivityLogger()
.logAction(this, "createAdminPasswordDialog", "show");
}
return true;
}
return super.onOptionsItemSelected(item);
}
private void createErrorDialog(String errorMsg, final boolean shouldExit) {
Collect.getInstance().getActivityLogger()
.logAction(this, "createErrorDialog", "show");
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertDialog.setMessage(errorMsg);
DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON1:
Collect.getInstance()
.getActivityLogger()
.logAction(this, "createErrorDialog",
shouldExit ? "exitApplication" : "OK");
if (shouldExit) {
finish();
}
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.ok), errorListener);
mAlertDialog.show();
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PASSWORD_DIALOG:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final AlertDialog passwordDialog = builder.create();
passwordDialog.setTitle(getString(R.string.enter_admin_password));
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
input.setTransformationMethod(PasswordTransformationMethod
.getInstance());
passwordDialog.setView(input, 20, 10, 20, 10);
passwordDialog.setButton(AlertDialog.BUTTON_POSITIVE,
getString(R.string.ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
String value = input.getText().toString();
String pw = mAdminPreferences.getString(
AdminPreferencesActivity.KEY_ADMIN_PW, "");
if (pw.compareTo(value) == 0) {
Intent i = new Intent(getApplicationContext(),
AdminPreferencesActivity.class);
startActivity(i);
input.setText("");
passwordDialog.dismiss();
} else {
Toast.makeText(
MainMenuActivity.this,
getString(R.string.admin_password_incorrect),
Toast.LENGTH_SHORT).show();
Collect.getInstance()
.getActivityLogger()
.logAction(this, "adminPasswordDialog",
"PASSWORD_INCORRECT");
}
}
});
passwordDialog.setButton(AlertDialog.BUTTON_NEGATIVE,
getString(R.string.cancel),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance()
.getActivityLogger()
.logAction(this, "adminPasswordDialog",
"cancel");
input.setText("");
return;
}
});
passwordDialog.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
return passwordDialog;
}
return null;
}
private void updateButtons() {
mFinalizedCursor.requery();
mCompletedCount = mFinalizedCursor.getCount();
if (mCompletedCount > 0) {
mSendDataButton.setText(getString(R.string.send_data_button,
mCompletedCount));
} else {
mSendDataButton.setText(getString(R.string.send_data));
}
mSavedCursor.requery();
mSavedCount = mSavedCursor.getCount();
if (mSavedCount > 0) {
mReviewDataButton.setText(getString(R.string.review_data_button,
mSavedCount));
} else {
mReviewDataButton.setText(getString(R.string.review_data));
}
}
/**
* notifies us that something changed
*
*/
private class MyContentObserver extends ContentObserver {
public MyContentObserver() {
super(null);
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
mHandler.sendEmptyMessage(0);
}
}
/*
* Used to prevent memory leaks
*/
static class IncomingHandler extends Handler {
private final WeakReference<MainMenuActivity> mTarget;
IncomingHandler(MainMenuActivity target) {
mTarget = new WeakReference<MainMenuActivity>(target);
}
@Override
public void handleMessage(Message msg) {
MainMenuActivity target = mTarget.get();
if (target != null) {
target.updateButtons();
}
}
}
private boolean loadSharedPreferencesFromFile(File src) {
// this should probably be in a thread if it ever gets big
boolean res = false;
ObjectInputStream input = null;
try {
input = new ObjectInputStream(new FileInputStream(src));
Editor prefEdit = PreferenceManager.getDefaultSharedPreferences(
this).edit();
prefEdit.clear();
// first object is preferences
Map<String, ?> entries = (Map<String, ?>) input.readObject();
for (Entry<String, ?> entry : entries.entrySet()) {
Object v = entry.getValue();
String key = entry.getKey();
if (v instanceof Boolean)
prefEdit.putBoolean(key, ((Boolean) v).booleanValue());
else if (v instanceof Float)
prefEdit.putFloat(key, ((Float) v).floatValue());
else if (v instanceof Integer)
prefEdit.putInt(key, ((Integer) v).intValue());
else if (v instanceof Long)
prefEdit.putLong(key, ((Long) v).longValue());
else if (v instanceof String)
prefEdit.putString(key, ((String) v));
}
prefEdit.commit();
// second object is admin options
Editor adminEdit = getSharedPreferences(AdminPreferencesActivity.ADMIN_PREFERENCES, 0).edit();
adminEdit.clear();
// first object is preferences
Map<String, ?> adminEntries = (Map<String, ?>) input.readObject();
for (Entry<String, ?> entry : adminEntries.entrySet()) {
Object v = entry.getValue();
String key = entry.getKey();
if (v instanceof Boolean)
adminEdit.putBoolean(key, ((Boolean) v).booleanValue());
else if (v instanceof Float)
adminEdit.putFloat(key, ((Float) v).floatValue());
else if (v instanceof Integer)
adminEdit.putInt(key, ((Integer) v).intValue());
else if (v instanceof Long)
adminEdit.putLong(key, ((Long) v).longValue());
else if (v instanceof String)
adminEdit.putString(key, ((String) v));
}
adminEdit.commit();
res = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return res;
}
}
| 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.activities;
import java.util.ArrayList;
import org.odk.collect.android.R;
import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
/**
* Allows the user to create desktop shortcuts to any form currently avaiable to Collect
*
* @author ctsims
* @author carlhartung (modified for ODK)
*/
public class AndroidShortcuts extends Activity {
private Uri[] mCommands;
private String[] mNames;
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
final Intent intent = getIntent();
final String action = intent.getAction();
// The Android needs to know what shortcuts are available, generate the list
if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) {
buildMenuList();
}
}
/**
* Builds a list of shortcuts
*/
private void buildMenuList() {
ArrayList<String> names = new ArrayList<String>();
ArrayList<Uri> commands = new ArrayList<Uri>();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select ODK Shortcut");
Cursor c = null;
try {
c = getContentResolver().query(FormsColumns.CONTENT_URI, null, null, null, null);
if (c.getCount() > 0) {
c.moveToPosition(-1);
while (c.moveToNext()) {
String formName = c.getString(c.getColumnIndex(FormsColumns.DISPLAY_NAME));
names.add(formName);
Uri uri =
Uri.withAppendedPath(FormsColumns.CONTENT_URI,
c.getString(c.getColumnIndex(FormsColumns._ID)));
commands.add(uri);
}
}
} finally {
if ( c != null ) {
c.close();
}
}
mNames = names.toArray(new String[0]);
mCommands = commands.toArray(new Uri[0]);
builder.setItems(this.mNames, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
returnShortcut(mNames[item], mCommands[item]);
}
});
builder.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
AndroidShortcuts sc = AndroidShortcuts.this;
sc.setResult(RESULT_CANCELED);
sc.finish();
return;
}
});
AlertDialog alert = builder.create();
alert.show();
}
/**
* Returns the results to the calling intent.
*/
private void returnShortcut(String name, Uri command) {
Intent shortcutIntent = new Intent(Intent.ACTION_VIEW);
shortcutIntent.setData(command);
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
Parcelable iconResource = Intent.ShortcutIconResource.fromContext(this, R.drawable.notes);
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
// Now, return the result to the launcher
setResult(RESULT_OK, intent);
finish();
return;
}
}
| 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.activities;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.preferences.PreferencesActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class SplashScreenActivity extends Activity {
private static final int mSplashTimeout = 2000; // milliseconds
private static final boolean EXIT = true;
private int mImageMaxWidth;
private AlertDialog mAlertDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// must be at the beginning of any activity that can be called from an external intent
try {
Collect.createODKDirs();
} catch (RuntimeException e) {
createErrorDialog(e.getMessage(), EXIT);
return;
}
mImageMaxWidth = getWindowManager().getDefaultDisplay().getWidth();
// this splash screen should be a blank slate
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash_screen);
// get the shared preferences object
SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = mSharedPreferences.edit();
// get the package info object with version number
PackageInfo packageInfo = null;
try {
packageInfo =
getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
boolean firstRun = mSharedPreferences.getBoolean(PreferencesActivity.KEY_FIRST_RUN, true);
boolean showSplash =
mSharedPreferences.getBoolean(PreferencesActivity.KEY_SHOW_SPLASH, false);
String splashPath =
mSharedPreferences.getString(PreferencesActivity.KEY_SPLASH_PATH,
getString(R.string.default_splash_path));
// if you've increased version code, then update the version number and set firstRun to true
if (mSharedPreferences.getLong(PreferencesActivity.KEY_LAST_VERSION, 0) < packageInfo.versionCode) {
editor.putLong(PreferencesActivity.KEY_LAST_VERSION, packageInfo.versionCode);
editor.commit();
firstRun = true;
}
// do all the first run things
if (firstRun || showSplash) {
editor.putBoolean(PreferencesActivity.KEY_FIRST_RUN, false);
editor.commit();
startSplashScreen(splashPath);
} else {
endSplashScreen();
}
}
private void endSplashScreen() {
// launch new activity and close splash screen
startActivity(new Intent(SplashScreenActivity.this, MainMenuActivity.class));
finish();
}
// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
Bitmap b = null;
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int scale = 1;
if (o.outHeight > mImageMaxWidth || o.outWidth > mImageMaxWidth) {
scale =
(int) Math.pow(
2,
(int) Math.round(Math.log(mImageMaxWidth
/ (double) Math.max(o.outHeight, o.outWidth))
/ Math.log(0.5)));
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
}
return b;
}
private void startSplashScreen(String path) {
// add items to the splash screen here. makes things less distracting.
ImageView iv = (ImageView) findViewById(R.id.splash);
LinearLayout ll = (LinearLayout) findViewById(R.id.splash_default);
File f = new File(path);
if (f.exists()) {
iv.setImageBitmap(decodeFile(f));
ll.setVisibility(View.GONE);
iv.setVisibility(View.VISIBLE);
}
// create a thread that counts up to the timeout
Thread t = new Thread() {
int count = 0;
@Override
public void run() {
try {
super.run();
while (count < mSplashTimeout) {
sleep(100);
count += 100;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
endSplashScreen();
}
}
};
t.start();
}
private void createErrorDialog(String errorMsg, final boolean shouldExit) {
Collect.getInstance().getActivityLogger().logAction(this, "createErrorDialog", "show");
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertDialog.setMessage(errorMsg);
DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON1:
Collect.getInstance().getActivityLogger().logAction(this, "createErrorDialog", "OK");
if (shouldExit) {
finish();
}
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.ok), errorListener);
mAlertDialog.show();
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
}
| 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.activities;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.DiskSyncListener;
import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns;
import org.odk.collect.android.tasks.DiskSyncTask;
import org.odk.collect.android.utilities.VersionHidingCursorAdapter;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
/**
* Responsible for displaying all the valid forms in the forms directory. Stores the path to
* selected form for use by {@link MainMenuActivity}.
*
* @author Yaw Anokwa (yanokwa@gmail.com)
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class FormChooserList extends ListActivity implements DiskSyncListener {
private static final String t = "FormChooserList";
private static final boolean EXIT = true;
private static final String syncMsgKey = "syncmsgkey";
private DiskSyncTask mDiskSyncTask;
private AlertDialog mAlertDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// must be at the beginning of any activity that can be called from an external intent
try {
Collect.createODKDirs();
} catch (RuntimeException e) {
createErrorDialog(e.getMessage(), EXIT);
return;
}
setContentView(R.layout.chooser_list_layout);
setTitle(getString(R.string.app_name) + " > " + getString(R.string.enter_data));
String sortOrder = FormsColumns.DISPLAY_NAME + " ASC, " + FormsColumns.JR_VERSION + " DESC";
Cursor c = managedQuery(FormsColumns.CONTENT_URI, null, null, null, sortOrder);
String[] data = new String[] {
FormsColumns.DISPLAY_NAME, FormsColumns.DISPLAY_SUBTEXT, FormsColumns.JR_VERSION
};
int[] view = new int[] {
R.id.text1, R.id.text2, R.id.text3
};
// render total instance view
SimpleCursorAdapter instances =
new VersionHidingCursorAdapter(FormsColumns.JR_VERSION, this, R.layout.two_item, c, data, view);
setListAdapter(instances);
if (savedInstanceState != null && savedInstanceState.containsKey(syncMsgKey)) {
TextView tv = (TextView) findViewById(R.id.status_text);
tv.setText(savedInstanceState.getString(syncMsgKey));
}
// DiskSyncTask checks the disk for any forms not already in the content provider
// that is, put here by dragging and dropping onto the SDCard
mDiskSyncTask = (DiskSyncTask) getLastNonConfigurationInstance();
if (mDiskSyncTask == null) {
Log.i(t, "Starting new disk sync task");
mDiskSyncTask = new DiskSyncTask();
mDiskSyncTask.setDiskSyncListener(this);
mDiskSyncTask.execute((Void[]) null);
}
}
@Override
public Object onRetainNonConfigurationInstance() {
// pass the thread on restart
return mDiskSyncTask;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
TextView tv = (TextView) findViewById(R.id.status_text);
outState.putString(syncMsgKey, tv.getText().toString());
}
/**
* Stores the path of selected form and finishes.
*/
@Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
// get uri to form
long idFormsTable = ((SimpleCursorAdapter) getListAdapter()).getItemId(position);
Uri formUri = ContentUris.withAppendedId(FormsColumns.CONTENT_URI, idFormsTable);
Collect.getInstance().getActivityLogger().logAction(this, "onListItemClick", formUri.toString());
String action = getIntent().getAction();
if (Intent.ACTION_PICK.equals(action)) {
// caller is waiting on a picked form
setResult(RESULT_OK, new Intent().setData(formUri));
} else {
// caller wants to view/edit a form, so launch formentryactivity
startActivity(new Intent(Intent.ACTION_EDIT, formUri));
}
finish();
}
@Override
protected void onResume() {
mDiskSyncTask.setDiskSyncListener(this);
super.onResume();
if (mDiskSyncTask.getStatus() == AsyncTask.Status.FINISHED) {
SyncComplete(mDiskSyncTask.getStatusMessage());
}
}
@Override
protected void onPause() {
mDiskSyncTask.setDiskSyncListener(null);
super.onPause();
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
/**
* Called by DiskSyncTask when the task is finished
*/
@Override
public void SyncComplete(String result) {
Log.i(t, "disk sync task complete");
TextView tv = (TextView) findViewById(R.id.status_text);
tv.setText(result);
}
/**
* Creates a dialog with the given message. Will exit the activity when the user preses "ok" if
* shouldExit is set to true.
*
* @param errorMsg
* @param shouldExit
*/
private void createErrorDialog(String errorMsg, final boolean shouldExit) {
Collect.getInstance().getActivityLogger().logAction(this, "createErrorDialog", "show");
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertDialog.setMessage(errorMsg);
DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON1:
Collect.getInstance().getActivityLogger().logAction(this, "createErrorDialog",
shouldExit ? "exitApplication" : "OK");
if (shouldExit) {
finish();
}
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.ok), errorListener);
mAlertDialog.show();
}
}
| 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.activities;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.InstanceUploaderListener;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import org.odk.collect.android.tasks.InstanceUploaderTask;
import org.odk.collect.android.utilities.WebUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
/**
* Activity to upload completed forms.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class InstanceUploaderActivity extends Activity implements InstanceUploaderListener {
private final static String t = "InstanceUploaderActivity";
private final static int PROGRESS_DIALOG = 1;
private final static int AUTH_DIALOG = 2;
private final static String AUTH_URI = "auth";
private static final String ALERT_MSG = "alertmsg";
private static final String ALERT_SHOWING = "alertshowing";
private static final String TO_SEND = "tosend";
private ProgressDialog mProgressDialog;
private AlertDialog mAlertDialog;
private String mAlertMsg;
private boolean mAlertShowing;
private InstanceUploaderTask mInstanceUploaderTask;
// maintain a list of what we've yet to send, in case we're interrupted by auth requests
private Long[] mInstancesToSend;
// maintain a list of what we've sent, in case we're interrupted by auth requests
private HashMap<String, String> mUploadedInstances;
private String mUrl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(t, "onCreate: " + ((savedInstanceState == null) ? "creating" : "re-initializing"));
mAlertMsg = getString(R.string.please_wait);
mAlertShowing = false;
mUploadedInstances = new HashMap<String, String>();
setTitle(getString(R.string.app_name) + " > " + getString(R.string.send_data));
// get any simple saved state...
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(ALERT_MSG)) {
mAlertMsg = savedInstanceState.getString(ALERT_MSG);
}
if (savedInstanceState.containsKey(ALERT_SHOWING)) {
mAlertShowing = savedInstanceState.getBoolean(ALERT_SHOWING, false);
}
mUrl = savedInstanceState.getString(AUTH_URI);
}
// and if we are resuming, use the TO_SEND list of not-yet-sent submissions
// Otherwise, construct the list from the incoming intent value
long[] selectedInstanceIDs = null;
if (savedInstanceState != null && savedInstanceState.containsKey(TO_SEND)) {
selectedInstanceIDs = savedInstanceState.getLongArray(TO_SEND);
} else {
// get instances to upload...
Intent intent = getIntent();
selectedInstanceIDs = intent.getLongArrayExtra(FormEntryActivity.KEY_INSTANCES);
}
mInstancesToSend = new Long[(selectedInstanceIDs == null) ? 0 : selectedInstanceIDs.length];
if ( selectedInstanceIDs != null ) {
for ( int i = 0 ; i < selectedInstanceIDs.length ; ++i ) {
mInstancesToSend[i] = selectedInstanceIDs[i];
}
}
// at this point, we don't expect this to be empty...
if (mInstancesToSend.length == 0) {
Log.e(t, "onCreate: No instances to upload!");
// drop through -- everything will process through OK
} else {
Log.i(t, "onCreate: Beginning upload of " + mInstancesToSend.length + " instances!");
}
// get the task if we've changed orientations. If it's null it's a new upload.
mInstanceUploaderTask = (InstanceUploaderTask) getLastNonConfigurationInstance();
if (mInstanceUploaderTask == null) {
// setup dialog and upload task
showDialog(PROGRESS_DIALOG);
mInstanceUploaderTask = new InstanceUploaderTask();
// register this activity with the new uploader task
mInstanceUploaderTask.setUploaderListener(InstanceUploaderActivity.this);
mInstanceUploaderTask.execute(mInstancesToSend);
}
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onResume() {
Log.i(t, "onResume: Resuming upload of " + mInstancesToSend.length + " instances!");
if (mInstanceUploaderTask != null) {
mInstanceUploaderTask.setUploaderListener(this);
}
if (mAlertShowing) {
createAlertDialog(mAlertMsg);
}
super.onResume();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(ALERT_MSG, mAlertMsg);
outState.putBoolean(ALERT_SHOWING, mAlertShowing);
outState.putString(AUTH_URI, mUrl);
long[] toSend = new long[mInstancesToSend.length];
for ( int i = 0 ; i < mInstancesToSend.length ; ++i ) {
toSend[i] = mInstancesToSend[i];
}
outState.putLongArray(TO_SEND, toSend);
}
@Override
public Object onRetainNonConfigurationInstance() {
return mInstanceUploaderTask;
}
@Override
protected void onPause() {
Log.i(t, "onPause: Pausing upload of " + mInstancesToSend.length + " instances!");
super.onPause();
if (mAlertDialog != null && mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
@Override
protected void onDestroy() {
if (mInstanceUploaderTask != null) {
mInstanceUploaderTask.setUploaderListener(null);
}
super.onDestroy();
}
@Override
public void uploadingComplete(HashMap<String, String> result) {
Log.i(t, "uploadingComplete: Processing results (" + result.size() + ") from upload of " + mInstancesToSend.length + " instances!");
try {
dismissDialog(PROGRESS_DIALOG);
} catch (Exception e) {
// tried to close a dialog not open. don't care.
}
StringBuilder selection = new StringBuilder();
Set<String> keys = result.keySet();
Iterator<String> it = keys.iterator();
String[] selectionArgs = new String[keys.size()];
int i = 0;
while (it.hasNext()) {
String id = it.next();
selection.append(InstanceColumns._ID + "=?");
selectionArgs[i++] = id;
if (i != keys.size()) {
selection.append(" or ");
}
}
StringBuilder message = new StringBuilder();
{
Cursor results = null;
try {
results = getContentResolver().query(InstanceColumns.CONTENT_URI,
null, selection.toString(), selectionArgs, null);
if (results.getCount() > 0) {
results.moveToPosition(-1);
while (results.moveToNext()) {
String name =
results.getString(results.getColumnIndex(InstanceColumns.DISPLAY_NAME));
String id = results.getString(results.getColumnIndex(InstanceColumns._ID));
message.append(name + " - " + result.get(id) + "\n\n");
}
} else {
message.append(getString(R.string.no_forms_uploaded));
}
} finally {
if ( results != null ) {
results.close();
}
}
}
createAlertDialog(message.toString().trim());
}
@Override
public void progressUpdate(int progress, int total) {
mAlertMsg = getString(R.string.sending_items, progress, total);
mProgressDialog.setMessage(mAlertMsg);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.PROGRESS_DIALOG", "show");
mProgressDialog = new ProgressDialog(this);
DialogInterface.OnClickListener loadingButtonListener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.PROGRESS_DIALOG", "cancel");
dialog.dismiss();
mInstanceUploaderTask.cancel(true);
mInstanceUploaderTask.setUploaderListener(null);
finish();
}
};
mProgressDialog.setTitle(getString(R.string.uploading_data));
mProgressDialog.setMessage(mAlertMsg);
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setCancelable(false);
mProgressDialog.setButton(getString(R.string.cancel), loadingButtonListener);
return mProgressDialog;
case AUTH_DIALOG:
Log.i(t, "onCreateDialog(AUTH_DIALOG): for upload of " + mInstancesToSend.length + " instances!");
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.AUTH_DIALOG", "show");
AlertDialog.Builder b = new AlertDialog.Builder(this);
LayoutInflater factory = LayoutInflater.from(this);
final View dialogView = factory.inflate(R.layout.server_auth_dialog, null);
// Get the server, username, and password from the settings
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String server = mUrl;
if (server == null) {
Log.e(t, "onCreateDialog(AUTH_DIALOG): No failing mUrl specified for upload of " + mInstancesToSend.length + " instances!");
// if the bundle is null, we're looking for a formlist
String submissionUrl = getString(R.string.default_odk_submission);
server =
settings.getString(PreferencesActivity.KEY_SERVER_URL,
getString(R.string.default_server_url))
+ settings.getString(PreferencesActivity.KEY_SUBMISSION_URL, submissionUrl);
}
final String url = server;
Log.i(t, "Trying connecting to: " + url);
EditText username = (EditText) dialogView.findViewById(R.id.username_edit);
String storedUsername = settings.getString(PreferencesActivity.KEY_USERNAME, null);
username.setText(storedUsername);
EditText password = (EditText) dialogView.findViewById(R.id.password_edit);
String storedPassword = settings.getString(PreferencesActivity.KEY_PASSWORD, null);
password.setText(storedPassword);
b.setTitle(getString(R.string.server_requires_auth));
b.setMessage(getString(R.string.server_auth_credentials, url));
b.setView(dialogView);
b.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.AUTH_DIALOG", "OK");
EditText username = (EditText) dialogView.findViewById(R.id.username_edit);
EditText password = (EditText) dialogView.findViewById(R.id.password_edit);
Uri u = Uri.parse(url);
WebUtils.addCredentials(username.getText().toString(), password.getText()
.toString(), u.getHost());
showDialog(PROGRESS_DIALOG);
mInstanceUploaderTask = new InstanceUploaderTask();
// register this activity with the new uploader task
mInstanceUploaderTask.setUploaderListener(InstanceUploaderActivity.this);
mInstanceUploaderTask.execute(mInstancesToSend);
}
});
b.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.AUTH_DIALOG", "cancel");
finish();
}
});
b.setCancelable(false);
return b.create();
}
return null;
}
@Override
public void authRequest(Uri url, HashMap<String, String> doneSoFar) {
if (mProgressDialog.isShowing()) {
// should always be showing here
mProgressDialog.dismiss();
}
// add our list of completed uploads to "completed"
// and remove them from our toSend list.
ArrayList<Long> workingSet = new ArrayList<Long>();
Collections.addAll(workingSet, mInstancesToSend);
if (doneSoFar != null) {
Set<String> uploadedInstances = doneSoFar.keySet();
Iterator<String> itr = uploadedInstances.iterator();
while (itr.hasNext()) {
Long removeMe = Long.valueOf(itr.next());
boolean removed = workingSet.remove(removeMe);
if (removed) {
Log.i(t, removeMe
+ " was already sent, removing from queue before restarting task");
}
}
mUploadedInstances.putAll(doneSoFar);
}
// and reconstruct the pending set of instances to send
Long[] updatedToSend = new Long[workingSet.size()];
for ( int i = 0 ; i < workingSet.size() ; ++i ) {
updatedToSend[i] = workingSet.get(i);
}
mInstancesToSend = updatedToSend;
mUrl = url.toString();
showDialog(AUTH_DIALOG);
}
private void createAlertDialog(String message) {
Collect.getInstance().getActivityLogger().logAction(this, "createAlertDialog", "show");
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setTitle(getString(R.string.upload_results));
mAlertDialog.setMessage(message);
DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON1: // ok
Collect.getInstance().getActivityLogger().logAction(this, "createAlertDialog", "OK");
// always exit this activity since it has no interface
mAlertShowing = false;
finish();
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.ok), quitListener);
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertShowing = true;
mAlertMsg = message;
mAlertDialog.show();
}
}
| 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.activities;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.FormDownloaderListener;
import org.odk.collect.android.listeners.FormListDownloaderListener;
import org.odk.collect.android.logic.FormDetails;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.odk.collect.android.tasks.DownloadFormListTask;
import org.odk.collect.android.tasks.DownloadFormsTask;
import org.odk.collect.android.utilities.WebUtils;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
/**
* Responsible for displaying, adding and deleting all the valid forms in the forms directory. One
* caveat. If the server requires authentication, a dialog will pop up asking when you request the
* form list. If somehow you manage to wait long enough and then try to download selected forms and
* your authorization has timed out, it won't again ask for authentication, it will just throw a 401
* and you'll have to hit 'refresh' where it will ask for credentials again. Technically a server
* could point at other servers requiring authentication to download the forms, but the current
* implementation in Collect doesn't allow for that. Mostly this is just because it's a pain in the
* butt to keep track of which forms we've downloaded and where we're needing to authenticate. I
* think we do something similar in the instanceuploader task/activity, so should change the
* implementation eventually.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class FormDownloadList extends ListActivity implements FormListDownloaderListener,
FormDownloaderListener {
private static final String t = "RemoveFileManageList";
private static final int PROGRESS_DIALOG = 1;
private static final int AUTH_DIALOG = 2;
private static final int MENU_PREFERENCES = Menu.FIRST;
private static final String BUNDLE_TOGGLED_KEY = "toggled";
private static final String BUNDLE_SELECTED_COUNT = "selectedcount";
private static final String BUNDLE_FORM_MAP = "formmap";
private static final String DIALOG_TITLE = "dialogtitle";
private static final String DIALOG_MSG = "dialogmsg";
private static final String DIALOG_SHOWING = "dialogshowing";
private static final String FORMLIST = "formlist";
public static final String LIST_URL = "listurl";
private static final String FORMNAME = "formname";
private static final String FORMDETAIL_KEY = "formdetailkey";
private static final String FORMID_DISPLAY = "formiddisplay";
private String mAlertMsg;
private boolean mAlertShowing = false;
private String mAlertTitle;
private AlertDialog mAlertDialog;
private ProgressDialog mProgressDialog;
private Button mDownloadButton;
private DownloadFormListTask mDownloadFormListTask;
private DownloadFormsTask mDownloadFormsTask;
private Button mToggleButton;
private Button mRefreshButton;
private HashMap<String, FormDetails> mFormNamesAndURLs = new HashMap<String,FormDetails>();
private SimpleAdapter mFormListAdapter;
private ArrayList<HashMap<String, String>> mFormList;
private boolean mToggled = false;
private int mSelectedCount = 0;
private static final boolean EXIT = true;
private static final boolean DO_NOT_EXIT = false;
private boolean mShouldExit;
private static final String SHOULD_EXIT = "shouldexit";
@SuppressWarnings("unchecked")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.remote_file_manage_list);
setTitle(getString(R.string.app_name) + " > " + getString(R.string.get_forms));
mAlertMsg = getString(R.string.please_wait);
// need white background before load
getListView().setBackgroundColor(Color.WHITE);
mDownloadButton = (Button) findViewById(R.id.add_button);
mDownloadButton.setEnabled(selectedItemCount() > 0);
mDownloadButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// this is callled in downloadSelectedFiles():
// Collect.getInstance().getActivityLogger().logAction(this, "downloadSelectedFiles", ...);
downloadSelectedFiles();
mToggled = false;
clearChoices();
}
});
mToggleButton = (Button) findViewById(R.id.toggle_button);
mToggleButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// toggle selections of items to all or none
ListView ls = getListView();
mToggled = !mToggled;
Collect.getInstance().getActivityLogger().logAction(this, "toggleFormCheckbox", Boolean.toString(mToggled));
for (int pos = 0; pos < ls.getCount(); pos++) {
ls.setItemChecked(pos, mToggled);
}
mDownloadButton.setEnabled(!(selectedItemCount() == 0));
}
});
mRefreshButton = (Button) findViewById(R.id.refresh_button);
mRefreshButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logAction(this, "refreshForms", "");
mToggled = false;
downloadFormList();
FormDownloadList.this.getListView().clearChoices();
clearChoices();
}
});
if (savedInstanceState != null) {
// If the screen has rotated, the hashmap with the form ids and urls is passed here.
if (savedInstanceState.containsKey(BUNDLE_FORM_MAP)) {
mFormNamesAndURLs =
(HashMap<String, FormDetails>) savedInstanceState
.getSerializable(BUNDLE_FORM_MAP);
}
// indicating whether or not select-all is on or off.
if (savedInstanceState.containsKey(BUNDLE_TOGGLED_KEY)) {
mToggled = savedInstanceState.getBoolean(BUNDLE_TOGGLED_KEY);
}
// how many items we've selected
// Android should keep track of this, but broken on rotate...
if (savedInstanceState.containsKey(BUNDLE_SELECTED_COUNT)) {
mSelectedCount = savedInstanceState.getInt(BUNDLE_SELECTED_COUNT);
mDownloadButton.setEnabled(!(mSelectedCount == 0));
}
// to restore alert dialog.
if (savedInstanceState.containsKey(DIALOG_TITLE)) {
mAlertTitle = savedInstanceState.getString(DIALOG_TITLE);
}
if (savedInstanceState.containsKey(DIALOG_MSG)) {
mAlertMsg = savedInstanceState.getString(DIALOG_MSG);
}
if (savedInstanceState.containsKey(DIALOG_SHOWING)) {
mAlertShowing = savedInstanceState.getBoolean(DIALOG_SHOWING);
}
if (savedInstanceState.containsKey(SHOULD_EXIT)) {
mShouldExit = savedInstanceState.getBoolean(SHOULD_EXIT);
}
}
if (savedInstanceState != null && savedInstanceState.containsKey(FORMLIST)) {
mFormList =
(ArrayList<HashMap<String, String>>) savedInstanceState.getSerializable(FORMLIST);
} else {
mFormList = new ArrayList<HashMap<String, String>>();
}
if (getLastNonConfigurationInstance() instanceof DownloadFormListTask) {
mDownloadFormListTask = (DownloadFormListTask) getLastNonConfigurationInstance();
if (mDownloadFormListTask.getStatus() == AsyncTask.Status.FINISHED) {
try {
dismissDialog(PROGRESS_DIALOG);
} catch (IllegalArgumentException e) {
Log.i(t, "Attempting to close a dialog that was not previously opened");
}
mDownloadFormsTask = null;
}
} else if (getLastNonConfigurationInstance() instanceof DownloadFormsTask) {
mDownloadFormsTask = (DownloadFormsTask) getLastNonConfigurationInstance();
if (mDownloadFormsTask.getStatus() == AsyncTask.Status.FINISHED) {
try {
dismissDialog(PROGRESS_DIALOG);
} catch (IllegalArgumentException e) {
Log.i(t, "Attempting to close a dialog that was not previously opened");
}
mDownloadFormsTask = null;
}
} else if (getLastNonConfigurationInstance() == null) {
// first time, so get the formlist
downloadFormList();
}
String[] data = new String[] {
FORMNAME, FORMID_DISPLAY, FORMDETAIL_KEY
};
int[] view = new int[] {
R.id.text1, R.id.text2
};
mFormListAdapter =
new SimpleAdapter(this, mFormList, R.layout.two_item_multiple_choice, data, view);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
getListView().setItemsCanFocus(false);
setListAdapter(mFormListAdapter);
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
private void clearChoices() {
FormDownloadList.this.getListView().clearChoices();
mDownloadButton.setEnabled(false);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
mDownloadButton.setEnabled(!(selectedItemCount() == 0));
Object o = getListAdapter().getItem(position);
@SuppressWarnings("unchecked")
HashMap<String, String> item = (HashMap<String, String>) o;
FormDetails detail = mFormNamesAndURLs.get(item.get(FORMDETAIL_KEY));
Collect.getInstance().getActivityLogger().logAction(this, "onListItemClick", detail.downloadUrl);
}
/**
* Starts the download task and shows the progress dialog.
*/
private void downloadFormList() {
ConnectivityManager connectivityManager =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
if (ni == null || !ni.isConnected()) {
Toast.makeText(this, R.string.no_connection, Toast.LENGTH_SHORT).show();
} else {
mFormNamesAndURLs = new HashMap<String, FormDetails>();
if (mProgressDialog != null) {
// This is needed because onPrepareDialog() is broken in 1.6.
mProgressDialog.setMessage(getString(R.string.please_wait));
}
showDialog(PROGRESS_DIALOG);
if (mDownloadFormListTask != null &&
mDownloadFormListTask.getStatus() != AsyncTask.Status.FINISHED) {
return; // we are already doing the download!!!
} else if (mDownloadFormListTask != null) {
mDownloadFormListTask.setDownloaderListener(null);
mDownloadFormListTask.cancel(true);
mDownloadFormListTask = null;
}
mDownloadFormListTask = new DownloadFormListTask();
mDownloadFormListTask.setDownloaderListener(this);
mDownloadFormListTask.execute();
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(BUNDLE_TOGGLED_KEY, mToggled);
outState.putInt(BUNDLE_SELECTED_COUNT, selectedItemCount());
outState.putSerializable(BUNDLE_FORM_MAP, mFormNamesAndURLs);
outState.putString(DIALOG_TITLE, mAlertTitle);
outState.putString(DIALOG_MSG, mAlertMsg);
outState.putBoolean(DIALOG_SHOWING, mAlertShowing);
outState.putBoolean(SHOULD_EXIT, mShouldExit);
outState.putSerializable(FORMLIST, mFormList);
}
/**
* returns the number of items currently selected in the list.
*
* @return
*/
private int selectedItemCount() {
int count = 0;
SparseBooleanArray sba = getListView().getCheckedItemPositions();
for (int i = 0; i < getListView().getCount(); i++) {
if (sba.get(i, false)) {
count++;
}
}
return count;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Collect.getInstance().getActivityLogger().logAction(this, "onCreateOptionsMenu", "show");
menu.add(0, MENU_PREFERENCES, 0, getString(R.string.general_preferences)).setIcon(
android.R.drawable.ic_menu_preferences);
return true;
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case MENU_PREFERENCES:
Collect.getInstance().getActivityLogger().logAction(this, "onMenuItemSelected", "MENU_PREFERENCES");
Intent i = new Intent(this, PreferencesActivity.class);
startActivity(i);
return true;
}
return super.onMenuItemSelected(featureId, item);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.PROGRESS_DIALOG", "show");
mProgressDialog = new ProgressDialog(this);
DialogInterface.OnClickListener loadingButtonListener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.PROGRESS_DIALOG", "OK");
dialog.dismiss();
// we use the same progress dialog for both
// so whatever isn't null is running
if (mDownloadFormListTask != null) {
mDownloadFormListTask.setDownloaderListener(null);
mDownloadFormListTask.cancel(true);
mDownloadFormListTask = null;
}
if (mDownloadFormsTask != null) {
mDownloadFormsTask.setDownloaderListener(null);
mDownloadFormsTask.cancel(true);
mDownloadFormsTask = null;
}
}
};
mProgressDialog.setTitle(getString(R.string.downloading_data));
mProgressDialog.setMessage(mAlertMsg);
mProgressDialog.setIcon(android.R.drawable.ic_dialog_info);
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setButton(getString(R.string.cancel), loadingButtonListener);
return mProgressDialog;
case AUTH_DIALOG:
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.AUTH_DIALOG", "show");
AlertDialog.Builder b = new AlertDialog.Builder(this);
LayoutInflater factory = LayoutInflater.from(this);
final View dialogView = factory.inflate(R.layout.server_auth_dialog, null);
// Get the server, username, and password from the settings
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String server =
settings.getString(PreferencesActivity.KEY_SERVER_URL,
getString(R.string.default_server_url));
String formListUrl = getString(R.string.default_odk_formlist);
final String url =
server + settings.getString(PreferencesActivity.KEY_FORMLIST_URL, formListUrl);
Log.i(t, "Trying to get formList from: " + url);
EditText username = (EditText) dialogView.findViewById(R.id.username_edit);
String storedUsername = settings.getString(PreferencesActivity.KEY_USERNAME, null);
username.setText(storedUsername);
EditText password = (EditText) dialogView.findViewById(R.id.password_edit);
String storedPassword = settings.getString(PreferencesActivity.KEY_PASSWORD, null);
password.setText(storedPassword);
b.setTitle(getString(R.string.server_requires_auth));
b.setMessage(getString(R.string.server_auth_credentials, url));
b.setView(dialogView);
b.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.AUTH_DIALOG", "OK");
EditText username = (EditText) dialogView.findViewById(R.id.username_edit);
EditText password = (EditText) dialogView.findViewById(R.id.password_edit);
Uri u = Uri.parse(url);
WebUtils.addCredentials(username.getText().toString(), password.getText()
.toString(), u.getHost());
downloadFormList();
}
});
b.setNegativeButton(getString(R.string.cancel),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.AUTH_DIALOG", "Cancel");
finish();
}
});
b.setCancelable(false);
mAlertShowing = false;
return b.create();
}
return null;
}
/**
* starts the task to download the selected forms, also shows progress dialog
*/
@SuppressWarnings("unchecked")
private void downloadSelectedFiles() {
int totalCount = 0;
ArrayList<FormDetails> filesToDownload = new ArrayList<FormDetails>();
SparseBooleanArray sba = getListView().getCheckedItemPositions();
for (int i = 0; i < getListView().getCount(); i++) {
if (sba.get(i, false)) {
HashMap<String, String> item =
(HashMap<String, String>) getListAdapter().getItem(i);
filesToDownload.add(mFormNamesAndURLs.get(item.get(FORMDETAIL_KEY)));
}
}
totalCount = filesToDownload.size();
Collect.getInstance().getActivityLogger().logAction(this, "downloadSelectedFiles", Integer.toString(totalCount));
if (totalCount > 0) {
// show dialog box
showDialog(PROGRESS_DIALOG);
mDownloadFormsTask = new DownloadFormsTask();
mDownloadFormsTask.setDownloaderListener(this);
mDownloadFormsTask.execute(filesToDownload);
} else {
Toast.makeText(getApplicationContext(), R.string.noselect_error, Toast.LENGTH_SHORT)
.show();
}
}
@Override
public Object onRetainNonConfigurationInstance() {
if (mDownloadFormsTask != null) {
return mDownloadFormsTask;
} else {
return mDownloadFormListTask;
}
}
@Override
protected void onDestroy() {
if (mDownloadFormListTask != null) {
mDownloadFormListTask.setDownloaderListener(null);
}
if (mDownloadFormsTask != null) {
mDownloadFormsTask.setDownloaderListener(null);
}
super.onDestroy();
}
@Override
protected void onResume() {
if (mDownloadFormListTask != null) {
mDownloadFormListTask.setDownloaderListener(this);
}
if (mDownloadFormsTask != null) {
mDownloadFormsTask.setDownloaderListener(this);
}
if (mAlertShowing) {
createAlertDialog(mAlertTitle, mAlertMsg, mShouldExit);
}
super.onResume();
}
@Override
protected void onPause() {
if (mAlertDialog != null && mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
super.onPause();
}
/**
* Called when the form list has finished downloading. results will either contain a set of
* <formname, formdetails> tuples, or one tuple of DL.ERROR.MSG and the associated message.
*
* @param result
*/
public void formListDownloadingComplete(HashMap<String, FormDetails> result) {
dismissDialog(PROGRESS_DIALOG);
mDownloadFormListTask.setDownloaderListener(null);
mDownloadFormListTask = null;
if (result == null) {
Log.e(t, "Formlist Downloading returned null. That shouldn't happen");
// Just displayes "error occured" to the user, but this should never happen.
createAlertDialog(getString(R.string.load_remote_form_error),
getString(R.string.error_occured), EXIT);
return;
}
if (result.containsKey(DownloadFormListTask.DL_AUTH_REQUIRED)) {
// need authorization
showDialog(AUTH_DIALOG);
} else if (result.containsKey(DownloadFormListTask.DL_ERROR_MSG)) {
// Download failed
String dialogMessage =
getString(R.string.list_failed_with_error,
result.get(DownloadFormListTask.DL_ERROR_MSG).errorStr);
String dialogTitle = getString(R.string.load_remote_form_error);
createAlertDialog(dialogTitle, dialogMessage, DO_NOT_EXIT);
} else {
// Everything worked. Clear the list and add the results.
mFormNamesAndURLs = result;
mFormList.clear();
ArrayList<String> ids = new ArrayList<String>(mFormNamesAndURLs.keySet());
for (int i = 0; i < result.size(); i++) {
String formDetailsKey = ids.get(i);
FormDetails details = mFormNamesAndURLs.get(formDetailsKey);
HashMap<String, String> item = new HashMap<String, String>();
item.put(FORMNAME, details.formName);
item.put(FORMID_DISPLAY,
((details.formVersion == null) ? "" : (getString(R.string.version) + " " + details.formVersion + " ")) +
"ID: " + details.formID );
item.put(FORMDETAIL_KEY, formDetailsKey);
// Insert the new form in alphabetical order.
if (mFormList.size() == 0) {
mFormList.add(item);
} else {
int j;
for (j = 0; j < mFormList.size(); j++) {
HashMap<String, String> compareMe = mFormList.get(j);
String name = compareMe.get(FORMNAME);
if (name.compareTo(mFormNamesAndURLs.get(ids.get(i)).formName) > 0) {
break;
}
}
mFormList.add(j, item);
}
}
mFormListAdapter.notifyDataSetChanged();
}
}
/**
* Creates an alert dialog with the given tite and message. If shouldExit is set to true, the
* activity will exit when the user clicks "ok".
*
* @param title
* @param message
* @param shouldExit
*/
private void createAlertDialog(String title, String message, final boolean shouldExit) {
Collect.getInstance().getActivityLogger().logAction(this, "createAlertDialog", "show");
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setTitle(title);
mAlertDialog.setMessage(message);
DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON1: // ok
Collect.getInstance().getActivityLogger().logAction(this, "createAlertDialog", "OK");
// just close the dialog
mAlertShowing = false;
// successful download, so quit
if (shouldExit) {
finish();
}
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.ok), quitListener);
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertMsg = message;
mAlertTitle = title;
mAlertShowing = true;
mShouldExit = shouldExit;
mAlertDialog.show();
}
@Override
public void progressUpdate(String currentFile, int progress, int total) {
mAlertMsg = getString(R.string.fetching_file, currentFile, progress, total);
mProgressDialog.setMessage(mAlertMsg);
}
@Override
public void formsDownloadingComplete(HashMap<FormDetails, String> result) {
if (mDownloadFormsTask != null) {
mDownloadFormsTask.setDownloaderListener(null);
}
if (mProgressDialog.isShowing()) {
// should always be true here
mProgressDialog.dismiss();
}
Set<FormDetails> keys = result.keySet();
StringBuilder b = new StringBuilder();
for (FormDetails k : keys) {
b.append(k.formName +
" (" +
((k.formVersion != null) ?
(this.getString(R.string.version) + ": " + k.formVersion + " ")
: "") +
"ID: " + k.formID + ") - " +
result.get(k));
b.append("\n\n");
}
createAlertDialog(getString(R.string.download_forms_result), b.toString().trim(), EXIT);
}
}
| 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.adapters;
import org.odk.collect.android.logic.HierarchyElement;
import org.odk.collect.android.views.HierarchyElementView;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import java.util.ArrayList;
import java.util.List;
public class HierarchyListAdapter extends BaseAdapter {
private Context mContext;
private List<HierarchyElement> mItems = new ArrayList<HierarchyElement>();
public HierarchyListAdapter(Context context) {
mContext = context;
}
@Override
public int getCount() {
return mItems.size();
}
@Override
public Object getItem(int position) {
return mItems.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
HierarchyElementView hev;
if (convertView == null) {
hev = new HierarchyElementView(mContext, mItems.get(position));
} else {
hev = (HierarchyElementView) convertView;
hev.setPrimaryText(mItems.get(position).getPrimaryText());
hev.setSecondaryText(mItems.get(position).getSecondaryText());
hev.setIcon(mItems.get(position).getIcon());
hev.setColor(mItems.get(position).getColor());
}
if (mItems.get(position).getSecondaryText() == null
|| mItems.get(position).getSecondaryText().equals("")) {
hev.showSecondary(false);
} else {
hev.showSecondary(true);
}
return hev;
}
/**
* Sets the list of items for this adapter to use.
*/
public void setListItems(List<HierarchyElement> it) {
mItems = it;
}
}
| Java |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.odk.collect.android.provider;
import android.net.Uri;
import android.provider.BaseColumns;
/**
* Convenience definitions for NotePadProvider
*/
public final class InstanceProviderAPI {
public static final String AUTHORITY = "org.odk.collect.android.provider.odk.instances";
// This class cannot be instantiated
private InstanceProviderAPI() {}
// status for instances
public static final String STATUS_INCOMPLETE = "incomplete";
public static final String STATUS_COMPLETE = "complete";
public static final String STATUS_SUBMITTED = "submitted";
public static final String STATUS_SUBMISSION_FAILED = "submissionFailed";
/**
* Notes table
*/
public static final class InstanceColumns implements BaseColumns {
// This class cannot be instantiated
private InstanceColumns() {}
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/instances");
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.odk.instance";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.odk.instance";
// These are the only things needed for an insert
public static final String DISPLAY_NAME = "displayName";
public static final String SUBMISSION_URI = "submissionUri";
public static final String INSTANCE_FILE_PATH = "instanceFilePath";
public static final String JR_FORM_ID = "jrFormId";
public static final String JR_VERSION = "jrVersion";
//public static final String FORM_ID = "formId";
// these are generated for you (but you can insert something else if you want)
public static final String STATUS = "status";
public static final String CAN_EDIT_WHEN_COMPLETE = "canEditWhenComplete";
public static final String LAST_STATUS_CHANGE_DATE = "date";
public static final String DISPLAY_SUBTEXT = "displaySubtext";
//public static final String DISPLAY_SUB_SUBTEXT = "displaySubSubtext";
// public static final String DEFAULT_SORT_ORDER = "modified DESC";
// public static final String TITLE = "title";
// public static final String NOTE = "note";
// public static final String CREATED_DATE = "created";
// public static final String MODIFIED_DATE = "modified";
}
}
| Java |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.provider;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.database.ODKSQLiteOpenHelper;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import org.odk.collect.android.utilities.MediaUtils;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
/**
*
*/
public class InstanceProvider extends ContentProvider {
private static final String t = "InstancesProvider";
private static final String DATABASE_NAME = "instances.db";
private static final int DATABASE_VERSION = 3;
private static final String INSTANCES_TABLE_NAME = "instances";
private static HashMap<String, String> sInstancesProjectionMap;
private static final int INSTANCES = 1;
private static final int INSTANCE_ID = 2;
private static final UriMatcher sUriMatcher;
/**
* This class helps open, create, and upgrade the database file.
*/
private static class DatabaseHelper extends ODKSQLiteOpenHelper {
DatabaseHelper(String databaseName) {
super(Collect.METADATA_PATH, databaseName, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + INSTANCES_TABLE_NAME + " ("
+ InstanceColumns._ID + " integer primary key, "
+ InstanceColumns.DISPLAY_NAME + " text not null, "
+ InstanceColumns.SUBMISSION_URI + " text, "
+ InstanceColumns.CAN_EDIT_WHEN_COMPLETE + " text, "
+ InstanceColumns.INSTANCE_FILE_PATH + " text not null, "
+ InstanceColumns.JR_FORM_ID + " text not null, "
+ InstanceColumns.JR_VERSION + " text, "
+ InstanceColumns.STATUS + " text not null, "
+ InstanceColumns.LAST_STATUS_CHANGE_DATE + " date not null, "
+ InstanceColumns.DISPLAY_SUBTEXT + " text not null );");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
int initialVersion = oldVersion;
if ( oldVersion == 1 ) {
db.execSQL("ALTER TABLE " + INSTANCES_TABLE_NAME + " ADD COLUMN " +
InstanceColumns.CAN_EDIT_WHEN_COMPLETE + " text;");
db.execSQL("UPDATE " + INSTANCES_TABLE_NAME + " SET " +
InstanceColumns.CAN_EDIT_WHEN_COMPLETE + " = '" + Boolean.toString(true) + "' WHERE " +
InstanceColumns.STATUS + " IS NOT NULL AND " +
InstanceColumns.STATUS + " != '" + InstanceProviderAPI.STATUS_INCOMPLETE + "'");
oldVersion = 2;
}
if ( oldVersion == 2 ) {
db.execSQL("ALTER TABLE " + INSTANCES_TABLE_NAME + " ADD COLUMN " +
InstanceColumns.JR_VERSION + " text;");
}
Log.w(t, "Successfully upgraded database from version " + initialVersion + " to " + newVersion
+ ", without destroying all the old data");
}
}
private DatabaseHelper mDbHelper;
@Override
public boolean onCreate() {
// must be at the beginning of any activity that can be called from an external intent
Collect.createODKDirs();
mDbHelper = new DatabaseHelper(DATABASE_NAME);
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(INSTANCES_TABLE_NAME);
switch (sUriMatcher.match(uri)) {
case INSTANCES:
qb.setProjectionMap(sInstancesProjectionMap);
break;
case INSTANCE_ID:
qb.setProjectionMap(sInstancesProjectionMap);
qb.appendWhere(InstanceColumns._ID + "=" + uri.getPathSegments().get(1));
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
// Get the database and run the query
SQLiteDatabase db = mDbHelper.getReadableDatabase();
Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
// Tell the cursor what uri to watch, so it knows when its source data changes
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
@Override
public String getType(Uri uri) {
switch (sUriMatcher.match(uri)) {
case INSTANCES:
return InstanceColumns.CONTENT_TYPE;
case INSTANCE_ID:
return InstanceColumns.CONTENT_ITEM_TYPE;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
}
@Override
public Uri insert(Uri uri, ContentValues initialValues) {
// Validate the requested uri
if (sUriMatcher.match(uri) != INSTANCES) {
throw new IllegalArgumentException("Unknown URI " + uri);
}
ContentValues values;
if (initialValues != null) {
values = new ContentValues(initialValues);
} else {
values = new ContentValues();
}
Long now = Long.valueOf(System.currentTimeMillis());
// Make sure that the fields are all set
if (values.containsKey(InstanceColumns.LAST_STATUS_CHANGE_DATE) == false) {
values.put(InstanceColumns.LAST_STATUS_CHANGE_DATE, now);
}
if (values.containsKey(InstanceColumns.DISPLAY_SUBTEXT) == false) {
Date today = new Date();
String text = getDisplaySubtext(InstanceProviderAPI.STATUS_INCOMPLETE, today);
values.put(InstanceColumns.DISPLAY_SUBTEXT, text);
}
if (values.containsKey(InstanceColumns.STATUS) == false) {
values.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_INCOMPLETE);
}
SQLiteDatabase db = mDbHelper.getWritableDatabase();
long rowId = db.insert(INSTANCES_TABLE_NAME, null, values);
if (rowId > 0) {
Uri instanceUri = ContentUris.withAppendedId(InstanceColumns.CONTENT_URI, rowId);
getContext().getContentResolver().notifyChange(instanceUri, null);
Collect.getInstance().getActivityLogger().logActionParam(this, "insert",
instanceUri.toString(), values.getAsString(InstanceColumns.INSTANCE_FILE_PATH));
return instanceUri;
}
throw new SQLException("Failed to insert row into " + uri);
}
private String getDisplaySubtext(String state, Date date) {
if (state == null) {
return new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time), Locale.getDefault()).format(date);
} else if (InstanceProviderAPI.STATUS_INCOMPLETE.equalsIgnoreCase(state)) {
return new SimpleDateFormat(getContext().getString(R.string.saved_on_date_at_time), Locale.getDefault()).format(date);
} else if (InstanceProviderAPI.STATUS_COMPLETE.equalsIgnoreCase(state)) {
return new SimpleDateFormat(getContext().getString(R.string.finalized_on_date_at_time), Locale.getDefault()).format(date);
} else if (InstanceProviderAPI.STATUS_SUBMITTED.equalsIgnoreCase(state)) {
return new SimpleDateFormat(getContext().getString(R.string.sent_on_date_at_time), Locale.getDefault()).format(date);
} else if (InstanceProviderAPI.STATUS_SUBMISSION_FAILED.equalsIgnoreCase(state)) {
return new SimpleDateFormat(getContext().getString(R.string.sending_failed_on_date_at_time), Locale.getDefault()).format(date);
} else {
return new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time), Locale.getDefault()).format(date);
}
}
private void deleteAllFilesInDirectory(File directory) {
if (directory.exists()) {
if (directory.isDirectory()) {
// delete any media entries for files in this directory...
int images = MediaUtils.deleteImagesInFolderFromMediaProvider(directory);
int audio = MediaUtils.deleteAudioInFolderFromMediaProvider(directory);
int video = MediaUtils.deleteVideoInFolderFromMediaProvider(directory);
Log.i(t, "removed from content providers: " + images
+ " image files, " + audio + " audio files,"
+ " and " + video + " video files.");
// delete all the files in the directory
File[] files = directory.listFiles();
for (File f : files) {
// should make this recursive if we get worried about
// the media directory containing directories
f.delete();
}
}
directory.delete();
}
}
/**
* This method removes the entry from the content provider, and also removes any associated files.
* files: form.xml, [formmd5].formdef, formname-media {directory}
*/
@Override
public int delete(Uri uri, String where, String[] whereArgs) {
SQLiteDatabase db = mDbHelper.getWritableDatabase();
int count;
switch (sUriMatcher.match(uri)) {
case INSTANCES:
Cursor del = null;
try {
del = this.query(uri, null, where, whereArgs, null);
del.moveToPosition(-1);
while (del.moveToNext()) {
String instanceFile = del.getString(del.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
Collect.getInstance().getActivityLogger().logAction(this, "delete", instanceFile);
File instanceDir = (new File(instanceFile)).getParentFile();
deleteAllFilesInDirectory(instanceDir);
}
} finally {
if ( del != null ) {
del.close();
}
}
count = db.delete(INSTANCES_TABLE_NAME, where, whereArgs);
break;
case INSTANCE_ID:
String instanceId = uri.getPathSegments().get(1);
Cursor c = null;
try {
c = this.query(uri, null, where, whereArgs, null);
// This should only ever return 1 record. I hope.
c.moveToPosition(-1);
while (c.moveToNext()) {
String instanceFile = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
Collect.getInstance().getActivityLogger().logAction(this, "delete", instanceFile);
File instanceDir = (new File(instanceFile)).getParentFile();
deleteAllFilesInDirectory(instanceDir);
}
} finally {
if ( c != null ) {
c.close();
}
}
count =
db.delete(INSTANCES_TABLE_NAME,
InstanceColumns._ID + "=" + instanceId
+ (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""),
whereArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
SQLiteDatabase db = mDbHelper.getWritableDatabase();
int count;
String status = null;
switch (sUriMatcher.match(uri)) {
case INSTANCES:
if (values.containsKey(InstanceColumns.STATUS)) {
status = values.getAsString(InstanceColumns.STATUS);
if (values.containsKey(InstanceColumns.DISPLAY_SUBTEXT) == false) {
Date today = new Date();
String text = getDisplaySubtext(status, today);
values.put(InstanceColumns.DISPLAY_SUBTEXT, text);
}
}
count = db.update(INSTANCES_TABLE_NAME, values, where, whereArgs);
break;
case INSTANCE_ID:
String instanceId = uri.getPathSegments().get(1);
if (values.containsKey(InstanceColumns.STATUS)) {
status = values.getAsString(InstanceColumns.STATUS);
if (values.containsKey(InstanceColumns.DISPLAY_SUBTEXT) == false) {
Date today = new Date();
String text = getDisplaySubtext(status, today);
values.put(InstanceColumns.DISPLAY_SUBTEXT, text);
}
}
count =
db.update(INSTANCES_TABLE_NAME, values, InstanceColumns._ID + "=" + instanceId
+ (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
static {
sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
sUriMatcher.addURI(InstanceProviderAPI.AUTHORITY, "instances", INSTANCES);
sUriMatcher.addURI(InstanceProviderAPI.AUTHORITY, "instances/#", INSTANCE_ID);
sInstancesProjectionMap = new HashMap<String, String>();
sInstancesProjectionMap.put(InstanceColumns._ID, InstanceColumns._ID);
sInstancesProjectionMap.put(InstanceColumns.DISPLAY_NAME, InstanceColumns.DISPLAY_NAME);
sInstancesProjectionMap.put(InstanceColumns.SUBMISSION_URI, InstanceColumns.SUBMISSION_URI);
sInstancesProjectionMap.put(InstanceColumns.CAN_EDIT_WHEN_COMPLETE, InstanceColumns.CAN_EDIT_WHEN_COMPLETE);
sInstancesProjectionMap.put(InstanceColumns.INSTANCE_FILE_PATH, InstanceColumns.INSTANCE_FILE_PATH);
sInstancesProjectionMap.put(InstanceColumns.JR_FORM_ID, InstanceColumns.JR_FORM_ID);
sInstancesProjectionMap.put(InstanceColumns.JR_VERSION, InstanceColumns.JR_VERSION);
sInstancesProjectionMap.put(InstanceColumns.STATUS, InstanceColumns.STATUS);
sInstancesProjectionMap.put(InstanceColumns.LAST_STATUS_CHANGE_DATE, InstanceColumns.LAST_STATUS_CHANGE_DATE);
sInstancesProjectionMap.put(InstanceColumns.DISPLAY_SUBTEXT, InstanceColumns.DISPLAY_SUBTEXT);
}
}
| Java |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.odk.collect.android.provider;
import android.net.Uri;
import android.provider.BaseColumns;
/**
* Convenience definitions for NotePadProvider
*/
public final class FormsProviderAPI {
public static final String AUTHORITY = "org.odk.collect.android.provider.odk.forms";
// This class cannot be instantiated
private FormsProviderAPI() {}
/**
* Notes table
*/
public static final class FormsColumns implements BaseColumns {
// This class cannot be instantiated
private FormsColumns() {}
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/forms");
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.odk.form";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.odk.form";
// These are the only things needed for an insert
public static final String DISPLAY_NAME = "displayName";
public static final String DESCRIPTION = "description"; // can be null
public static final String JR_FORM_ID = "jrFormId";
public static final String JR_VERSION = "jrVersion"; // can be null
public static final String FORM_FILE_PATH = "formFilePath";
public static final String SUBMISSION_URI = "submissionUri"; // can be null
public static final String BASE64_RSA_PUBLIC_KEY = "base64RsaPublicKey"; // can be null
// these are generated for you (but you can insert something else if you want)
public static final String DISPLAY_SUBTEXT = "displaySubtext";
public static final String MD5_HASH = "md5Hash";
public static final String DATE = "date";
public static final String JRCACHE_FILE_PATH = "jrcacheFilePath";
public static final String FORM_MEDIA_PATH = "formMediaPath";
// this is null on create, and can only be set on an update.
public static final String LANGUAGE = "language";
}
}
| Java |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.provider;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.database.ODKSQLiteOpenHelper;
import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.utilities.MediaUtils;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
/**
*
*/
public class FormsProvider extends ContentProvider {
private static final String t = "FormsProvider";
private static final String DATABASE_NAME = "forms.db";
private static final int DATABASE_VERSION = 4;
private static final String FORMS_TABLE_NAME = "forms";
private static HashMap<String, String> sFormsProjectionMap;
private static final int FORMS = 1;
private static final int FORM_ID = 2;
private static final UriMatcher sUriMatcher;
/**
* This class helps open, create, and upgrade the database file.
*/
private static class DatabaseHelper extends ODKSQLiteOpenHelper {
// These exist in database versions 2 and 3, but not in 4...
private static final String TEMP_FORMS_TABLE_NAME = "forms_v4";
private static final String MODEL_VERSION = "modelVersion";
DatabaseHelper(String databaseName) {
super(Collect.METADATA_PATH, databaseName, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
onCreateNamed(db, FORMS_TABLE_NAME);
}
private void onCreateNamed(SQLiteDatabase db, String tableName) {
db.execSQL("CREATE TABLE " + tableName + " ("
+ FormsColumns._ID + " integer primary key, "
+ FormsColumns.DISPLAY_NAME + " text not null, "
+ FormsColumns.DISPLAY_SUBTEXT + " text not null, "
+ FormsColumns.DESCRIPTION + " text, "
+ FormsColumns.JR_FORM_ID + " text not null, "
+ FormsColumns.JR_VERSION + " text, "
+ FormsColumns.MD5_HASH + " text not null, "
+ FormsColumns.DATE + " integer not null, " // milliseconds
+ FormsColumns.FORM_MEDIA_PATH + " text not null, "
+ FormsColumns.FORM_FILE_PATH + " text not null, "
+ FormsColumns.LANGUAGE + " text, "
+ FormsColumns.SUBMISSION_URI + " text, "
+ FormsColumns.BASE64_RSA_PUBLIC_KEY + " text, "
+ FormsColumns.JRCACHE_FILE_PATH + " text not null );");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
int initialVersion = oldVersion;
if ( oldVersion < 2 ) {
Log.w(t, "Upgrading database from version " + oldVersion + " to " + newVersion
+ ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + FORMS_TABLE_NAME);
onCreate(db);
return;
} else {
// adding BASE64_RSA_PUBLIC_KEY and changing type and name of integer MODEL_VERSION to text VERSION
db.execSQL("DROP TABLE IF EXISTS " + TEMP_FORMS_TABLE_NAME);
onCreateNamed(db, TEMP_FORMS_TABLE_NAME);
db.execSQL("INSERT INTO " + TEMP_FORMS_TABLE_NAME + " ("
+ FormsColumns._ID + ", "
+ FormsColumns.DISPLAY_NAME + ", "
+ FormsColumns.DISPLAY_SUBTEXT + ", "
+ FormsColumns.DESCRIPTION + ", "
+ FormsColumns.JR_FORM_ID + ", "
+ FormsColumns.MD5_HASH + ", "
+ FormsColumns.DATE + ", " // milliseconds
+ FormsColumns.FORM_MEDIA_PATH + ", "
+ FormsColumns.FORM_FILE_PATH + ", "
+ FormsColumns.LANGUAGE + ", "
+ FormsColumns.SUBMISSION_URI + ", "
+ FormsColumns.JR_VERSION + ", "
+ ((oldVersion != 3) ? "" : (FormsColumns.BASE64_RSA_PUBLIC_KEY + ", "))
+ FormsColumns.JRCACHE_FILE_PATH + ") SELECT "
+ FormsColumns._ID + ", "
+ FormsColumns.DISPLAY_NAME + ", "
+ FormsColumns.DISPLAY_SUBTEXT + ", "
+ FormsColumns.DESCRIPTION + ", "
+ FormsColumns.JR_FORM_ID + ", "
+ FormsColumns.MD5_HASH + ", "
+ FormsColumns.DATE + ", " // milliseconds
+ FormsColumns.FORM_MEDIA_PATH + ", "
+ FormsColumns.FORM_FILE_PATH + ", "
+ FormsColumns.LANGUAGE + ", "
+ FormsColumns.SUBMISSION_URI + ", "
+ "CASE WHEN " + MODEL_VERSION + " IS NOT NULL THEN " +
"CAST(" + MODEL_VERSION + " AS TEXT) ELSE NULL END, "
+ ((oldVersion != 3) ? "" : (FormsColumns.BASE64_RSA_PUBLIC_KEY + ", "))
+ FormsColumns.JRCACHE_FILE_PATH + " FROM " + FORMS_TABLE_NAME);
// risky failures here...
db.execSQL("DROP TABLE IF EXISTS " + FORMS_TABLE_NAME);
onCreateNamed(db, FORMS_TABLE_NAME);
db.execSQL("INSERT INTO " + FORMS_TABLE_NAME + " ("
+ FormsColumns._ID + ", "
+ FormsColumns.DISPLAY_NAME + ", "
+ FormsColumns.DISPLAY_SUBTEXT + ", "
+ FormsColumns.DESCRIPTION + ", "
+ FormsColumns.JR_FORM_ID + ", "
+ FormsColumns.MD5_HASH + ", "
+ FormsColumns.DATE + ", " // milliseconds
+ FormsColumns.FORM_MEDIA_PATH + ", "
+ FormsColumns.FORM_FILE_PATH + ", "
+ FormsColumns.LANGUAGE + ", "
+ FormsColumns.SUBMISSION_URI + ", "
+ FormsColumns.JR_VERSION + ", "
+ FormsColumns.BASE64_RSA_PUBLIC_KEY + ", "
+ FormsColumns.JRCACHE_FILE_PATH + ") SELECT "
+ FormsColumns._ID + ", "
+ FormsColumns.DISPLAY_NAME + ", "
+ FormsColumns.DISPLAY_SUBTEXT + ", "
+ FormsColumns.DESCRIPTION + ", "
+ FormsColumns.JR_FORM_ID + ", "
+ FormsColumns.MD5_HASH + ", "
+ FormsColumns.DATE + ", " // milliseconds
+ FormsColumns.FORM_MEDIA_PATH + ", "
+ FormsColumns.FORM_FILE_PATH + ", "
+ FormsColumns.LANGUAGE + ", "
+ FormsColumns.SUBMISSION_URI + ", "
+ FormsColumns.JR_VERSION + ", "
+ FormsColumns.BASE64_RSA_PUBLIC_KEY + ", "
+ FormsColumns.JRCACHE_FILE_PATH + " FROM " + TEMP_FORMS_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + TEMP_FORMS_TABLE_NAME);
Log.w(t, "Successfully upgraded database from version " + initialVersion + " to " + newVersion
+ ", without destroying all the old data");
}
}
}
private DatabaseHelper mDbHelper;
@Override
public boolean onCreate() {
// must be at the beginning of any activity that can be called from an external intent
Collect.createODKDirs();
mDbHelper = new DatabaseHelper(DATABASE_NAME);
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(FORMS_TABLE_NAME);
switch (sUriMatcher.match(uri)) {
case FORMS:
qb.setProjectionMap(sFormsProjectionMap);
break;
case FORM_ID:
qb.setProjectionMap(sFormsProjectionMap);
qb.appendWhere(FormsColumns._ID + "=" + uri.getPathSegments().get(1));
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
// Get the database and run the query
SQLiteDatabase db = mDbHelper.getReadableDatabase();
Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
// Tell the cursor what uri to watch, so it knows when its source data changes
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
@Override
public String getType(Uri uri) {
switch (sUriMatcher.match(uri)) {
case FORMS:
return FormsColumns.CONTENT_TYPE;
case FORM_ID:
return FormsColumns.CONTENT_ITEM_TYPE;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
}
@Override
public synchronized Uri insert(Uri uri, ContentValues initialValues) {
// Validate the requested uri
if (sUriMatcher.match(uri) != FORMS) {
throw new IllegalArgumentException("Unknown URI " + uri);
}
ContentValues values;
if (initialValues != null) {
values = new ContentValues(initialValues);
} else {
values = new ContentValues();
}
if (!values.containsKey(FormsColumns.FORM_FILE_PATH)) {
throw new IllegalArgumentException(FormsColumns.FORM_FILE_PATH + " must be specified.");
}
// Normalize the file path.
// (don't trust the requester).
String filePath = values.getAsString(FormsColumns.FORM_FILE_PATH);
File form = new File(filePath);
filePath = form.getAbsolutePath(); // normalized
values.put(FormsColumns.FORM_FILE_PATH, filePath);
Long now = Long.valueOf(System.currentTimeMillis());
// Make sure that the necessary fields are all set
if (values.containsKey(FormsColumns.DATE) == false) {
values.put(FormsColumns.DATE, now);
}
if (values.containsKey(FormsColumns.DISPLAY_SUBTEXT) == false) {
Date today = new Date();
String ts = new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time), Locale.getDefault()).format(today);
values.put(FormsColumns.DISPLAY_SUBTEXT, ts);
}
if (values.containsKey(FormsColumns.DISPLAY_NAME) == false) {
values.put(FormsColumns.DISPLAY_NAME, form.getName());
}
// don't let users put in a manual md5 hash
if (values.containsKey(FormsColumns.MD5_HASH)) {
values.remove(FormsColumns.MD5_HASH);
}
String md5 = FileUtils.getMd5Hash(form);
values.put(FormsColumns.MD5_HASH, md5);
if (values.containsKey(FormsColumns.JRCACHE_FILE_PATH) == false) {
String cachePath = Collect.CACHE_PATH + File.separator + md5 + ".formdef";
values.put(FormsColumns.JRCACHE_FILE_PATH, cachePath);
}
if (values.containsKey(FormsColumns.FORM_MEDIA_PATH) == false) {
String pathNoExtension = filePath.substring(0, filePath.lastIndexOf("."));
String mediaPath = pathNoExtension + "-media";
values.put(FormsColumns.FORM_MEDIA_PATH, mediaPath);
}
SQLiteDatabase db = mDbHelper.getWritableDatabase();
// first try to see if a record with this filename already exists...
String[] projection = {
FormsColumns._ID, FormsColumns.FORM_FILE_PATH
};
String[] selectionArgs = { filePath };
String selection = FormsColumns.FORM_FILE_PATH + "=?";
Cursor c = null;
try {
c = db.query(FORMS_TABLE_NAME, projection, selection, selectionArgs, null, null, null);
if ( c.getCount() > 0 ) {
// already exists
throw new SQLException("FAILED Insert into " + uri + " -- row already exists for form definition file: " + filePath);
}
} finally {
if ( c != null ) {
c.close();
}
}
long rowId = db.insert(FORMS_TABLE_NAME, null, values);
if (rowId > 0) {
Uri formUri = ContentUris.withAppendedId(FormsColumns.CONTENT_URI, rowId);
getContext().getContentResolver().notifyChange(formUri, null);
Collect.getInstance().getActivityLogger().logActionParam(this, "insert",
formUri.toString(), values.getAsString(FormsColumns.FORM_FILE_PATH));
return formUri;
}
throw new SQLException("Failed to insert row into " + uri);
}
private void deleteFileOrDir(String fileName) {
File file = new File(fileName);
if (file.exists()) {
if (file.isDirectory()) {
// delete any media entries for files in this directory...
int images = MediaUtils.deleteImagesInFolderFromMediaProvider(file);
int audio = MediaUtils.deleteAudioInFolderFromMediaProvider(file);
int video = MediaUtils.deleteVideoInFolderFromMediaProvider(file);
Log.i(t, "removed from content providers: " + images
+ " image files, " + audio + " audio files,"
+ " and " + video + " video files.");
// delete all the containing files
File[] files = file.listFiles();
for (File f : files) {
// should make this recursive if we get worried about
// the media directory containing directories
Log.i(t, "attempting to delete file: " + f.getAbsolutePath());
f.delete();
}
}
file.delete();
Log.i(t, "attempting to delete file: " + file.getAbsolutePath());
}
}
/**
* This method removes the entry from the content provider, and also removes any associated
* files. files: form.xml, [formmd5].formdef, formname-media {directory}
*/
@Override
public int delete(Uri uri, String where, String[] whereArgs) {
SQLiteDatabase db = mDbHelper.getWritableDatabase();
int count;
switch (sUriMatcher.match(uri)) {
case FORMS:
Cursor del = null;
try {
del = this.query(uri, null, where, whereArgs, null);
del.moveToPosition(-1);
while (del.moveToNext()) {
deleteFileOrDir(del.getString(del
.getColumnIndex(FormsColumns.JRCACHE_FILE_PATH)));
String formFilePath = del.getString(del.getColumnIndex(FormsColumns.FORM_FILE_PATH));
Collect.getInstance().getActivityLogger().logAction(this, "delete", formFilePath);
deleteFileOrDir(formFilePath);
deleteFileOrDir(del.getString(del.getColumnIndex(FormsColumns.FORM_MEDIA_PATH)));
}
} finally {
if ( del != null ) {
del.close();
}
}
count = db.delete(FORMS_TABLE_NAME, where, whereArgs);
break;
case FORM_ID:
String formId = uri.getPathSegments().get(1);
Cursor c = null;
try {
c = this.query(uri, null, where, whereArgs, null);
// This should only ever return 1 record.
c.moveToPosition(-1);
while (c.moveToNext()) {
deleteFileOrDir(c.getString(c.getColumnIndex(FormsColumns.JRCACHE_FILE_PATH)));
String formFilePath = c.getString(c.getColumnIndex(FormsColumns.FORM_FILE_PATH));
Collect.getInstance().getActivityLogger().logAction(this, "delete", formFilePath);
deleteFileOrDir(formFilePath);
deleteFileOrDir(c.getString(c.getColumnIndex(FormsColumns.FORM_MEDIA_PATH)));
}
} finally {
if ( c != null ) {
c.close();
}
}
count =
db.delete(FORMS_TABLE_NAME,
FormsColumns._ID + "=" + formId
+ (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""),
whereArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
SQLiteDatabase db = mDbHelper.getWritableDatabase();
int count = 0;
switch (sUriMatcher.match(uri)) {
case FORMS:
// don't let users manually update md5
if (values.containsKey(FormsColumns.MD5_HASH)) {
values.remove(FormsColumns.MD5_HASH);
}
// if values contains path, then all filepaths and md5s will get updated
// this probably isn't a great thing to do.
if (values.containsKey(FormsColumns.FORM_FILE_PATH)) {
String formFile = values.getAsString(FormsColumns.FORM_FILE_PATH);
values.put(FormsColumns.MD5_HASH, FileUtils.getMd5Hash(new File(formFile)));
}
Cursor c = null;
try {
c = this.query(uri, null, where, whereArgs, null);
if (c.getCount() > 0) {
c.moveToPosition(-1);
while (c.moveToNext()) {
// before updating the paths, delete all the files
if (values.containsKey(FormsColumns.FORM_FILE_PATH)) {
String newFile = values.getAsString(FormsColumns.FORM_FILE_PATH);
String delFile =
c.getString(c.getColumnIndex(FormsColumns.FORM_FILE_PATH));
if (newFile.equalsIgnoreCase(delFile)) {
// same file, so don't delete anything
} else {
// different files, delete the old one
deleteFileOrDir(delFile);
}
// either way, delete the old cache because we'll calculate a new one.
deleteFileOrDir(c.getString(c
.getColumnIndex(FormsColumns.JRCACHE_FILE_PATH)));
}
}
}
} finally {
if ( c != null ) {
c.close();
}
}
// Make sure that the necessary fields are all set
if (values.containsKey(FormsColumns.DATE) == true) {
Date today = new Date();
String ts = new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time), Locale.getDefault()).format(today);
values.put(FormsColumns.DISPLAY_SUBTEXT, ts);
}
count = db.update(FORMS_TABLE_NAME, values, where, whereArgs);
break;
case FORM_ID:
String formId = uri.getPathSegments().get(1);
// Whenever file paths are updated, delete the old files.
Cursor update = null;
try {
update = this.query(uri, null, where, whereArgs, null);
// This should only ever return 1 record.
if (update.getCount() > 0) {
update.moveToFirst();
// don't let users manually update md5
if (values.containsKey(FormsColumns.MD5_HASH)) {
values.remove(FormsColumns.MD5_HASH);
}
// the order here is important (jrcache needs to be before form file)
// because we update the jrcache file if there's a new form file
if (values.containsKey(FormsColumns.JRCACHE_FILE_PATH)) {
deleteFileOrDir(update.getString(update
.getColumnIndex(FormsColumns.JRCACHE_FILE_PATH)));
}
if (values.containsKey(FormsColumns.FORM_FILE_PATH)) {
String formFile = values.getAsString(FormsColumns.FORM_FILE_PATH);
String oldFile =
update.getString(update.getColumnIndex(FormsColumns.FORM_FILE_PATH));
if (formFile != null && formFile.equalsIgnoreCase(oldFile)) {
// Files are the same, so we may have just copied over something we had
// already
} else {
// New file name. This probably won't ever happen, though.
deleteFileOrDir(oldFile);
}
// we're updating our file, so update the md5
// and get rid of the cache (doesn't harm anything)
deleteFileOrDir(update.getString(update
.getColumnIndex(FormsColumns.JRCACHE_FILE_PATH)));
String newMd5 = FileUtils.getMd5Hash(new File(formFile));
values.put(FormsColumns.MD5_HASH, newMd5);
values.put(FormsColumns.JRCACHE_FILE_PATH,
Collect.CACHE_PATH + File.separator + newMd5 + ".formdef");
}
// Make sure that the necessary fields are all set
if (values.containsKey(FormsColumns.DATE) == true) {
Date today = new Date();
String ts =
new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time), Locale.getDefault()).format(today);
values.put(FormsColumns.DISPLAY_SUBTEXT, ts);
}
count =
db.update(FORMS_TABLE_NAME, values, FormsColumns._ID + "=" + formId
+ (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""),
whereArgs);
} else {
Log.e(t, "Attempting to update row that does not exist");
}
} finally {
if ( update != null ) {
update.close();
}
}
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
static {
sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
sUriMatcher.addURI(FormsProviderAPI.AUTHORITY, "forms", FORMS);
sUriMatcher.addURI(FormsProviderAPI.AUTHORITY, "forms/#", FORM_ID);
sFormsProjectionMap = new HashMap<String, String>();
sFormsProjectionMap.put(FormsColumns._ID, FormsColumns._ID);
sFormsProjectionMap.put(FormsColumns.DISPLAY_NAME, FormsColumns.DISPLAY_NAME);
sFormsProjectionMap.put(FormsColumns.DISPLAY_SUBTEXT, FormsColumns.DISPLAY_SUBTEXT);
sFormsProjectionMap.put(FormsColumns.DESCRIPTION, FormsColumns.DESCRIPTION);
sFormsProjectionMap.put(FormsColumns.JR_FORM_ID, FormsColumns.JR_FORM_ID);
sFormsProjectionMap.put(FormsColumns.JR_VERSION, FormsColumns.JR_VERSION);
sFormsProjectionMap.put(FormsColumns.SUBMISSION_URI, FormsColumns.SUBMISSION_URI);
sFormsProjectionMap.put(FormsColumns.BASE64_RSA_PUBLIC_KEY, FormsColumns.BASE64_RSA_PUBLIC_KEY);
sFormsProjectionMap.put(FormsColumns.MD5_HASH, FormsColumns.MD5_HASH);
sFormsProjectionMap.put(FormsColumns.DATE, FormsColumns.DATE);
sFormsProjectionMap.put(FormsColumns.FORM_MEDIA_PATH, FormsColumns.FORM_MEDIA_PATH);
sFormsProjectionMap.put(FormsColumns.FORM_FILE_PATH, FormsColumns.FORM_FILE_PATH);
sFormsProjectionMap.put(FormsColumns.JRCACHE_FILE_PATH, FormsColumns.JRCACHE_FILE_PATH);
sFormsProjectionMap.put(FormsColumns.LANGUAGE, FormsColumns.LANGUAGE);
}
}
| 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.views;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.widgets.IBinaryWidget;
import org.odk.collect.android.widgets.QuestionWidget;
import org.odk.collect.android.widgets.WidgetFactory;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
/**
* This class is
*
* @author carlhartung
*/
public class ODKView extends ScrollView implements OnLongClickListener {
// starter random number for view IDs
private final static int VIEW_ID = 12345;
private final static String t = "ODKView";
private LinearLayout mView;
private LinearLayout.LayoutParams mLayout;
private ArrayList<QuestionWidget> widgets;
private Handler h = null;
public final static String FIELD_LIST = "field-list";
public ODKView(Context context, FormEntryPrompt[] questionPrompts,
FormEntryCaption[] groups, boolean advancingPage) {
super(context);
widgets = new ArrayList<QuestionWidget>();
mView = new LinearLayout(getContext());
mView.setOrientation(LinearLayout.VERTICAL);
mView.setGravity(Gravity.TOP);
mView.setPadding(0, 7, 0, 0);
mLayout =
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
mLayout.setMargins(10, 0, 10, 0);
// display which group you are in as well as the question
addGroupText(groups);
boolean first = true;
int id = 0;
for (FormEntryPrompt p : questionPrompts) {
if (!first) {
View divider = new View(getContext());
divider.setBackgroundResource(android.R.drawable.divider_horizontal_bright);
divider.setMinimumHeight(3);
mView.addView(divider);
} else {
first = false;
}
// if question or answer type is not supported, use text widget
QuestionWidget qw =
WidgetFactory.createWidgetFromPrompt(p, getContext());
qw.setLongClickable(true);
qw.setOnLongClickListener(this);
qw.setId(VIEW_ID + id++);
widgets.add(qw);
mView.addView((View) qw, mLayout);
}
addView(mView);
// see if there is an autoplay option.
// Only execute it during forward swipes through the form
if ( advancingPage && questionPrompts.length == 1 ) {
final String playOption = widgets.get(0).getPrompt().getFormElement().getAdditionalAttribute(null, "autoplay");
if ( playOption != null ) {
h = new Handler();
h.postDelayed(new Runnable() {
@Override
public void run() {
if ( playOption.equalsIgnoreCase("audio") ) {
widgets.get(0).playAudio();
} else if ( playOption.equalsIgnoreCase("video") ) {
widgets.get(0).playVideo();
}
}
}, 150);
}
}
}
/**
* http://code.google.com/p/android/issues/detail?id=8488
*/
public void recycleDrawables() {
this.destroyDrawingCache();
mView.destroyDrawingCache();
for ( QuestionWidget q : widgets ) {
q.recycleDrawables();
}
}
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
Collect.getInstance().getActivityLogger().logScrollAction(this, t - oldt);
}
/**
* @return a HashMap of answers entered by the user for this set of widgets
*/
public LinkedHashMap<FormIndex, IAnswerData> getAnswers() {
LinkedHashMap<FormIndex, IAnswerData> answers = new LinkedHashMap<FormIndex, IAnswerData>();
Iterator<QuestionWidget> i = widgets.iterator();
while (i.hasNext()) {
/*
* The FormEntryPrompt has the FormIndex, which is where the answer gets stored. The
* QuestionWidget has the answer the user has entered.
*/
QuestionWidget q = i.next();
FormEntryPrompt p = q.getPrompt();
answers.put(p.getIndex(), q.getAnswer());
}
return answers;
}
/**
* // * Add a TextView containing the hierarchy of groups to which the question belongs. //
*/
private void addGroupText(FormEntryCaption[] groups) {
StringBuffer s = new StringBuffer("");
String t = "";
int i;
// list all groups in one string
for (FormEntryCaption g : groups) {
i = g.getMultiplicity() + 1;
t = g.getLongText();
if (t != null) {
s.append(t);
if (g.repeats() && i > 0) {
s.append(" (" + i + ")");
}
s.append(" > ");
}
}
// build view
if (s.length() > 0) {
TextView tv = new TextView(getContext());
tv.setText(s.substring(0, s.length() - 3));
int questionFontsize = Collect.getQuestionFontsize();
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, questionFontsize - 4);
tv.setPadding(0, 0, 0, 5);
mView.addView(tv, mLayout);
}
}
public void setFocus(Context context) {
if (widgets.size() > 0) {
widgets.get(0).setFocus(context);
}
}
/**
* Called when another activity returns information to answer this question.
*
* @param answer
*/
public void setBinaryData(Object answer) {
boolean set = false;
for (QuestionWidget q : widgets) {
if (q instanceof IBinaryWidget) {
if (((IBinaryWidget) q).isWaitingForBinaryData()) {
((IBinaryWidget) q).setBinaryData(answer);
set = true;
break;
}
}
}
if (!set) {
Log.w(t, "Attempting to return data to a widget or set of widgets not looking for data");
}
}
public void cancelWaitingForBinaryData() {
int count = 0;
for (QuestionWidget q : widgets) {
if (q instanceof IBinaryWidget) {
if (((IBinaryWidget) q).isWaitingForBinaryData()) {
((IBinaryWidget) q).cancelWaitingForBinaryData();
++count;
}
}
}
if (count != 1) {
Log.w(t, "Attempting to cancel waiting for binary data to a widget or set of widgets not looking for data");
}
}
public boolean suppressFlingGesture(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
for (QuestionWidget q : widgets) {
if ( q.suppressFlingGesture(e1, e2, velocityX, velocityY) ) {
return true;
}
}
return false;
}
/**
* @return true if the answer was cleared, false otherwise.
*/
public boolean clearAnswer() {
// If there's only one widget, clear the answer.
// If there are more, then force a long-press to clear the answer.
if (widgets.size() == 1 && !widgets.get(0).getPrompt().isReadOnly()) {
widgets.get(0).clearAnswer();
return true;
} else {
return false;
}
}
public ArrayList<QuestionWidget> getWidgets() {
return widgets;
}
@Override
public void setOnFocusChangeListener(OnFocusChangeListener l) {
for (int i = 0; i < widgets.size(); i++) {
QuestionWidget qw = widgets.get(i);
qw.setOnFocusChangeListener(l);
}
}
@Override
public boolean onLongClick(View v) {
return false;
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
for (QuestionWidget qw : widgets) {
qw.cancelLongPress();
}
}
}
| 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.views;
import java.io.File;
import java.io.IOException;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.Toast;
/**
* @author ctsims
* @author carlhartung
*/
public class AudioButton extends ImageButton implements OnClickListener {
private final static String t = "AudioButton";
/**
* Useful class for handling the playing and stopping of audio prompts.
* This is used here, and also in the GridMultiWidget and GridWidget
* to play prompts as items are selected.
*
* @author mitchellsundt@gmail.com
*
*/
public static class AudioHandler {
private FormIndex index;
private String selectionDesignator;
private String URI;
private MediaPlayer player;
public AudioHandler(FormIndex index, String selectionDesignator, String URI) {
this.index = index;
this.selectionDesignator = selectionDesignator;
this.URI = URI;
player = null;
}
public void playAudio(Context c) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onClick.playAudioPrompt", selectionDesignator, index);
if (URI == null) {
// No audio file specified
Log.e(t, "No audio file was specified");
Toast.makeText(c, c.getString(R.string.audio_file_error),
Toast.LENGTH_LONG).show();
return;
}
String audioFilename = "";
try {
audioFilename = ReferenceManager._().DeriveReference(URI).getLocalURI();
} catch (InvalidReferenceException e) {
Log.e(t, "Invalid reference exception");
e.printStackTrace();
}
File audioFile = new File(audioFilename);
if (!audioFile.exists()) {
// We should have an audio clip, but the file doesn't exist.
String errorMsg = c.getString(R.string.file_missing, audioFile);
Log.e(t, errorMsg);
Toast.makeText(c, errorMsg, Toast.LENGTH_LONG).show();
return;
}
// In case we're currently playing sounds.
stopPlaying();
player = new MediaPlayer();
try {
player.setDataSource(audioFilename);
player.prepare();
player.start();
player.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.release();
}
});
} catch (IOException e) {
String errorMsg = c.getString(R.string.audio_file_invalid);
Log.e(t, errorMsg);
Toast.makeText(c, errorMsg, Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
public void stopPlaying() {
if (player != null) {
player.release();
}
}
}
AudioHandler handler;
public AudioButton(Context context, FormIndex index, String selectionDesignator, String URI) {
super(context);
this.setOnClickListener(this);
handler = new AudioHandler( index, selectionDesignator, URI);
Bitmap b =
BitmapFactory.decodeResource(context.getResources(),
android.R.drawable.ic_lock_silent_mode_off);
this.setImageBitmap(b);
}
public void playAudio() {
handler.playAudio(getContext());
}
@Override
public void onClick(View v) {
playAudio();
}
public void stopPlaying() {
handler.stopPlaying();
}
}
| 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.views;
import java.io.File;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.widgets.QuestionWidget;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
* This layout is used anywhere we can have image/audio/video/text. TODO: It would probably be nice
* to put this in a layout.xml file of some sort at some point.
*
* @author carlhartung
*/
public class MediaLayout extends RelativeLayout {
private static final String t = "AVTLayout";
private String mSelectionDesignator;
private FormIndex mIndex;
private TextView mView_Text;
private AudioButton mAudioButton;
private ImageButton mVideoButton;
private ImageView mImageView;
private TextView mMissingImage;
private String mVideoURI = null;
public MediaLayout(Context c) {
super(c);
mView_Text = null;
mAudioButton = null;
mImageView = null;
mMissingImage = null;
mVideoButton = null;
mIndex = null;
}
public void playAudio() {
if ( mAudioButton != null ) {
mAudioButton.playAudio();
}
}
public void playVideo() {
if ( mVideoURI != null ) {
String videoFilename = "";
try {
videoFilename =
ReferenceManager._().DeriveReference(mVideoURI).getLocalURI();
} catch (InvalidReferenceException e) {
Log.e(t, "Invalid reference exception");
e.printStackTrace();
}
File videoFile = new File(videoFilename);
if (!videoFile.exists()) {
// We should have a video clip, but the file doesn't exist.
String errorMsg =
getContext().getString(R.string.file_missing, videoFilename);
Log.e(t, errorMsg);
Toast.makeText(getContext(), errorMsg, Toast.LENGTH_LONG).show();
return;
}
Intent i = new Intent("android.intent.action.VIEW");
i.setDataAndType(Uri.fromFile(videoFile), "video/*");
try {
((Activity) getContext()).startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(getContext(),
getContext().getString(R.string.activity_not_found, "view video"),
Toast.LENGTH_SHORT).show();
}
}
}
public void setAVT(FormIndex index, String selectionDesignator, TextView text, String audioURI, String imageURI, String videoURI,
final String bigImageURI) {
mSelectionDesignator = selectionDesignator;
mIndex = index;
mView_Text = text;
mView_Text.setId(QuestionWidget.newUniqueId());
mVideoURI = videoURI;
// Layout configurations for our elements in the relative layout
RelativeLayout.LayoutParams textParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams audioParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams imageParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams videoParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// First set up the audio button
if (audioURI != null) {
// An audio file is specified
mAudioButton = new AudioButton(getContext(), mIndex, mSelectionDesignator, audioURI);
mAudioButton.setId(QuestionWidget.newUniqueId()); // random ID to be used by the
// relative layout.
} else {
// No audio file specified, so ignore.
}
// Then set up the video button
if (videoURI != null) {
// An video file is specified
mVideoButton = new ImageButton(getContext());
Bitmap b =
BitmapFactory.decodeResource(getContext().getResources(),
android.R.drawable.ic_media_play);
mVideoButton.setImageBitmap(b);
mVideoButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onClick", "playVideoPrompt"+mSelectionDesignator, mIndex);
MediaLayout.this.playVideo();
}
});
mVideoButton.setId(QuestionWidget.newUniqueId());
} else {
// No video file specified, so ignore.
}
// Now set up the image view
String errorMsg = null;
final int imageId = QuestionWidget.newUniqueId();
if (imageURI != null) {
try {
String imageFilename = ReferenceManager._().DeriveReference(imageURI).getLocalURI();
final File imageFile = new File(imageFilename);
if (imageFile.exists()) {
Display display =
((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
Bitmap b = FileUtils.getBitmapScaledToDisplay(imageFile, screenHeight, screenWidth);
if (b != null) {
mImageView = new ImageView(getContext());
mImageView.setPadding(2, 2, 2, 2);
mImageView.setBackgroundColor(Color.WHITE);
mImageView.setImageBitmap(b);
mImageView.setId(imageId);
if (bigImageURI != null) {
mImageView.setOnClickListener(new OnClickListener() {
String bigImageFilename = ReferenceManager._()
.DeriveReference(bigImageURI).getLocalURI();
File bigImage = new File(bigImageFilename);
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onClick", "showImagePromptBigImage"+mSelectionDesignator, mIndex);
Intent i = new Intent("android.intent.action.VIEW");
i.setDataAndType(Uri.fromFile(bigImage), "image/*");
try {
getContext().startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(
getContext(),
getContext().getString(R.string.activity_not_found,
"view image"), Toast.LENGTH_SHORT).show();
}
}
});
}
} else {
// Loading the image failed, so it's likely a bad file.
errorMsg = getContext().getString(R.string.file_invalid, imageFile);
}
} else {
// We should have an image, but the file doesn't exist.
errorMsg = getContext().getString(R.string.file_missing, imageFile);
}
if (errorMsg != null) {
// errorMsg is only set when an error has occurred
Log.e(t, errorMsg);
mMissingImage = new TextView(getContext());
mMissingImage.setText(errorMsg);
mMissingImage.setPadding(10, 10, 10, 10);
mMissingImage.setId(imageId);
}
} catch (InvalidReferenceException e) {
Log.e(t, "image invalid reference exception");
e.printStackTrace();
}
} else {
// There's no imageURI listed, so just ignore it.
}
// Determine the layout constraints...
// Assumes LTR, TTB reading bias!
if (mView_Text.getText().length() == 0 && (mImageView != null || mMissingImage != null)) {
// No text; has image. The image is treated as question/choice icon.
// The Text view may just have a radio button or checkbox. It
// needs to remain in the layout even though it is blank.
//
// The image view, as created above, will dynamically resize and
// center itself. We want it to resize but left-align itself
// in the resized area and we want a white background, as otherwise
// it will show a grey bar to the right of the image icon.
if (mImageView != null) {
mImageView.setScaleType(ScaleType.FIT_START);
}
//
// In this case, we have:
// Text upper left; image upper, left edge aligned with text right edge;
// audio upper right; video below audio on right.
textParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
textParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
imageParams.addRule(RelativeLayout.RIGHT_OF, mView_Text.getId());
imageParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
if (mAudioButton != null && mVideoButton == null) {
audioParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
audioParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
imageParams.addRule(RelativeLayout.LEFT_OF, mAudioButton.getId());
} else if (mAudioButton == null && mVideoButton != null) {
videoParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
videoParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
imageParams.addRule(RelativeLayout.LEFT_OF, mVideoButton.getId());
} else if (mAudioButton != null && mVideoButton != null) {
audioParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
audioParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
imageParams.addRule(RelativeLayout.LEFT_OF, mAudioButton.getId());
videoParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
videoParams.addRule(RelativeLayout.BELOW, mAudioButton.getId());
imageParams.addRule(RelativeLayout.LEFT_OF, mVideoButton.getId());
} else {
// the image will implicitly scale down to fit within parent...
// no need to bound it by the width of the parent...
imageParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
}
imageParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
} else {
// We have a non-blank text label -- image is below the text.
// In this case, we want the image to be centered...
if (mImageView != null) {
mImageView.setScaleType(ScaleType.FIT_START);
}
//
// Text upper left; audio upper right; video below audio on right.
// image below text, audio and video buttons; left-aligned with text.
textParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
textParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
if (mAudioButton != null && mVideoButton == null) {
audioParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
textParams.addRule(RelativeLayout.LEFT_OF, mAudioButton.getId());
} else if (mAudioButton == null && mVideoButton != null) {
videoParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
textParams.addRule(RelativeLayout.LEFT_OF, mVideoButton.getId());
} else if (mAudioButton != null && mVideoButton != null) {
audioParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
textParams.addRule(RelativeLayout.LEFT_OF, mAudioButton.getId());
videoParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
videoParams.addRule(RelativeLayout.BELOW, mAudioButton.getId());
} else {
textParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
}
if (mImageView != null || mMissingImage != null) {
imageParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
imageParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
imageParams.addRule(RelativeLayout.BELOW, mView_Text.getId());
} else {
textParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
}
}
addView(mView_Text, textParams);
if (mAudioButton != null)
addView(mAudioButton, audioParams);
if (mVideoButton != null)
addView(mVideoButton, videoParams);
if (mImageView != null)
addView(mImageView, imageParams);
else if (mMissingImage != null)
addView(mMissingImage, imageParams);
}
/**
* This adds a divider at the bottom of this layout. Used to separate fields in lists.
*
* @param v
*/
public void addDivider(ImageView v) {
RelativeLayout.LayoutParams dividerParams =
new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
if (mImageView != null) {
dividerParams.addRule(RelativeLayout.BELOW, mImageView.getId());
} else if (mMissingImage != null) {
dividerParams.addRule(RelativeLayout.BELOW, mMissingImage.getId());
} else if (mVideoButton != null) {
dividerParams.addRule(RelativeLayout.BELOW, mVideoButton.getId());
} else if (mAudioButton != null) {
dividerParams.addRule(RelativeLayout.BELOW, mAudioButton.getId());
} else if (mView_Text != null) {
// No picture
dividerParams.addRule(RelativeLayout.BELOW, mView_Text.getId());
} else {
Log.e(t, "Tried to add divider to uninitialized ATVWidget");
return;
}
addView(v, dividerParams);
}
@Override
protected void onWindowVisibilityChanged(int visibility) {
super.onWindowVisibilityChanged(visibility);
if (visibility != View.VISIBLE) {
if (mAudioButton != null) {
mAudioButton.stopPlaying();
}
}
}
}
| Java |
/*
* Copyright (C) 2013 University of Washington
*
* http://creativecommons.org/licenses/by-sa/3.0/ -- code is based upon an answer on Stack Overflow:
* http://stackoverflow.com/questions/8481844/gridview-height-gets-cut
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.views;
import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.GridView;
/**
* From Stack Overflow: http://stackoverflow.com/questions/8481844/gridview-height-gets-cut
* Changed to always be expanded, since widgets are always embedded in a scroll view.
*
* @author tacone based on answer by Neil Traft
* @author mitchellsundt@gmail.com
*
*/
public class ExpandedHeightGridView extends GridView
{
public ExpandedHeightGridView(Context context)
{
super(context);
}
public ExpandedHeightGridView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public ExpandedHeightGridView(Context context, AttributeSet attrs,
int defStyle)
{
super(context, attrs, defStyle);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
// HACK! TAKE THAT ANDROID!
// Calculate entire height by providing a very large height hint.
// But do not use the highest 2 bits of this integer; those are
// reserved for the MeasureSpec mode.
int expandSpec = MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
}
}
| 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.views;
import org.odk.collect.android.R;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.CheckBox;
import android.widget.Checkable;
import android.widget.RelativeLayout;
public class TwoItemMultipleChoiceView extends RelativeLayout implements Checkable {
public TwoItemMultipleChoiceView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public TwoItemMultipleChoiceView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TwoItemMultipleChoiceView(Context context) {
super(context);
}
@Override
public boolean isChecked() {
CheckBox c = (CheckBox) findViewById(R.id.checkbox);
return c.isChecked();
}
@Override
public void setChecked(boolean checked) {
CheckBox c = (CheckBox) findViewById(R.id.checkbox);
c.setChecked(checked);
}
@Override
public void toggle() {
CheckBox c = (CheckBox) findViewById(R.id.checkbox);
c.setChecked(!c.isChecked());
}
}
| 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.views;
import org.odk.collect.android.logic.HierarchyElement;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class HierarchyElementView extends RelativeLayout {
private TextView mPrimaryTextView;
private TextView mSecondaryTextView;
private ImageView mIcon;
public HierarchyElementView(Context context, HierarchyElement it) {
super(context);
setColor(it.getColor());
mIcon = new ImageView(context);
mIcon.setImageDrawable(it.getIcon());
mIcon.setId(1);
mIcon.setPadding(0, 0, dipToPx(4), 0);
addView(mIcon, new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
mPrimaryTextView = new TextView(context);
mPrimaryTextView.setTextAppearance(context, android.R.style.TextAppearance_Large);
mPrimaryTextView.setText(it.getPrimaryText());
mPrimaryTextView.setId(2);
mPrimaryTextView.setGravity(Gravity.CENTER_VERTICAL);
LayoutParams l =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
l.addRule(RelativeLayout.RIGHT_OF, mIcon.getId());
addView(mPrimaryTextView, l);
mSecondaryTextView = new TextView(context);
mSecondaryTextView.setText(it.getSecondaryText());
mSecondaryTextView.setTextAppearance(context, android.R.style.TextAppearance_Small);
mSecondaryTextView.setGravity(Gravity.CENTER_VERTICAL);
LayoutParams lp =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.BELOW, mPrimaryTextView.getId());
lp.addRule(RelativeLayout.RIGHT_OF, mIcon.getId());
addView(mSecondaryTextView, lp);
setPadding(dipToPx(8), dipToPx(4), dipToPx(8), dipToPx(8));
}
public void setPrimaryText(String text) {
mPrimaryTextView.setText(text);
}
public void setSecondaryText(String text) {
mSecondaryTextView.setText(text);
}
public void setIcon(Drawable icon) {
mIcon.setImageDrawable(icon);
}
public void setColor(int color) {
setBackgroundColor(color);
}
public void showSecondary(boolean bool) {
if (bool) {
mSecondaryTextView.setVisibility(VISIBLE);
setMinimumHeight(dipToPx(64));
} else {
mSecondaryTextView.setVisibility(GONE);
setMinimumHeight(dipToPx(32));
}
}
public int dipToPx(int dip) {
return (int) (dip * getResources().getDisplayMetrics().density + 0.5f);
}
}
| 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.views;
import org.odk.collect.android.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
/**
* Builds view for arrow animation
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class ArrowAnimationView extends View {
private final static String t = "ArrowAnimationView";
private Animation mAnimation;
private Bitmap mArrow;
private int mImgXOffset;
public ArrowAnimationView(Context context, AttributeSet attrs) {
super(context, attrs);
Log.i(t, "called constructor");
init();
}
public ArrowAnimationView(Context context) {
super(context);
init();
}
private void init() {
mArrow = BitmapFactory.decodeResource(getResources(), R.drawable.left_arrow);
mImgXOffset = mArrow.getWidth() / 2;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mAnimation == null) {
createAnim(canvas);
}
int centerX = canvas.getWidth() / 2;
canvas.drawBitmap(mArrow, centerX - mImgXOffset, (float) mArrow.getHeight() / 4, null);
}
private void createAnim(Canvas canvas) {
mAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.start_arrow);
startAnimation(mAnimation);
}
}
| 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.utilities;
import org.odk.collect.android.R;
import android.content.Context;
import android.database.Cursor;
import android.view.View;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
/**
* Implementation of cursor adapter that displays the version of a form if a form has a version.
*
* @author mitchellsundt@gmail.com
*
*/
public class VersionHidingCursorAdapter extends SimpleCursorAdapter {
private final Context ctxt;
private final String versionColumnName;
private final ViewBinder originalBinder;
public VersionHidingCursorAdapter(String versionColumnName, Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
this.versionColumnName = versionColumnName;
ctxt = context;
originalBinder = getViewBinder();
setViewBinder( new ViewBinder(){
@Override
public boolean setViewValue(View view, Cursor cursor,
int columnIndex) {
String columnName = cursor.getColumnName(columnIndex);
if ( !columnName.equals(VersionHidingCursorAdapter.this.versionColumnName) ) {
if ( originalBinder != null ) {
return originalBinder.setViewValue(view, cursor, columnIndex);
}
return false;
} else {
String version = cursor.getString(columnIndex);
TextView v = (TextView) view;
if ( version != null ) {
v.setText(ctxt.getString(R.string.version) + " " + version);
v.setVisibility(View.VISIBLE);
} else {
v.setText(null);
v.setVisibility(View.GONE);
}
}
return true;
}} );
}
} | 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.utilities;
import org.javarosa.xform.parse.XFormParser;
import org.kxml2.kdom.Document;
import org.kxml2.kdom.Element;
import org.kxml2.kdom.Node;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
/**
* Static methods used for common file operations.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class FileUtils {
private final static String t = "FileUtils";
// Used to validate and display valid form names.
public static final String VALID_FILENAME = "[ _\\-A-Za-z0-9]*.x[ht]*ml";
public static final String FORMID = "formid";
public static final String VERSION = "version"; // arbitrary string in OpenRosa 1.0
public static final String TITLE = "title";
public static final String SUBMISSIONURI = "submission";
public static final String BASE64_RSA_PUBLIC_KEY = "base64RsaPublicKey";
public static boolean createFolder(String path) {
boolean made = true;
File dir = new File(path);
if (!dir.exists()) {
made = dir.mkdirs();
}
return made;
}
public static byte[] getFileAsBytes(File file) {
byte[] bytes = null;
InputStream is = null;
try {
is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
Log.e(t, "File " + file.getName() + "is too large");
return null;
}
// Create the byte array to hold the data
bytes = new byte[(int) length];
// Read in the bytes
int offset = 0;
int read = 0;
try {
while (offset < bytes.length && read >= 0) {
read = is.read(bytes, offset, bytes.length - offset);
offset += read;
}
} catch (IOException e) {
Log.e(t, "Cannot read " + file.getName());
e.printStackTrace();
return null;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
try {
throw new IOException("Could not completely read file " + file.getName());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return bytes;
} catch (FileNotFoundException e) {
Log.e(t, "Cannot find " + file.getName());
e.printStackTrace();
return null;
} finally {
// Close the input stream
try {
is.close();
} catch (IOException e) {
Log.e(t, "Cannot close input stream for " + file.getName());
e.printStackTrace();
return null;
}
}
}
public static String getMd5Hash(File file) {
try {
// CTS (6/15/2010) : stream file through digest instead of handing it the byte[]
MessageDigest md = MessageDigest.getInstance("MD5");
int chunkSize = 256;
byte[] chunk = new byte[chunkSize];
// Get the size of the file
long lLength = file.length();
if (lLength > Integer.MAX_VALUE) {
Log.e(t, "File " + file.getName() + "is too large");
return null;
}
int length = (int) lLength;
InputStream is = null;
is = new FileInputStream(file);
int l = 0;
for (l = 0; l + chunkSize < length; l += chunkSize) {
is.read(chunk, 0, chunkSize);
md.update(chunk, 0, chunkSize);
}
int remaining = length - l;
if (remaining > 0) {
is.read(chunk, 0, remaining);
md.update(chunk, 0, remaining);
}
byte[] messageDigest = md.digest();
BigInteger number = new BigInteger(1, messageDigest);
String md5 = number.toString(16);
while (md5.length() < 32)
md5 = "0" + md5;
is.close();
return md5;
} catch (NoSuchAlgorithmException e) {
Log.e("MD5", e.getMessage());
return null;
} catch (FileNotFoundException e) {
Log.e("No Cache File", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Problem reading from file", e.getMessage());
return null;
}
}
public static Bitmap getBitmapScaledToDisplay(File f, int screenHeight, int screenWidth) {
// Determine image size of f
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(f.getAbsolutePath(), o);
int heightScale = o.outHeight / screenHeight;
int widthScale = o.outWidth / screenWidth;
// Powers of 2 work faster, sometimes, according to the doc.
// We're just doing closest size that still fills the screen.
int scale = Math.max(widthScale, heightScale);
// get bitmap with scale ( < 1 is the same as 1)
BitmapFactory.Options options = new BitmapFactory.Options();
options.inInputShareable = true;
options.inPurgeable = true;
options.inSampleSize = scale;
Bitmap b = BitmapFactory.decodeFile(f.getAbsolutePath(), options);
if (b != null) {
Log.i(t,
"Screen is " + screenHeight + "x" + screenWidth + ". Image has been scaled down by "
+ scale + " to " + b.getHeight() + "x" + b.getWidth());
}
return b;
}
public static void copyFile(File sourceFile, File destFile) {
if (sourceFile.exists()) {
FileChannel src;
try {
src = new FileInputStream(sourceFile).getChannel();
FileChannel dst = new FileOutputStream(destFile).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
} catch (FileNotFoundException e) {
Log.e(t, "FileNotFoundExeception while copying audio");
e.printStackTrace();
} catch (IOException e) {
Log.e(t, "IOExeception while copying audio");
e.printStackTrace();
}
} else {
Log.e(t, "Source file does not exist: " + sourceFile.getAbsolutePath());
}
}
public static HashMap<String, String> parseXML(File xmlFile) {
HashMap<String, String> fields = new HashMap<String, String>();
InputStream is;
try {
is = new FileInputStream(xmlFile);
} catch (FileNotFoundException e1) {
throw new IllegalStateException(e1);
}
InputStreamReader isr;
try {
isr = new InputStreamReader(is, "UTF-8");
} catch (UnsupportedEncodingException uee) {
Log.w(t, "UTF 8 encoding unavailable, trying default encoding");
isr = new InputStreamReader(is);
}
if (isr != null) {
Document doc;
try {
doc = XFormParser.getXMLDocument(isr);
} finally {
try {
isr.close();
} catch (IOException e) {
Log.w(t, xmlFile.getAbsolutePath() + " Error closing form reader");
e.printStackTrace();
}
}
String xforms = "http://www.w3.org/2002/xforms";
String html = doc.getRootElement().getNamespace();
Element head = doc.getRootElement().getElement(html, "head");
Element title = head.getElement(html, "title");
if (title != null) {
fields.put(TITLE, XFormParser.getXMLText(title, true));
}
Element model = getChildElement(head, "model");
Element cur = getChildElement(model,"instance");
int idx = cur.getChildCount();
int i;
for (i = 0; i < idx; ++i) {
if (cur.isText(i))
continue;
if (cur.getType(i) == Node.ELEMENT) {
break;
}
}
if (i < idx) {
cur = cur.getElement(i); // this is the first data element
String id = cur.getAttributeValue(null, "id");
String xmlns = cur.getNamespace();
String version = cur.getAttributeValue(null, "version");
String uiVersion = cur.getAttributeValue(null, "uiVersion");
if ( uiVersion != null ) {
// pre-OpenRosa 1.0 variant of spec
Log.e(t, "Obsolete use of uiVersion -- IGNORED -- only using version: " + version);
}
fields.put(FORMID, (id == null) ? xmlns : id);
fields.put(VERSION, (version == null) ? null : version);
} else {
throw new IllegalStateException(xmlFile.getAbsolutePath() + " could not be parsed");
}
try {
Element submission = model.getElement(xforms, "submission");
String submissionUri = submission.getAttributeValue(null, "action");
fields.put(SUBMISSIONURI, (submissionUri == null) ? null : submissionUri);
String base64RsaPublicKey = submission.getAttributeValue(null, "base64RsaPublicKey");
fields.put(BASE64_RSA_PUBLIC_KEY,
(base64RsaPublicKey == null || base64RsaPublicKey.trim().length() == 0)
? null : base64RsaPublicKey.trim());
} catch (Exception e) {
Log.i(t, xmlFile.getAbsolutePath() + " does not have a submission element");
// and that's totally fine.
}
}
return fields;
}
// needed because element.getelement fails when there are attributes
private static Element getChildElement(Element parent, String childName) {
Element e = null;
int c = parent.getChildCount();
int i = 0;
for (i = 0; i < c; i++) {
if (parent.getType(i) == Node.ELEMENT) {
if (parent.getElement(i).getName().equalsIgnoreCase(childName)) {
return parent.getElement(i);
}
}
}
return e;
}
}
| 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.utilities;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.List;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.kxml2.io.KXmlSerializer;
import org.kxml2.kdom.Document;
import org.kxml2.kdom.Element;
import org.kxml2.kdom.Node;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.logic.FormController.InstanceMetadata;
import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
/**
* Utility class for encrypting submissions during the SaveToDiskTask.
*
* @author mitchellsundt@gmail.com
*
*/
public class EncryptionUtils {
private static final String t = "EncryptionUtils";
public static final String RSA_ALGORITHM = "RSA";
// the symmetric key we are encrypting with RSA is only 256 bits... use SHA-256
public static final String ASYMMETRIC_ALGORITHM = "RSA/NONE/OAEPWithSHA256AndMGF1Padding";
public static final String SYMMETRIC_ALGORITHM = "AES/CFB/PKCS5Padding";
public static final String UTF_8 = "UTF-8";
public static final int SYMMETRIC_KEY_LENGTH = 256;
public static final int IV_BYTE_LENGTH = 16;
// tags in the submission manifest
private static final String XML_ENCRYPTED_TAG_NAMESPACE = "http://www.opendatakit.org/xforms/encrypted";
private static final String XML_OPENROSA_NAMESPACE = "http://openrosa.org/xforms";
private static final String DATA = "data";
private static final String ID = "id";
private static final String VERSION = "version";
private static final String ENCRYPTED = "encrypted";
private static final String BASE64_ENCRYPTED_KEY = "base64EncryptedKey";
private static final String ENCRYPTED_XML_FILE = "encryptedXmlFile";
private static final String META = "meta";
private static final String INSTANCE_ID = "instanceID";
private static final String MEDIA = "media";
private static final String FILE = "file";
private static final String BASE64_ENCRYPTED_ELEMENT_SIGNATURE = "base64EncryptedElementSignature";
private static final String NEW_LINE = "\n";
private EncryptionUtils() {
};
public static final class EncryptedFormInformation {
public final String formId;
public final String formVersion;
public final InstanceMetadata instanceMetadata;
public final PublicKey rsaPublicKey;
public final String base64RsaEncryptedSymmetricKey;
public final SecretKeySpec symmetricKey;
public final byte[] ivSeedArray;
private int ivCounter = 0;
public final StringBuilder elementSignatureSource = new StringBuilder();
public final Base64Wrapper wrapper;
EncryptedFormInformation(String formId, String formVersion,
InstanceMetadata instanceMetadata, PublicKey rsaPublicKey, Base64Wrapper wrapper) {
this.formId = formId;
this.formVersion = formVersion;
this.instanceMetadata = instanceMetadata;
this.rsaPublicKey = rsaPublicKey;
this.wrapper = wrapper;
// generate the symmetric key from random bits...
SecureRandom r = new SecureRandom();
byte[] key = new byte[SYMMETRIC_KEY_LENGTH/8];
r.nextBytes(key);
SecretKeySpec sk = new SecretKeySpec(key, SYMMETRIC_ALGORITHM);
symmetricKey = sk;
// construct the fixed portion of the iv -- the ivSeedArray
// this is the md5 hash of the instanceID and the symmetric key
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(instanceMetadata.instanceId.getBytes(UTF_8));
md.update(key);
byte[] messageDigest = md.digest();
ivSeedArray = new byte[IV_BYTE_LENGTH];
for ( int i = 0 ; i < IV_BYTE_LENGTH ; ++i ) {
ivSeedArray[i] = messageDigest[(i % messageDigest.length)];
}
} catch (NoSuchAlgorithmException e) {
Log.e(t, e.toString());
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (UnsupportedEncodingException e) {
Log.e(t, e.toString());
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
}
// construct the base64-encoded RSA-encrypted symmetric key
try {
Cipher pkCipher;
pkCipher = Cipher.getInstance(ASYMMETRIC_ALGORITHM);
// write AES key
pkCipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);
byte[] pkEncryptedKey = pkCipher.doFinal(key);
String alg = pkCipher.getAlgorithm();
Log.i(t, "AlgorithmUsed: " + alg);
base64RsaEncryptedSymmetricKey = wrapper
.encodeToString(pkEncryptedKey);
} catch (NoSuchAlgorithmException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (NoSuchPaddingException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (InvalidKeyException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (IllegalBlockSizeException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (BadPaddingException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
}
// start building elementSignatureSource...
appendElementSignatureSource(formId);
if ( formVersion != null ) {
appendElementSignatureSource(formVersion.toString());
}
appendElementSignatureSource(base64RsaEncryptedSymmetricKey);
appendElementSignatureSource( instanceMetadata.instanceId );
}
public void appendElementSignatureSource(String value) {
elementSignatureSource.append(value).append("\n");
}
public void appendFileSignatureSource(File file) {
String md5Hash = FileUtils.getMd5Hash(file);
appendElementSignatureSource(file.getName()+"::"+md5Hash);
}
public String getBase64EncryptedElementSignature() {
// Step 0: construct the text of the elements in elementSignatureSource (done)
// Where...
// * Elements are separated by newline characters.
// * Filename is the unencrypted filename (no .enc suffix).
// * Md5 hashes of the unencrypted files' contents are converted
// to zero-padded 32-character strings before concatenation.
// Assumes this is in the order:
// formId
// version (omitted if null)
// base64RsaEncryptedSymmetricKey
// instanceId
// for each media file { filename "::" md5Hash }
// submission.xml "::" md5Hash
// Step 1: construct the (raw) md5 hash of Step 0.
byte[] messageDigest;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(elementSignatureSource.toString().getBytes(UTF_8));
messageDigest = md.digest();
} catch (NoSuchAlgorithmException e) {
Log.e(t, e.toString());
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (UnsupportedEncodingException e) {
Log.e(t, e.toString());
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
}
// Step 2: construct the base64-encoded RSA-encrypted md5
try {
Cipher pkCipher;
pkCipher = Cipher.getInstance(ASYMMETRIC_ALGORITHM);
// write AES key
pkCipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);
byte[] pkEncryptedKey = pkCipher.doFinal(messageDigest);
return wrapper.encodeToString(pkEncryptedKey);
} catch (NoSuchAlgorithmException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (NoSuchPaddingException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (InvalidKeyException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (IllegalBlockSizeException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (BadPaddingException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
}
}
public Cipher getCipher() throws InvalidKeyException,
InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException {
++ivSeedArray[ivCounter % ivSeedArray.length];
++ivCounter;
IvParameterSpec baseIv = new IvParameterSpec(ivSeedArray);
Cipher c = Cipher.getInstance(EncryptionUtils.SYMMETRIC_ALGORITHM);
c.init(Cipher.ENCRYPT_MODE, symmetricKey, baseIv);
return c;
}
}
/**
* Retrieve the encryption information for this uri.
*
* @param mUri either an instance URI (if previously saved) or a form URI
* @param instanceMetadata
* @return
*/
public static EncryptedFormInformation getEncryptedFormInformation(Uri mUri, InstanceMetadata instanceMetadata) {
ContentResolver cr = Collect.getInstance().getContentResolver();
// fetch the form information
String formId;
String formVersion;
PublicKey pk;
Base64Wrapper wrapper;
Cursor formCursor = null;
try {
if (cr.getType(mUri) == InstanceColumns.CONTENT_ITEM_TYPE) {
// chain back to the Form record...
String[] selectionArgs = null;
String selection = null;
Cursor instanceCursor = null;
try {
instanceCursor = cr.query(mUri, null, null, null, null);
if ( instanceCursor.getCount() != 1 ) {
Log.e(t, "Not exactly one record for this instance!");
return null; // save unencrypted.
}
instanceCursor.moveToFirst();
String jrFormId = instanceCursor.getString(instanceCursor.getColumnIndex(InstanceColumns.JR_FORM_ID));
int idxJrVersion = instanceCursor.getColumnIndex(InstanceColumns.JR_VERSION);
if ( !instanceCursor.isNull(idxJrVersion) ) {
selectionArgs = new String[] {jrFormId, instanceCursor.getString(idxJrVersion)};
selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + "=?";
} else {
selectionArgs = new String[] {jrFormId};
selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + " IS NULL";
}
} finally {
if ( instanceCursor != null ) {
instanceCursor.close();
}
}
formCursor = cr.query(FormsColumns.CONTENT_URI, null, selection, selectionArgs,
null);
if (formCursor.getCount() != 1) {
Log.e(t, "Not exactly one blank form matches this jr_form_id");
return null; // save unencrypted
}
formCursor.moveToFirst();
} else if (cr.getType(mUri) == FormsColumns.CONTENT_ITEM_TYPE) {
formCursor = cr.query(mUri, null, null, null, null);
if ( formCursor.getCount() != 1 ) {
Log.e(t, "Not exactly one blank form!");
return null; // save unencrypted.
}
formCursor.moveToFirst();
}
formId = formCursor.getString(formCursor.getColumnIndex(FormsColumns.JR_FORM_ID));
if (formId == null || formId.length() == 0) {
Log.e(t, "No FormId specified???");
return null;
}
int idxVersion = formCursor.getColumnIndex(FormsColumns.JR_VERSION);
int idxBase64RsaPublicKey = formCursor.getColumnIndex(FormsColumns.BASE64_RSA_PUBLIC_KEY);
formVersion = formCursor.isNull(idxVersion) ? null : formCursor.getString(idxVersion);
String base64RsaPublicKey = formCursor.isNull(idxBase64RsaPublicKey)
? null : formCursor.getString(idxBase64RsaPublicKey);
if (base64RsaPublicKey == null || base64RsaPublicKey.length() == 0) {
return null; // this is legitimately not an encrypted form
}
int version = android.os.Build.VERSION.SDK_INT;
if (version < 8) {
Log.e(t, "Phone does not support encryption.");
return null; // save unencrypted
}
// this constructor will throw an exception if we are not
// running on version 8 or above (if Base64 is not found).
try {
wrapper = new Base64Wrapper();
} catch (ClassNotFoundException e) {
Log.e(t, "Phone does not have Base64 class but API level is "
+ version);
e.printStackTrace();
return null; // save unencrypted
}
// OK -- Base64 decode (requires API Version 8 or higher)
byte[] publicKey = wrapper.decode(base64RsaPublicKey);
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKey);
KeyFactory kf;
try {
kf = KeyFactory.getInstance(RSA_ALGORITHM);
} catch (NoSuchAlgorithmException e) {
Log.e(t, "Phone does not support RSA encryption.");
e.printStackTrace();
return null;
}
try {
pk = kf.generatePublic(publicKeySpec);
} catch (InvalidKeySpecException e) {
e.printStackTrace();
Log.e(t, "Invalid RSA public key.");
return null;
}
} finally {
if (formCursor != null) {
formCursor.close();
}
}
// submission must have an OpenRosa metadata block with a non-null
// instanceID value.
if (instanceMetadata.instanceId == null) {
Log.e(t, "No OpenRosa metadata block or no instanceId defined in that block");
return null;
}
return new EncryptedFormInformation(formId, formVersion, instanceMetadata,
pk, wrapper);
}
private static void encryptFile(File file, EncryptedFormInformation formInfo)
throws IOException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException,
InvalidAlgorithmParameterException {
File encryptedFile = new File(file.getParentFile(), file.getName()
+ ".enc");
// add elementSignatureSource for this file...
formInfo.appendFileSignatureSource(file);
try {
Cipher c = formInfo.getCipher();
OutputStream fout;
fout = new FileOutputStream(encryptedFile);
fout = new CipherOutputStream(fout, c);
InputStream fin;
fin = new FileInputStream(file);
byte[] buffer = new byte[2048];
int len = fin.read(buffer);
while (len != -1) {
fout.write(buffer, 0, len);
len = fin.read(buffer);
}
fin.close();
fout.flush();
fout.close();
Log.i(t,
"Encrpyted:" + file.getName() + " -> "
+ encryptedFile.getName());
} catch (IOException e) {
Log.e(t, "Error encrypting: " + file.getName() + " -> "
+ encryptedFile.getName());
e.printStackTrace();
throw e;
} catch (NoSuchAlgorithmException e) {
Log.e(t, "Error encrypting: " + file.getName() + " -> "
+ encryptedFile.getName());
e.printStackTrace();
throw e;
} catch (NoSuchPaddingException e) {
Log.e(t, "Error encrypting: " + file.getName() + " -> "
+ encryptedFile.getName());
e.printStackTrace();
throw e;
} catch (InvalidKeyException e) {
Log.e(t, "Error encrypting: " + file.getName() + " -> "
+ encryptedFile.getName());
e.printStackTrace();
throw e;
} catch (InvalidAlgorithmParameterException e) {
Log.e(t, "Error encrypting: " + file.getName() + " -> "
+ encryptedFile.getName());
e.printStackTrace();
throw e;
}
}
public static boolean deletePlaintextFiles(File instanceXml) {
// NOTE: assume the directory containing the instanceXml contains ONLY
// files related to this one instance.
File instanceDir = instanceXml.getParentFile();
boolean allSuccessful = true;
// encrypt files that do not end with ".enc", and do not start with ".";
// ignore directories
File[] allFiles = instanceDir.listFiles();
for (File f : allFiles) {
if (f.equals(instanceXml))
continue; // don't touch instance file
if (f.isDirectory())
continue; // don't handle directories
if (!f.getName().endsWith(".enc")) {
// not an encrypted file -- delete it!
allSuccessful = allSuccessful & f.delete(); // DO NOT
// short-circuit
}
}
return allSuccessful;
}
private static List<File> encryptSubmissionFiles(File instanceXml,
File submissionXml, EncryptedFormInformation formInfo) {
// NOTE: assume the directory containing the instanceXml contains ONLY
// files related to this one instance.
File instanceDir = instanceXml.getParentFile();
// encrypt files that do not end with ".enc", and do not start with ".";
// ignore directories
File[] allFiles = instanceDir.listFiles();
List<File> filesToProcess = new ArrayList<File>();
for (File f : allFiles) {
if (f.equals(instanceXml))
continue; // don't touch restore file
if (f.equals(submissionXml))
continue; // handled last
if (f.isDirectory())
continue; // don't handle directories
if (f.getName().startsWith("."))
continue; // MacOSX garbage
if (f.getName().endsWith(".enc")) {
f.delete(); // try to delete this (leftover junk)
} else {
filesToProcess.add(f);
}
}
// encrypt here...
for (File f : filesToProcess) {
try {
encryptFile(f, formInfo);
} catch (IOException e) {
return null;
} catch (InvalidKeyException e) {
return null;
} catch (NoSuchAlgorithmException e) {
return null;
} catch (NoSuchPaddingException e) {
return null;
} catch (InvalidAlgorithmParameterException e) {
return null;
}
}
// encrypt the submission.xml as the last file...
try {
encryptFile(submissionXml, formInfo);
} catch (IOException e) {
return null;
} catch (InvalidKeyException e) {
return null;
} catch (NoSuchAlgorithmException e) {
return null;
} catch (NoSuchPaddingException e) {
return null;
} catch (InvalidAlgorithmParameterException e) {
return null;
}
return filesToProcess;
}
/**
* Constructs the encrypted attachments, encrypted form xml, and the
* plaintext submission manifest (with signature) for the form submission.
*
* Does not delete any of the original files.
*
* @param instanceXml
* @param submissionXml
* @param metadata
* @param formInfo
* @return
*/
public static boolean generateEncryptedSubmission(File instanceXml,
File submissionXml, EncryptedFormInformation formInfo) {
// submissionXml is the submission data to be published to Aggregate
if (!submissionXml.exists() || !submissionXml.isFile()) {
Log.e(t, "No submission.xml found");
return false;
}
// TODO: confirm that this xml is not already encrypted...
// Step 1: encrypt the submission and all the media files...
List<File> mediaFiles = encryptSubmissionFiles(instanceXml,
submissionXml, formInfo);
if (mediaFiles == null) {
return false; // something failed...
}
// Step 2: build the encrypted-submission manifest (overwrites
// submission.xml)...
if (!writeSubmissionManifest(formInfo, submissionXml, mediaFiles)) {
return false;
}
return true;
}
private static boolean writeSubmissionManifest(
EncryptedFormInformation formInfo,
File submissionXml, List<File> mediaFiles) {
Document d = new Document();
d.setStandalone(true);
d.setEncoding(UTF_8);
Element e = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, DATA);
e.setPrefix(null, XML_ENCRYPTED_TAG_NAMESPACE);
e.setAttribute(null, ID, formInfo.formId);
if ( formInfo.formVersion != null ) {
e.setAttribute(null, VERSION, formInfo.formVersion);
}
e.setAttribute(null, ENCRYPTED, "yes");
d.addChild(0, Node.ELEMENT, e);
int idx = 0;
Element c;
c = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, BASE64_ENCRYPTED_KEY);
c.addChild(0, Node.TEXT, formInfo.base64RsaEncryptedSymmetricKey);
e.addChild(idx++, Node.ELEMENT, c);
c = d.createElement(XML_OPENROSA_NAMESPACE, META);
c.setPrefix("orx", XML_OPENROSA_NAMESPACE);
{
Element instanceTag = d.createElement(XML_OPENROSA_NAMESPACE, INSTANCE_ID);
instanceTag.addChild(0, Node.TEXT, formInfo.instanceMetadata.instanceId);
c.addChild(0, Node.ELEMENT, instanceTag);
}
e.addChild(idx++, Node.ELEMENT, c);
e.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);
for (File file : mediaFiles) {
c = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, MEDIA);
Element fileTag = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, FILE);
fileTag.addChild(0, Node.TEXT, file.getName() + ".enc");
c.addChild(0, Node.ELEMENT, fileTag);
e.addChild(idx++, Node.ELEMENT, c);
e.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);
}
c = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, ENCRYPTED_XML_FILE);
c.addChild(0, Node.TEXT, submissionXml.getName() + ".enc");
e.addChild(idx++, Node.ELEMENT, c);
c = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, BASE64_ENCRYPTED_ELEMENT_SIGNATURE);
c.addChild(0, Node.TEXT, formInfo.getBase64EncryptedElementSignature());
e.addChild(idx++, Node.ELEMENT, c);
FileOutputStream out;
try {
out = new FileOutputStream(submissionXml);
OutputStreamWriter writer = new OutputStreamWriter(out, UTF_8);
KXmlSerializer serializer = new KXmlSerializer();
serializer.setOutput(writer);
// setting the response content type emits the xml header.
// just write the body here...
d.writeChildren(serializer);
serializer.flush();
writer.flush();
writer.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
Log.e(t, "Error writing submission.xml for encrypted submission: "
+ submissionXml.getParentFile().getName());
return false;
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
Log.e(t, "Error writing submission.xml for encrypted submission: "
+ submissionXml.getParentFile().getName());
return false;
} catch (IOException ex) {
ex.printStackTrace();
Log.e(t, "Error writing submission.xml for encrypted submission: "
+ submissionXml.getParentFile().getName());
return false;
}
return true;
}
}
| 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.utilities;
import org.odk.collect.android.R;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.HorizontalScrollView;
import android.widget.ScrollView;
/**
* Based heavily upon:
* http://www.yougli.net/android/a-photoshop-like-color-picker
* -for-your-android-application/
*
* @author BehrAtherton@gmail.com
* @author yougli@yougli.net
*
*/
public class ColorPickerDialog extends Dialog {
public interface OnColorChangedListener {
void colorChanged(String key, int color);
}
private OnColorChangedListener mListener;
private int mInitialColor, mDefaultColor;
private String mKey;
/**
* Modified HorizontalScrollView that communicates scroll
* actions to interior Vertical scroll view.
* From: http://stackoverflow.com/questions/3866499/two-directional-scroll-view
*
*/
public class WScrollView extends HorizontalScrollView
{
public ScrollView sv;
public WScrollView(Context context)
{
super(context);
}
public WScrollView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public WScrollView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
@Override public boolean onTouchEvent(MotionEvent event)
{
boolean ret = super.onTouchEvent(event);
ret = ret | sv.onTouchEvent(event);
return ret;
}
@Override public boolean onInterceptTouchEvent(MotionEvent event)
{
boolean ret = super.onInterceptTouchEvent(event);
ret = ret | sv.onInterceptTouchEvent(event);
return ret;
}
}
private static class ColorPickerView extends View {
private Paint mPaint;
private float mCurrentHue = 0;
private int mCurrentX = 0, mCurrentY = 0;
private int mCurrentColor, mDefaultColor;
private final int[] mHueBarColors = new int[258];
private int[] mMainColors = new int[65536];
private OnColorChangedListener mListener;
ColorPickerView(Context c, OnColorChangedListener l, int color,
int defaultColor) {
super(c);
mListener = l;
mDefaultColor = defaultColor;
// Get the current hue from the current color and update the main
// color field
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
mCurrentHue = hsv[0];
updateMainColors();
mCurrentColor = color;
// Initialize the colors of the hue slider bar
int index = 0;
for (float i = 0; i < 256; i += 256 / 42) // Red (#f00) to pink
// (#f0f)
{
mHueBarColors[index] = Color.rgb(255, 0, (int) i);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) // Pink (#f0f) to blue
// (#00f)
{
mHueBarColors[index] = Color.rgb(255 - (int) i, 0, 255);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) // Blue (#00f) to light
// blue (#0ff)
{
mHueBarColors[index] = Color.rgb(0, (int) i, 255);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) // Light blue (#0ff) to
// green (#0f0)
{
mHueBarColors[index] = Color.rgb(0, 255, 255 - (int) i);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) // Green (#0f0) to yellow
// (#ff0)
{
mHueBarColors[index] = Color.rgb((int) i, 255, 0);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) // Yellow (#ff0) to red
// (#f00)
{
mHueBarColors[index] = Color.rgb(255, 255 - (int) i, 0);
index++;
}
// Initializes the Paint that will draw the View
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setTextAlign(Paint.Align.CENTER);
mPaint.setTextSize(12);
}
// Get the current selected color from the hue bar
private int getCurrentMainColor() {
int translatedHue = 255 - (int) (mCurrentHue * 255 / 360);
int index = 0;
for (float i = 0; i < 256; i += 256 / 42) {
if (index == translatedHue)
return Color.rgb(255, 0, (int) i);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) {
if (index == translatedHue)
return Color.rgb(255 - (int) i, 0, 255);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) {
if (index == translatedHue)
return Color.rgb(0, (int) i, 255);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) {
if (index == translatedHue)
return Color.rgb(0, 255, 255 - (int) i);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) {
if (index == translatedHue)
return Color.rgb((int) i, 255, 0);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) {
if (index == translatedHue)
return Color.rgb(255, 255 - (int) i, 0);
index++;
}
return Color.RED;
}
// Update the main field colors depending on the current selected hue
private void updateMainColors() {
int mainColor = getCurrentMainColor();
int index = 0;
int[] topColors = new int[256];
for (int y = 0; y < 256; y++) {
for (int x = 0; x < 256; x++) {
if (y == 0) {
mMainColors[index] = Color.rgb(
255 - (255 - Color.red(mainColor)) * x / 255,
255 - (255 - Color.green(mainColor)) * x / 255,
255 - (255 - Color.blue(mainColor)) * x / 255);
topColors[x] = mMainColors[index];
} else
mMainColors[index] = Color.rgb(
(255 - y) * Color.red(topColors[x]) / 255,
(255 - y) * Color.green(topColors[x]) / 255,
(255 - y) * Color.blue(topColors[x]) / 255);
index++;
}
}
}
@Override
protected void onDraw(Canvas canvas) {
int translatedHue = 255 - (int) (mCurrentHue * 255 / 360);
// Display all the colors of the hue bar with lines
for (int x = 0; x < 256; x++) {
// If this is not the current selected hue, display the actual
// color
if (translatedHue != x) {
mPaint.setColor(mHueBarColors[x]);
mPaint.setStrokeWidth(1);
} else // else display a slightly larger black line
{
mPaint.setColor(Color.BLACK);
mPaint.setStrokeWidth(3);
}
canvas.drawLine(x + 10, 0, x + 10, 40, mPaint);
}
// Display the main field colors using LinearGradient
for (int x = 0; x < 256; x++) {
int[] colors = new int[2];
colors[0] = mMainColors[x];
colors[1] = Color.BLACK;
Shader shader = new LinearGradient(0, 50, 0, 306, colors, null,
Shader.TileMode.REPEAT);
mPaint.setShader(shader);
canvas.drawLine(x + 10, 50, x + 10, 306, mPaint);
}
mPaint.setShader(null);
// Display the circle around the currently selected color in the
// main field
if (mCurrentX != 0 && mCurrentY != 0) {
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(Color.BLACK);
canvas.drawCircle(mCurrentX, mCurrentY, 10, mPaint);
}
// Draw a 'button' with the currently selected color
mPaint.setStyle(Paint.Style.FILL);
mPaint.setColor(mCurrentColor);
canvas.drawRect(10, 316, 138, 356, mPaint);
// Set the text color according to the brightness of the color
mPaint.setColor(getInverseColor(mCurrentColor));
canvas.drawText(getContext().getString(R.string.ok), 74, 340,
mPaint);
// Draw a 'button' with the default color
mPaint.setStyle(Paint.Style.FILL);
mPaint.setColor(mDefaultColor);
canvas.drawRect(138, 316, 266, 356, mPaint);
// Set the text color according to the brightness of the color
mPaint.setColor(getInverseColor(mDefaultColor));
canvas.drawText(getContext().getString(R.string.cancel), 202, 340,
mPaint);
}
private int getInverseColor(int color) {
int red = Color.red(color);
int green = Color.green(color);
int blue = Color.blue(color);
int alpha = Color.alpha(color);
return Color.argb(alpha, 255 - red, 255 - green, 255 - blue);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(276, 366);
}
private boolean afterFirstDown = false;
private float startX;
private float startY;
@Override
public boolean onTouchEvent(MotionEvent event) {
// allow scrolling...
boolean ret = super.onTouchEvent(event);
int action = event.getAction();
int pointerCount = event.getPointerCount();
if ( action == MotionEvent.ACTION_CANCEL ) {
afterFirstDown = false;
} else if ( pointerCount == 1 && action == MotionEvent.ACTION_DOWN ) {
afterFirstDown = true;
startX = event.getX();
startY = event.getY();
} else if ( pointerCount == 1 && action == MotionEvent.ACTION_MOVE && !afterFirstDown ) {
afterFirstDown = true;
startX = event.getX();
startY = event.getY();
}
if ( !afterFirstDown || pointerCount != 1 || action != MotionEvent.ACTION_UP ) {
return true;
}
// on an ACTION_UP, we reset the afterFirstDown flag.
// processing uses the lifting of the finger to choose
// the color...
afterFirstDown = false;
float x = event.getX();
float y = event.getY();
if ( Math.abs(x - startX) > 10 && Math.abs(y - startY) > 10 ) {
// the color location drifted, so it must just be a scrolling action
// ignore it...
return ret;
}
// If the touch event is located in the hue bar
if (x > 10 && x < 266 && y > 0 && y < 40) {
// Update the main field colors
mCurrentHue = (255 - x) * 360 / 255;
updateMainColors();
// Update the current selected color
int transX = mCurrentX - 10;
int transY = mCurrentY - 60;
int index = 256 * (transY - 1) + transX;
if (index > 0 && index < mMainColors.length)
mCurrentColor = mMainColors[256 * (transY - 1) + transX];
// Force the redraw of the dialog
invalidate();
}
// If the touch event is located in the main field
if (x > 10 && x < 266 && y > 50 && y < 306) {
mCurrentX = (int) x;
mCurrentY = (int) y;
int transX = mCurrentX - 10;
int transY = mCurrentY - 60;
int index = 256 * (transY - 1) + transX;
if (index > 0 && index < mMainColors.length) {
// Update the current color
mCurrentColor = mMainColors[index];
// Force the redraw of the dialog
invalidate();
}
}
// If the touch event is located in the left button, notify the
// listener with the current color
if (x > 10 && x < 138 && y > 316 && y < 356)
mListener.colorChanged("", mCurrentColor);
// If the touch event is located in the right button, notify the
// listener with the default color
if (x > 138 && x < 266 && y > 316 && y < 356)
mListener.colorChanged("", mDefaultColor);
return true;
}
}
public ColorPickerDialog(Context context, OnColorChangedListener listener,
String key, int initialColor, int defaultColor, String title) {
super(context);
mListener = listener;
mKey = key;
mInitialColor = initialColor;
mDefaultColor = defaultColor;
setTitle(title);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
OnColorChangedListener l = new OnColorChangedListener() {
public void colorChanged(String key, int color) {
mListener.colorChanged(mKey, color);
dismiss();
}
};
/*BIDIRECTIONAL SCROLLVIEW*/
ScrollView sv = new ScrollView(this.getContext());
WScrollView hsv = new WScrollView(this.getContext());
hsv.sv = sv;
/*END OF BIDIRECTIONAL SCROLLVIEW*/
sv.addView(new ColorPickerView(getContext(), l, mInitialColor,
mDefaultColor), new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
hsv.addView(sv, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
setContentView(hsv, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
setCanceledOnTouchOutside(true);
}
}
| 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.utilities;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Wrapper class for accessing Base64 functionality.
* This allows API Level 7 deployment of ODK Collect while
* enabling API Level 8 and higher phone to support encryption.
*
* @author mitchellsundt@gmail.com
*
*/
public class Base64Wrapper {
private static final int FLAGS = 2;// NO_WRAP
private Class<?> base64 = null;
public Base64Wrapper() throws ClassNotFoundException {
base64 = this.getClass().getClassLoader()
.loadClass("android.util.Base64");
}
public String encodeToString(byte[] ba) {
Class<?>[] argClassList = new Class[]{byte[].class, int.class};
try {
Method m = base64.getDeclaredMethod("encode", argClassList);
Object[] argList = new Object[]{ ba, FLAGS };
Object o = m.invoke(null, argList);
byte[] outArray = (byte[]) o;
String s = new String(outArray, "UTF-8");
return s;
} catch (SecurityException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.toString());
} catch (NoSuchMethodException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.toString());
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.toString());
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.toString());
}
}
public byte[] decode(String base64String) {
Class<?>[] argClassList = new Class[]{String.class, int.class};
Object o;
try {
Method m = base64.getDeclaredMethod("decode", argClassList);
Object[] argList = new Object[]{ base64String, FLAGS };
o = m.invoke(null, argList);
} catch (SecurityException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.toString());
} catch (NoSuchMethodException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.toString());
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.toString());
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.toString());
}
return (byte[]) o;
}
}
| 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.
*
* Original License from BasicCredentialsProvider:
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.odk.collect.android.utilities;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.opendatakit.httpclientandroidlib.annotation.ThreadSafe;
import org.opendatakit.httpclientandroidlib.auth.AuthScope;
import org.opendatakit.httpclientandroidlib.auth.Credentials;
import org.opendatakit.httpclientandroidlib.client.CredentialsProvider;
/**
* Modified BasicCredentialsProvider that will clear the provider
* after 'expiryInterval' milliseconds of inactivity. Use the WebUtils
* methods to manipulate the credentials in the local context. You should
* first check that the credentials exist (which will reset the expiration
* date), then set them if they are missing.
*
* Largely a cut-and-paste of BasicCredentialsProvider.
*
* @author mitchellsundt@gmail.com
*
*/
@ThreadSafe
public class AgingCredentialsProvider implements CredentialsProvider {
private final ConcurrentHashMap<AuthScope, Credentials> credMap;
private final long expiryInterval;
private long nextClearTimestamp;
/**
* Default constructor.
*/
public AgingCredentialsProvider(int expiryInterval) {
super();
this.credMap = new ConcurrentHashMap<AuthScope, Credentials>();
this.expiryInterval = expiryInterval;
nextClearTimestamp = System.currentTimeMillis() + expiryInterval;
}
public void setCredentials(
final AuthScope authscope,
final Credentials credentials) {
if (authscope == null) {
throw new IllegalArgumentException("Authentication scope may not be null");
}
if (nextClearTimestamp < System.currentTimeMillis()) {
clear();
}
nextClearTimestamp = System.currentTimeMillis() + expiryInterval;
if ( credentials == null ) {
credMap.remove(authscope);
} else {
credMap.put(authscope, credentials);
}
}
/**
* Find matching {@link Credentials credentials} for the given authentication scope.
*
* @param map the credentials hash map
* @param authscope the {@link AuthScope authentication scope}
* @return the credentials
*
*/
private static Credentials matchCredentials(
final Map<AuthScope, Credentials> map,
final AuthScope authscope) {
// see if we get a direct hit
Credentials creds = map.get(authscope);
if (creds == null) {
// Nope.
// Do a full scan
int bestMatchFactor = -1;
AuthScope bestMatch = null;
for (AuthScope current: map.keySet()) {
int factor = authscope.match(current);
if (factor > bestMatchFactor) {
bestMatchFactor = factor;
bestMatch = current;
}
}
if (bestMatch != null) {
creds = map.get(bestMatch);
}
}
return creds;
}
public Credentials getCredentials(final AuthScope authscope) {
if (authscope == null) {
throw new IllegalArgumentException("Authentication scope may not be null");
}
if (nextClearTimestamp < System.currentTimeMillis()) {
clear();
}
nextClearTimestamp = System.currentTimeMillis() + expiryInterval;
Credentials c = matchCredentials(this.credMap, authscope);
return c;
}
public void clear() {
this.credMap.clear();
}
@Override
public String toString() {
return credMap.toString();
}
}
| 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.utilities;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.odk.collect.android.application.Collect;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore.Audio;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Video;
import android.util.Log;
/**
* Consolidate all interactions with media providers here.
*
* @author mitchellsundt@gmail.com
*
*/
public class MediaUtils {
private static final String t = "MediaUtils";
private MediaUtils() {
// static methods only
}
private static String escapePath(String path) {
String ep = path;
ep = ep.replaceAll("\\!", "!!");
ep = ep.replaceAll("_", "!_");
ep = ep.replaceAll("%", "!%");
return ep;
}
public static final Uri getImageUriFromMediaProvider(String imageFile) {
String selection = Images.ImageColumns.DATA + "=?";
String[] selectArgs = { imageFile };
String[] projection = { Images.ImageColumns._ID };
Cursor c = null;
try {
c = Collect.getInstance().getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, selection, selectArgs, null);
if (c.getCount() > 0) {
c.moveToFirst();
String id = c.getString(c.getColumnIndex(Images.ImageColumns._ID));
return Uri.withAppendedPath(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
}
return null;
} finally {
if ( c != null ) {
c.close();
}
}
}
public static final int deleteImageFileFromMediaProvider(String imageFile) {
ContentResolver cr = Collect.getInstance().getContentResolver();
// images
int count = 0;
Cursor imageCursor = null;
try {
String select =
Images.Media.DATA + "=?";
String[] selectArgs = { imageFile };
String[] projection = {
Images.ImageColumns._ID
};
imageCursor = cr.query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, select, selectArgs, null);
if (imageCursor.getCount() > 0) {
imageCursor.moveToFirst();
List<Uri> imagesToDelete = new ArrayList<Uri>();
do {
String id =
imageCursor.getString(imageCursor
.getColumnIndex(Images.ImageColumns._ID));
imagesToDelete.add(Uri.withAppendedPath(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
id));
} while ( imageCursor.moveToNext());
for ( Uri uri : imagesToDelete ) {
Log.i(t,"attempting to delete: " + uri );
count += cr.delete(uri, null, null);
}
}
} catch ( Exception e ) {
Log.e(t, e.toString());
} finally {
if ( imageCursor != null ) {
imageCursor.close();
}
}
File f = new File(imageFile);
if ( f.exists() ) {
f.delete();
}
return count;
}
public static final int deleteImagesInFolderFromMediaProvider(File folder) {
ContentResolver cr = Collect.getInstance().getContentResolver();
// images
int count = 0;
Cursor imageCursor = null;
try {
String select =
Images.Media.DATA + " like ? escape '!'";
String[] selectArgs = { escapePath(folder.getAbsolutePath()) };
String[] projection = {
Images.ImageColumns._ID
};
imageCursor = cr.query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, select, selectArgs, null);
if (imageCursor.getCount() > 0) {
imageCursor.moveToFirst();
List<Uri> imagesToDelete = new ArrayList<Uri>();
do {
String id =
imageCursor.getString(imageCursor
.getColumnIndex(Images.ImageColumns._ID));
imagesToDelete.add(Uri.withAppendedPath(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
id));
} while ( imageCursor.moveToNext());
for ( Uri uri : imagesToDelete ) {
Log.i(t,"attempting to delete: " + uri );
count += cr.delete(uri, null, null);
}
}
} catch ( Exception e ) {
Log.e(t, e.toString());
} finally {
if ( imageCursor != null ) {
imageCursor.close();
}
}
return count;
}
public static final Uri getAudioUriFromMediaProvider(String audioFile) {
String selection = Audio.AudioColumns.DATA + "=?";
String[] selectArgs = { audioFile };
String[] projection = { Audio.AudioColumns._ID };
Cursor c = null;
try {
c = Collect.getInstance().getContentResolver().query(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection, selection, selectArgs, null);
if (c.getCount() > 0) {
c.moveToFirst();
String id = c.getString(c.getColumnIndex(Audio.AudioColumns._ID));
return Uri.withAppendedPath(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
}
return null;
} finally {
if ( c != null ) {
c.close();
}
}
}
public static final int deleteAudioFileFromMediaProvider(String audioFile) {
ContentResolver cr = Collect.getInstance().getContentResolver();
// audio
int count = 0;
Cursor audioCursor = null;
try {
String select =
Audio.Media.DATA + "=?";
String[] selectArgs = { audioFile };
String[] projection = {
Audio.AudioColumns._ID
};
audioCursor = cr.query(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection, select, selectArgs, null);
if (audioCursor.getCount() > 0) {
audioCursor.moveToFirst();
List<Uri> audioToDelete = new ArrayList<Uri>();
do {
String id =
audioCursor.getString(audioCursor
.getColumnIndex(Audio.AudioColumns._ID));
audioToDelete.add(Uri.withAppendedPath(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
id));
} while ( audioCursor.moveToNext());
for ( Uri uri : audioToDelete ) {
Log.i(t,"attempting to delete: " + uri );
count += cr.delete(uri, null, null);
}
}
} catch ( Exception e ) {
Log.e(t, e.toString());
} finally {
if ( audioCursor != null ) {
audioCursor.close();
}
}
File f = new File(audioFile);
if ( f.exists() ) {
f.delete();
}
return count;
}
public static final int deleteAudioInFolderFromMediaProvider(File folder) {
ContentResolver cr = Collect.getInstance().getContentResolver();
// audio
int count = 0;
Cursor audioCursor = null;
try {
String select =
Audio.Media.DATA + " like ? escape '!'";
String[] selectArgs = { escapePath(folder.getAbsolutePath()) };
String[] projection = {
Audio.AudioColumns._ID
};
audioCursor = cr.query(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection, select, selectArgs, null);
if (audioCursor.getCount() > 0) {
audioCursor.moveToFirst();
List<Uri> audioToDelete = new ArrayList<Uri>();
do {
String id =
audioCursor.getString(audioCursor
.getColumnIndex(Audio.AudioColumns._ID));
audioToDelete.add(Uri.withAppendedPath(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
id));
} while ( audioCursor.moveToNext());
for ( Uri uri : audioToDelete ) {
Log.i(t,"attempting to delete: " + uri );
count += cr.delete(uri, null, null);
}
}
} catch ( Exception e ) {
Log.e(t, e.toString());
} finally {
if ( audioCursor != null ) {
audioCursor.close();
}
}
return count;
}
public static final Uri getVideoUriFromMediaProvider(String videoFile) {
String selection = Video.VideoColumns.DATA + "=?";
String[] selectArgs = { videoFile };
String[] projection = { Video.VideoColumns._ID };
Cursor c = null;
try {
c = Collect.getInstance().getContentResolver().query(
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection, selection, selectArgs, null);
if (c.getCount() > 0) {
c.moveToFirst();
String id = c.getString(c.getColumnIndex(Video.VideoColumns._ID));
return Uri.withAppendedPath(
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id);
}
return null;
} finally {
if ( c != null ) {
c.close();
}
}
}
public static final int deleteVideoFileFromMediaProvider(String videoFile) {
ContentResolver cr = Collect.getInstance().getContentResolver();
// video
int count = 0;
Cursor videoCursor = null;
try {
String select =
Video.Media.DATA + "=?";
String[] selectArgs = { videoFile };
String[] projection = {
Video.VideoColumns._ID
};
videoCursor = cr.query(
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection, select, selectArgs, null);
if (videoCursor.getCount() > 0) {
videoCursor.moveToFirst();
List<Uri> videoToDelete = new ArrayList<Uri>();
do {
String id =
videoCursor.getString(videoCursor
.getColumnIndex(Video.VideoColumns._ID));
videoToDelete.add(Uri.withAppendedPath(
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
id));
} while ( videoCursor.moveToNext());
for ( Uri uri : videoToDelete ) {
Log.i(t,"attempting to delete: " + uri );
count += cr.delete(uri, null, null);
}
}
} catch ( Exception e ) {
Log.e(t, e.toString());
} finally {
if ( videoCursor != null ) {
videoCursor.close();
}
}
File f = new File(videoFile);
if ( f.exists() ) {
f.delete();
}
return count;
}
public static final int deleteVideoInFolderFromMediaProvider(File folder) {
ContentResolver cr = Collect.getInstance().getContentResolver();
// video
int count = 0;
Cursor videoCursor = null;
try {
String select =
Video.Media.DATA + " like ? escape '!'";
String[] selectArgs = { escapePath(folder.getAbsolutePath()) };
String[] projection = {
Video.VideoColumns._ID
};
videoCursor = cr.query(
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection, select, selectArgs, null);
if (videoCursor.getCount() > 0) {
videoCursor.moveToFirst();
List<Uri> videoToDelete = new ArrayList<Uri>();
do {
String id =
videoCursor.getString(videoCursor
.getColumnIndex(Video.VideoColumns._ID));
videoToDelete.add(Uri.withAppendedPath(
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
id));
} while ( videoCursor.moveToNext());
for ( Uri uri : videoToDelete ) {
Log.i(t,"attempting to delete: " + uri );
count += cr.delete(uri, null, null);
}
}
} catch ( Exception e ) {
Log.e(t, e.toString());
} finally {
if ( videoCursor != null ) {
videoCursor.close();
}
}
return count;
}
}
| 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.utilities;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import org.apache.http.HttpStatus;
import org.kxml2.io.KXmlParser;
import org.kxml2.kdom.Document;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.opendatakit.httpclientandroidlib.Header;
import org.opendatakit.httpclientandroidlib.HttpEntity;
import org.opendatakit.httpclientandroidlib.HttpHost;
import org.opendatakit.httpclientandroidlib.HttpRequest;
import org.opendatakit.httpclientandroidlib.HttpResponse;
import org.opendatakit.httpclientandroidlib.auth.AuthScope;
import org.opendatakit.httpclientandroidlib.auth.Credentials;
import org.opendatakit.httpclientandroidlib.auth.UsernamePasswordCredentials;
import org.opendatakit.httpclientandroidlib.auth.params.AuthPNames;
import org.opendatakit.httpclientandroidlib.client.AuthCache;
import org.opendatakit.httpclientandroidlib.client.CredentialsProvider;
import org.opendatakit.httpclientandroidlib.client.HttpClient;
import org.opendatakit.httpclientandroidlib.client.methods.HttpGet;
import org.opendatakit.httpclientandroidlib.client.methods.HttpHead;
import org.opendatakit.httpclientandroidlib.client.methods.HttpPost;
import org.opendatakit.httpclientandroidlib.client.params.AuthPolicy;
import org.opendatakit.httpclientandroidlib.client.params.ClientPNames;
import org.opendatakit.httpclientandroidlib.client.params.CookiePolicy;
import org.opendatakit.httpclientandroidlib.client.params.HttpClientParams;
import org.opendatakit.httpclientandroidlib.client.protocol.ClientContext;
import org.opendatakit.httpclientandroidlib.conn.ClientConnectionManager;
import org.opendatakit.httpclientandroidlib.impl.auth.BasicScheme;
import org.opendatakit.httpclientandroidlib.impl.client.BasicAuthCache;
import org.opendatakit.httpclientandroidlib.impl.client.DefaultHttpClient;
import org.opendatakit.httpclientandroidlib.params.BasicHttpParams;
import org.opendatakit.httpclientandroidlib.params.HttpConnectionParams;
import org.opendatakit.httpclientandroidlib.params.HttpParams;
import org.opendatakit.httpclientandroidlib.protocol.HttpContext;
import org.xmlpull.v1.XmlPullParser;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.text.format.DateFormat;
import android.util.Log;
/**
* Common utility methods for managing the credentials associated with the
* request context and constructing http context, client and request with the
* proper parameters and OpenRosa headers.
*
* @author mitchellsundt@gmail.com
*/
public final class WebUtils {
public static final String t = "WebUtils";
public static final String OPEN_ROSA_VERSION_HEADER = "X-OpenRosa-Version";
public static final String OPEN_ROSA_VERSION = "1.0";
private static final String DATE_HEADER = "Date";
public static final String HTTP_CONTENT_TYPE_TEXT_XML = "text/xml";
public static final int CONNECTION_TIMEOUT = 30000;
private static ClientConnectionManager httpConnectionManager = null;
public static final List<AuthScope> buildAuthScopes(String host) {
List<AuthScope> asList = new ArrayList<AuthScope>();
AuthScope a;
// allow digest auth on any port...
a = new AuthScope(host, -1, null, AuthPolicy.DIGEST);
asList.add(a);
// and allow basic auth on the standard TLS/SSL ports...
a = new AuthScope(host, 443, null, AuthPolicy.BASIC);
asList.add(a);
a = new AuthScope(host, 8443, null, AuthPolicy.BASIC);
asList.add(a);
return asList;
}
public static final void clearAllCredentials() {
CredentialsProvider credsProvider = Collect.getInstance()
.getCredentialsProvider();
Log.i(t, "clearAllCredentials");
credsProvider.clear();
}
public static final boolean hasCredentials(String userEmail, String host) {
CredentialsProvider credsProvider = Collect.getInstance()
.getCredentialsProvider();
List<AuthScope> asList = buildAuthScopes(host);
boolean hasCreds = true;
for (AuthScope a : asList) {
Credentials c = credsProvider.getCredentials(a);
if (c == null) {
hasCreds = false;
continue;
}
}
return hasCreds;
}
/**
* Remove all credentials for accessing the specified host.
*
* @param host
*/
private static final void clearHostCredentials(String host) {
CredentialsProvider credsProvider = Collect.getInstance()
.getCredentialsProvider();
Log.i(t, "clearHostCredentials: " + host);
List<AuthScope> asList = buildAuthScopes(host);
for (AuthScope a : asList) {
credsProvider.setCredentials(a, null);
}
}
/**
* Remove all credentials for accessing the specified host and, if the
* username is not null or blank then add a (username, password) credential
* for accessing this host.
*
* @param username
* @param password
* @param host
*/
public static final void addCredentials(String username, String password,
String host) {
// to ensure that this is the only authentication available for this
// host...
clearHostCredentials(host);
if (username != null && username.trim().length() != 0) {
Log.i(t, "adding credential for host: " + host + " username:"
+ username);
Credentials c = new UsernamePasswordCredentials(username, password);
addCredentials(c, host);
}
}
private static final void addCredentials(Credentials c, String host) {
CredentialsProvider credsProvider = Collect.getInstance()
.getCredentialsProvider();
List<AuthScope> asList = buildAuthScopes(host);
for (AuthScope a : asList) {
credsProvider.setCredentials(a, c);
}
}
public static final void enablePreemptiveBasicAuth(
HttpContext localContext, String host) {
AuthCache ac = (AuthCache) localContext
.getAttribute(ClientContext.AUTH_CACHE);
HttpHost h = new HttpHost(host);
if (ac == null) {
ac = new BasicAuthCache();
localContext.setAttribute(ClientContext.AUTH_CACHE, ac);
}
List<AuthScope> asList = buildAuthScopes(host);
for (AuthScope a : asList) {
if (a.getScheme() == AuthPolicy.BASIC) {
ac.put(h, new BasicScheme());
}
}
}
private static final void setOpenRosaHeaders(HttpRequest req) {
req.setHeader(OPEN_ROSA_VERSION_HEADER, OPEN_ROSA_VERSION);
GregorianCalendar g = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
g.setTime(new Date());
req.setHeader(DATE_HEADER,
DateFormat.format("E, dd MMM yyyy hh:mm:ss zz", g).toString());
}
public static final HttpHead createOpenRosaHttpHead(Uri u) {
HttpHead req = new HttpHead(URI.create(u.toString()));
setOpenRosaHeaders(req);
return req;
}
public static final HttpGet createOpenRosaHttpGet(URI uri) {
HttpGet req = new HttpGet();
setOpenRosaHeaders(req);
setGoogleHeaders(req);
req.setURI(uri);
return req;
}
public static final void setGoogleHeaders(HttpRequest req) {
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(Collect.getInstance().getApplicationContext());
String protocol = settings.getString(PreferencesActivity.KEY_PROTOCOL, PreferencesActivity.PROTOCOL_ODK_DEFAULT);
if ( protocol.equals(PreferencesActivity.PROTOCOL_GOOGLE) ) {
String auth = settings.getString(PreferencesActivity.KEY_AUTH, "");
if ((auth != null) && (auth.length() > 0)) {
req.setHeader("Authorization", "GoogleLogin auth=" + auth);
}
}
}
public static final HttpPost createOpenRosaHttpPost(Uri u) {
HttpPost req = new HttpPost(URI.create(u.toString()));
setOpenRosaHeaders(req);
setGoogleHeaders(req);
return req;
}
/**
* Create an httpClient with connection timeouts and other parameters set.
* Save and reuse the connection manager across invocations (this is what
* requires synchronized access).
*
* @param timeout
* @return HttpClient properly configured.
*/
public static final synchronized HttpClient createHttpClient(int timeout) {
// configure connection
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, timeout);
HttpConnectionParams.setSoTimeout(params, 2 * timeout);
// support redirecting to handle http: => https: transition
HttpClientParams.setRedirecting(params, true);
// support authenticating
HttpClientParams.setAuthenticating(params, true);
HttpClientParams.setCookiePolicy(params,
CookiePolicy.BROWSER_COMPATIBILITY);
// if possible, bias toward digest auth (may not be in 4.0 beta 2)
List<String> authPref = new ArrayList<String>();
authPref.add(AuthPolicy.DIGEST);
authPref.add(AuthPolicy.BASIC);
// does this work in Google's 4.0 beta 2 snapshot?
params.setParameter(AuthPNames.TARGET_AUTH_PREF, authPref);
params.setParameter(ClientPNames.MAX_REDIRECTS, 1);
params.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
// setup client
DefaultHttpClient httpclient;
// reuse the connection manager across all clients this ODK Collect
// creates.
if (httpConnectionManager == null) {
// let Apache stack create a connection manager.
httpclient = new DefaultHttpClient(params);
httpConnectionManager = httpclient.getConnectionManager();
} else {
// reuse the connection manager we already got.
httpclient = new DefaultHttpClient(httpConnectionManager, params);
}
return httpclient;
}
/**
* Utility to ensure that the entity stream of a response is drained of
* bytes.
*
* @param response
*/
public static final void discardEntityBytes(HttpResponse response) {
// may be a server that does not handle
HttpEntity entity = response.getEntity();
if (entity != null) {
try {
// have to read the stream in order to reuse the connection
InputStream is = response.getEntity().getContent();
// read to end of stream...
final long count = 1024L;
while (is.skip(count) == count)
;
is.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Common method for returning a parsed xml document given a url and the
* http context and client objects involved in the web connection.
*
* @param urlString
* @param localContext
* @param httpclient
* @return
*/
public static DocumentFetchResult getXmlDocument(String urlString,
HttpContext localContext, HttpClient httpclient) {
URI u = null;
try {
URL url = new URL(urlString);
u = url.toURI();
} catch (Exception e) {
e.printStackTrace();
return new DocumentFetchResult(e.getLocalizedMessage()
// + app.getString(R.string.while_accessing) + urlString);
+ ("while accessing") + urlString, 0);
}
if (u.getHost() == null ) {
return new DocumentFetchResult("Invalid server URL (no hostname): " + urlString, 0);
}
// if https then enable preemptive basic auth...
if (u.getScheme().equals("https")) {
enablePreemptiveBasicAuth(localContext, u.getHost());
}
// set up request...
HttpGet req = WebUtils.createOpenRosaHttpGet(u);
HttpResponse response = null;
try {
response = httpclient.execute(req, localContext);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
if (statusCode != HttpStatus.SC_OK) {
WebUtils.discardEntityBytes(response);
if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
// clear the cookies -- should not be necessary?
Collect.getInstance().getCookieStore().clear();
}
String webError = response.getStatusLine().getReasonPhrase()
+ " (" + statusCode + ")";
return new DocumentFetchResult(u.toString()
+ " responded with: " + webError, statusCode);
}
if (entity == null) {
String error = "No entity body returned from: " + u.toString();
Log.e(t, error);
return new DocumentFetchResult(error, 0);
}
if (!entity.getContentType().getValue().toLowerCase(Locale.ENGLISH)
.contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML)) {
WebUtils.discardEntityBytes(response);
String error = "ContentType: "
+ entity.getContentType().getValue()
+ " returned from: "
+ u.toString()
+ " is not text/xml. This is often caused a network proxy. Do you need to login to your network?";
Log.e(t, error);
return new DocumentFetchResult(error, 0);
}
// parse response
Document doc = null;
try {
InputStream is = null;
InputStreamReader isr = null;
try {
is = entity.getContent();
isr = new InputStreamReader(is, "UTF-8");
doc = new Document();
KXmlParser parser = new KXmlParser();
parser.setInput(isr);
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES,
true);
doc.parse(parser);
isr.close();
isr = null;
} finally {
if (isr != null) {
try {
// ensure stream is consumed...
final long count = 1024L;
while (isr.skip(count) == count)
;
} catch (Exception e) {
// no-op
}
try {
isr.close();
} catch (Exception e) {
// no-op
}
}
if (is != null) {
try {
is.close();
} catch (Exception e) {
// no-op
}
}
}
} catch (Exception e) {
e.printStackTrace();
String error = "Parsing failed with " + e.getMessage()
+ "while accessing " + u.toString();
Log.e(t, error);
return new DocumentFetchResult(error, 0);
}
boolean isOR = false;
Header[] fields = response
.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER);
if (fields != null && fields.length >= 1) {
isOR = true;
boolean versionMatch = false;
boolean first = true;
StringBuilder b = new StringBuilder();
for (Header h : fields) {
if (WebUtils.OPEN_ROSA_VERSION.equals(h.getValue())) {
versionMatch = true;
break;
}
if (!first) {
b.append("; ");
}
first = false;
b.append(h.getValue());
}
if (!versionMatch) {
Log.w(t, WebUtils.OPEN_ROSA_VERSION_HEADER
+ " unrecognized version(s): " + b.toString());
}
}
return new DocumentFetchResult(doc, isOR);
} catch (Exception e) {
clearHttpConnectionManager();
e.printStackTrace();
String cause;
Throwable c = e;
while (c.getCause() != null) {
c = c.getCause();
}
cause = c.toString();
String error = "Error: " + cause + " while accessing "
+ u.toString();
Log.w(t, error);
return new DocumentFetchResult(error, 0);
}
}
public static void clearHttpConnectionManager() {
// If we get an unexpected exception, the safest thing is to close
// all connections
// so that if there is garbage on the connection we ensure it is
// removed. This
// is especially important if the connection times out.
if ( httpConnectionManager != null ) {
httpConnectionManager.shutdown();
httpConnectionManager = null;
}
}
}
| 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.utilities;
import java.net.MalformedURLException;
import java.net.URL;
public class UrlUtils {
public static boolean isValidUrl(String url) {
try {
new URL(url);
return true;
} catch (MalformedURLException e) {
return false;
}
}
}
| 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.utilities;
import org.kxml2.kdom.Document;
public class DocumentFetchResult {
public final String errorMessage;
public final int responseCode;
public final Document doc;
public final boolean isOpenRosaResponse;
public DocumentFetchResult(String msg, int response) {
responseCode = response;
errorMessage = msg;
doc = null;
isOpenRosaResponse = false;
}
public DocumentFetchResult(Document doc, boolean isOpenRosaResponse) {
responseCode = 0;
errorMessage = null;
this.doc = doc;
this.isOpenRosaResponse = isOpenRosaResponse;
}
} | Java |
/*
* Copyright (C) 2013 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.utilities;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.odk.collect.android.application.Collect;
import android.util.Log;
/**
* Used for logging data to log files that could be retrieved after a field deployment.
* The initial use for this is to assist in diagnosing a report of a cached geopoints
* being reported, causing stale GPS coordinates to be recorded (issue 780).
*
* @author mitchellsundt@gmail.com
*
*/
public class InfoLogger {
private static final String t = "InfoLogger";
private static final String LOG_DIRECTORY = "logging";
private static final String LOG_FILE = "geotrace.log";
public static final void geolog(String msg) {
geologToLogcat(msg);
}
private static final void geologToLogcat(String msg) {
Log.i(t, msg);
}
@SuppressWarnings("unused")
private static final void geologToFile(String msg) {
File dir = new File( Collect.ODK_ROOT + File.separator + LOG_DIRECTORY );
if ( !dir.exists() ) {
dir.mkdirs();
}
File log = new File(dir, LOG_FILE);
FileOutputStream fo = null;
try {
fo = new FileOutputStream(log, true);
msg = msg + "\n";
fo.write( msg.getBytes("UTF-8") );
fo.flush();
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.e(t, "exception: " + e.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.e(t, "exception: " + e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.e(t, "exception: " + e.toString());
}
}
}
| 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.database;
import java.io.File;
import java.util.Calendar;
import java.util.LinkedList;
import org.javarosa.core.model.FormIndex;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.logic.FormController;
import android.app.Activity;
import android.content.ContentValues;
import android.database.SQLException;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
/**
* Log all user interface activity into a SQLite database. Logging is disabled by default.
*
* The logging database will be "/sdcard/odk/log/activityLog.db"
*
* Logging is enabled if the file "/sdcard/odk/log/enabled" exists.
*
* @author mitchellsundt@gmail.com
* @author Carl Hartung (carlhartung@gmail.com)
*
*/
public final class ActivityLogger {
private static class DatabaseHelper extends ODKSQLiteOpenHelper {
DatabaseHelper() {
super(Collect.LOG_PATH, DATABASE_NAME, null, DATABASE_VERSION);
new File(Collect.LOG_PATH).mkdirs();
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
/**
* The minimum delay, in milliseconds, for a scroll action to be considered new.
*/
private static final long MIN_SCROLL_DELAY = 400L;
/**
* The maximum size of the scroll action buffer. After it reaches this size,
* it will be flushed.
*/
private static final int MAX_SCROLL_ACTION_BUFFER_SIZE = 8;
private static final String DATABASE_TABLE = "log";
private static final String ENABLE_LOGGING = "enabled";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "activityLog.db";
// Database columns
private static final String ID = "_id";
private static final String TIMESTAMP = "timestamp";
private static final String DEVICEID = "device_id";
private static final String CLASS = "class";
private static final String CONTEXT = "context";
private static final String ACTION = "action";
private static final String INSTANCE_PATH = "instance_path";
private static final String QUESTION = "question";
private static final String PARAM1 = "param1";
private static final String PARAM2 = "param2";
private static final String DATABASE_CREATE =
"create table " + DATABASE_TABLE + " (" +
ID + " integer primary key autoincrement, " +
TIMESTAMP + " integer not null, " +
DEVICEID + " text not null, " +
CLASS + " text not null, " +
CONTEXT + " text not null, " +
ACTION + " text, " +
INSTANCE_PATH + " text, " +
QUESTION + " text, " +
PARAM1 + " text, " +
PARAM2 + " text);";
private final boolean mLoggingEnabled;
private final String mDeviceId;
private DatabaseHelper mDbHelper = null;
private SQLiteDatabase mDb = null;
private boolean mIsOpen = false;
// We buffer scroll actions to make sure there aren't too many pauses
// during scrolling. This list is flushed every time any other type of
// action is logged.
private LinkedList<ContentValues> mScrollActions = new LinkedList<ContentValues>();
public ActivityLogger(String deviceId) {
this.mDeviceId = deviceId;
mLoggingEnabled = new File(Collect.LOG_PATH, ENABLE_LOGGING).exists();
open();
}
public boolean isOpen() {
return mLoggingEnabled && mIsOpen;
}
public void open() throws SQLException {
if (!mLoggingEnabled || mIsOpen) return;
try {
mDbHelper = new DatabaseHelper();
mDb = mDbHelper.getWritableDatabase();
mIsOpen = true;
} catch (SQLiteException e) {
System.err.println("Error: " + e.getMessage());
mIsOpen = false;
}
}
// cached to improve logging performance...
// only access these through getXPath(FormIndex index);
private FormIndex cachedXPathIndex = null;
private String cachedXPathValue = null;
// DO NOT CALL THIS OUTSIDE OF synchronized(mScrollActions) !!!!
// DO NOT CALL THIS OUTSIDE OF synchronized(mScrollActions) !!!!
// DO NOT CALL THIS OUTSIDE OF synchronized(mScrollActions) !!!!
// DO NOT CALL THIS OUTSIDE OF synchronized(mScrollActions) !!!!
private String getXPath(FormIndex index) {
if ( index == cachedXPathIndex ) return cachedXPathValue;
cachedXPathIndex = index;
cachedXPathValue = Collect.getInstance().getFormController().getXPath(index);
return cachedXPathValue;
}
private void log(String object, String context, String action, String instancePath, FormIndex index, String param1, String param2) {
if (!isOpen()) return;
ContentValues cv = new ContentValues();
cv.put(DEVICEID, mDeviceId);
cv.put(CLASS, object);
cv.put(CONTEXT, context);
cv.put(ACTION, action);
cv.put(INSTANCE_PATH, instancePath);
cv.put(PARAM1, param1);
cv.put(PARAM2, param2);
cv.put(TIMESTAMP, Calendar.getInstance().getTimeInMillis());
insertContentValues(cv, index);
}
public void logScrollAction(Object t, int distance) {
if (!isOpen()) return;
synchronized(mScrollActions) {
long timeStamp = Calendar.getInstance().getTimeInMillis();
// Check to see if we can add this scroll action to the previous action.
if (!mScrollActions.isEmpty()) {
ContentValues lastCv = mScrollActions.get(mScrollActions.size() - 1);
long oldTimeStamp = lastCv.getAsLong(TIMESTAMP);
int oldDistance = Integer.parseInt(lastCv.getAsString(PARAM1));
if (Integer.signum(distance) == Integer.signum(oldDistance) &&
timeStamp - oldTimeStamp < MIN_SCROLL_DELAY) {
lastCv.put(PARAM1, oldDistance + distance);
lastCv.put(TIMESTAMP, timeStamp);
return;
}
}
if (mScrollActions.size() >= MAX_SCROLL_ACTION_BUFFER_SIZE) {
insertContentValues(null, null); // flush scroll list...
}
String idx = "";
String instancePath = "";
FormController formController = Collect.getInstance().getFormController();
if ( formController != null ) {
idx = getXPath(formController.getFormIndex());
instancePath = formController.getInstancePath().getAbsolutePath();
}
// Add a new scroll action to the buffer.
ContentValues cv = new ContentValues();
cv.put(DEVICEID, mDeviceId);
cv.put(CLASS, t.getClass().getName());
cv.put(CONTEXT, "scroll");
cv.put(ACTION, "");
cv.put(PARAM1, distance);
cv.put(QUESTION, idx);
cv.put(INSTANCE_PATH, instancePath);
cv.put(TIMESTAMP, timeStamp);
cv.put(PARAM2, timeStamp);
mScrollActions.add(cv);
}
}
private void insertContentValues(ContentValues cv, FormIndex index) {
synchronized(mScrollActions) {
try {
while ( !mScrollActions.isEmpty() ) {
ContentValues scv = mScrollActions.removeFirst();
mDb.insert(DATABASE_TABLE, null, scv);
}
if ( cv != null ) {
String idx = "";
if ( index != null ) {
idx = getXPath(index);
}
cv.put(QUESTION,idx);
mDb.insert(DATABASE_TABLE, null, cv);
}
} catch (SQLiteConstraintException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
// Convenience methods
public void logOnStart(Activity a) {
log( a.getClass().getName(), "onStart", null, null, null, null, null);
}
public void logOnStop(Activity a) {
log( a.getClass().getName(), "onStop", null, null, null, null, null);
}
public void logAction(Object t, String context, String action) {
log( t.getClass().getName(), context, action, null, null, null, null);
}
public void logActionParam(Object t, String context, String action, String param1) {
log( t.getClass().getName(), context, action, null, null, param1, null);
}
public void logInstanceAction(Object t, String context, String action) {
FormIndex index = null;
String instancePath = null;
FormController formController = Collect.getInstance().getFormController();
if ( formController != null ) {
index = formController.getFormIndex();
instancePath = formController.getInstancePath().getAbsolutePath();
}
log( t.getClass().getName(), context, action, instancePath, index, null, null);
}
public void logInstanceAction(Object t, String context, String action, FormIndex index) {
String instancePath = null;
FormController formController = Collect.getInstance().getFormController();
if ( formController != null ) {
index = formController.getFormIndex();
instancePath = formController.getInstancePath().getAbsolutePath();
}
log( t.getClass().getName(), context, action, instancePath, index, null, null);
}
}
| Java |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.database;
import java.io.File;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.util.Log;
/**
* We've taken this from Android's SQLiteOpenHelper. However, we can't appropriately lock the
* database so there may be issues if a thread opens the database read-only and another thread tries
* to open the database read/write. I don't think this will ever happen in ODK, though. (fingers
* crossed).
*/
/**
* A helper class to manage database creation and version management. You create a subclass
* implementing {@link #onCreate}, {@link #onUpgrade} and optionally {@link #onOpen}, and this class
* takes care of opening the database if it exists, creating it if it does not, and upgrading it as
* necessary. Transactions are used to make sure the database is always in a sensible state.
* <p>
* For an example, see the NotePadProvider class in the NotePad sample application, in the
* <em>samples/</em> directory of the SDK.
* </p>
*/
public abstract class ODKSQLiteOpenHelper {
private static final String t = ODKSQLiteOpenHelper.class.getSimpleName();
private final String mPath;
private final String mName;
private final CursorFactory mFactory;
private final int mNewVersion;
private SQLiteDatabase mDatabase = null;
private boolean mIsInitializing = false;
/**
* Create a helper object to create, open, and/or manage a database. The database is not
* actually created or opened until one of {@link #getWritableDatabase} or
* {@link #getReadableDatabase} is called.
*
* @param path to the file
* @param name of the database file, or null for an in-memory database
* @param factory to use for creating cursor objects, or null for the default
* @param version number of the database (starting at 1); if the database is older,
* {@link #onUpgrade} will be used to upgrade the database
*/
public ODKSQLiteOpenHelper(String path, String name, CursorFactory factory, int version) {
if (version < 1)
throw new IllegalArgumentException("Version must be >= 1, was " + version);
mPath = path;
mName = name;
mFactory = factory;
mNewVersion = version;
}
/**
* Create and/or open a database that will be used for reading and writing. Once opened
* successfully, the database is cached, so you can call this method every time you need to
* write to the database. Make sure to call {@link #close} when you no longer need it.
* <p>
* Errors such as bad permissions or a full disk may cause this operation to fail, but future
* attempts may succeed if the problem is fixed.
* </p>
*
* @throws SQLiteException if the database cannot be opened for writing
* @return a read/write database object valid until {@link #close} is called
*/
public synchronized SQLiteDatabase getWritableDatabase() {
if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly()) {
return mDatabase; // The database is already open for business
}
if (mIsInitializing) {
throw new IllegalStateException("getWritableDatabase called recursively");
}
// If we have a read-only database open, someone could be using it
// (though they shouldn't), which would cause a lock to be held on
// the file, and our attempts to open the database read-write would
// fail waiting for the file lock. To prevent that, we acquire the
// lock on the read-only database, which shuts out other users.
boolean success = false;
SQLiteDatabase db = null;
// if (mDatabase != null) mDatabase.lock();
try {
mIsInitializing = true;
if (mName == null) {
db = SQLiteDatabase.create(null);
} else {
db = SQLiteDatabase.openOrCreateDatabase(mPath + File.separator + mName, mFactory);
// db = mContext.openOrCreateDatabase(mName, 0, mFactory);
}
int version = db.getVersion();
if (version != mNewVersion) {
db.beginTransaction();
try {
if (version == 0) {
onCreate(db);
} else {
onUpgrade(db, version, mNewVersion);
}
db.setVersion(mNewVersion);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
onOpen(db);
success = true;
return db;
} finally {
mIsInitializing = false;
if (success) {
if (mDatabase != null) {
try {
mDatabase.close();
} catch (Exception e) {
}
// mDatabase.unlock();
}
mDatabase = db;
} else {
// if (mDatabase != null) mDatabase.unlock();
if (db != null)
db.close();
}
}
}
/**
* Create and/or open a database. This will be the same object returned by
* {@link #getWritableDatabase} unless some problem, such as a full disk, requires the database
* to be opened read-only. In that case, a read-only database object will be returned. If the
* problem is fixed, a future call to {@link #getWritableDatabase} may succeed, in which case
* the read-only database object will be closed and the read/write object will be returned in
* the future.
*
* @throws SQLiteException if the database cannot be opened
* @return a database object valid until {@link #getWritableDatabase} or {@link #close} is
* called.
*/
public synchronized SQLiteDatabase getReadableDatabase() {
if (mDatabase != null && mDatabase.isOpen()) {
return mDatabase; // The database is already open for business
}
if (mIsInitializing) {
throw new IllegalStateException("getReadableDatabase called recursively");
}
try {
return getWritableDatabase();
} catch (SQLiteException e) {
if (mName == null)
throw e; // Can't open a temp database read-only!
Log.e(t, "Couldn't open " + mName + " for writing (will try read-only):", e);
}
SQLiteDatabase db = null;
try {
mIsInitializing = true;
String path = mPath + File.separator + mName;
// mContext.getDatabasePath(mName).getPath();
db = SQLiteDatabase.openDatabase(path, mFactory, SQLiteDatabase.OPEN_READONLY);
if (db.getVersion() != mNewVersion) {
throw new SQLiteException("Can't upgrade read-only database from version "
+ db.getVersion() + " to " + mNewVersion + ": " + path);
}
onOpen(db);
Log.w(t, "Opened " + mName + " in read-only mode");
mDatabase = db;
return mDatabase;
} finally {
mIsInitializing = false;
if (db != null && db != mDatabase)
db.close();
}
}
/**
* Close any open database object.
*/
public synchronized void close() {
if (mIsInitializing)
throw new IllegalStateException("Closed during initialization");
if (mDatabase != null && mDatabase.isOpen()) {
mDatabase.close();
mDatabase = null;
}
}
/**
* Called when the database is created for the first time. This is where the creation of tables
* and the initial population of the tables should happen.
*
* @param db The database.
*/
public abstract void onCreate(SQLiteDatabase db);
/**
* Called when the database needs to be upgraded. The implementation should use this method to
* drop tables, add tables, or do anything else it needs to upgrade to the new schema version.
* <p>
* The SQLite ALTER TABLE documentation can be found <a
* href="http://sqlite.org/lang_altertable.html">here</a>. If you add new columns you can use
* ALTER TABLE to insert them into a live table. If you rename or remove columns you can use
* ALTER TABLE to rename the old table, then create the new table and then populate the new
* table with the contents of the old table.
*
* @param db The database.
* @param oldVersion The old database version.
* @param newVersion The new database version.
*/
public abstract void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion);
/**
* Called when the database has been opened. Override method should check
* {@link SQLiteDatabase#isReadOnly} before updating the database.
*
* @param db The database.
*/
public void onOpen(SQLiteDatabase db) {
}
}
| 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.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 android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* ListMultiWidget handles multiple selection fields using check boxes. The check boxes are aligned
* horizontally. They are typically meant to be used in a field list, where multiple questions with
* the same multiple choice answers can sit on top of each other and make a grid of buttons that is
* easy to navigate quickly. Optionally, you can turn off the labels. This would be done if a label
* widget was at the top of your field list to provide the labels. If audio or video are specified
* in the select answers they are ignored. This class is almost identical to ListWidget, except it
* uses checkboxes. It also did not require a custom clickListener class.
*
* @author Jeff Beorse (jeff@beorse.net)
*/
public class ListMultiWidget extends QuestionWidget {
private static final String t = "ListMultiWidget";
// Holds the entire question and answers. It is a horizontally aligned linear layout
// needed because it is created in the super() constructor via addQuestionText() call.
LinearLayout questionLayout;
private boolean mCheckboxInit = true;
private Vector<SelectChoice> mItems; // may take a while to compute...
private ArrayList<CheckBox> mCheckboxes;
@SuppressWarnings("unchecked")
public ListMultiWidget(Context context, FormEntryPrompt prompt, boolean displayLabel) {
super(context, prompt);
mItems = prompt.getSelectChoices();
mCheckboxes = new ArrayList<CheckBox>();
mPrompt = prompt;
// Layout holds the horizontal list of buttons
LinearLayout buttonLayout = new LinearLayout(context);
Vector<Selection> ve = new Vector<Selection>();
if (prompt.getAnswerValue() != null) {
ve = (Vector<Selection>) prompt.getAnswerValue().getValue();
}
if (mItems != null) {
for (int i = 0; i < mItems.size(); i++) {
CheckBox c = new CheckBox(getContext());
c.setTag(Integer.valueOf(i));
c.setId(QuestionWidget.newUniqueId());
c.setFocusable(!prompt.isReadOnly());
c.setEnabled(!prompt.isReadOnly());
for (int vi = 0; vi < ve.size(); vi++) {
// match based on value, not key
if (mItems.get(i).getValue().equals(ve.elementAt(vi).getValue())) {
c.setChecked(true);
break;
}
}
mCheckboxes.add(c);
// when clicked, check for readonly before toggling
c.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!mCheckboxInit && mPrompt.isReadOnly()) {
if (buttonView.isChecked()) {
buttonView.setChecked(false);
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onItemClick.deselect",
mItems.get((Integer)buttonView.getTag()).getValue(), mPrompt.getIndex());
} else {
buttonView.setChecked(true);
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onItemClick.select",
mItems.get((Integer)buttonView.getTag()).getValue(), mPrompt.getIndex());
}
}
}
});
String imageURI = 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(c, buttonParams);
answer.setPadding(4, 0, 4, 0);
// /Each button gets equal weight
LinearLayout.LayoutParams answerParams =
new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
answerParams.weight = 1;
buttonLayout.addView(answer, answerParams);
}
}
// Align the buttons so that they appear horizonally and are right justified
// buttonLayout.setGravity(Gravity.RIGHT);
buttonLayout.setOrientation(LinearLayout.HORIZONTAL);
// LinearLayout.LayoutParams params = new
// LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// buttonLayout.setLayoutParams(params);
// The buttons take up the right half of the screen
LinearLayout.LayoutParams buttonParams =
new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
buttonParams.weight = 1;
questionLayout.addView(buttonLayout, buttonParams);
addView(questionLayout);
}
@Override
public void clearAnswer() {
for (int i = 0; i < mCheckboxes.size(); i++) {
CheckBox c = mCheckboxes.get(i);
if (c.isChecked()) {
c.setChecked(false);
}
}
}
@Override
public IAnswerData getAnswer() {
Vector<Selection> vc = new Vector<Selection>();
for (int i = 0; i < mCheckboxes.size(); i++) {
CheckBox c = mCheckboxes.get(i);
if (c.isChecked()) {
vc.add(new Selection(mItems.get(i)));
}
}
if (vc.size() == 0) {
return null;
} else {
return new SelectMultiData(vc);
}
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
// Override QuestionWidget's add question text. Build it the same
// but add it to the questionLayout
protected void addQuestionText(FormEntryPrompt p) {
// Add the text view. Textview always exists, regardless of whether there's text.
TextView questionText = new TextView(getContext());
questionText.setText(p.getLongText());
questionText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize);
questionText.setTypeface(null, Typeface.BOLD);
questionText.setPadding(0, 0, 0, 7);
questionText.setId(QuestionWidget.newUniqueId()); // assign random id
// Wrap to the size of the parent view
questionText.setHorizontallyScrolling(false);
if (p.getLongText() == null) {
questionText.setVisibility(GONE);
}
// Put the question text on the left half of the screen
LinearLayout.LayoutParams labelParams =
new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
labelParams.weight = 1;
questionLayout = new LinearLayout(getContext());
questionLayout.setOrientation(LinearLayout.HORIZONTAL);
questionLayout.addView(questionText, labelParams);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
for (CheckBox c : mCheckboxes) {
c.setOnLongClickListener(l);
}
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
for (CheckBox c : mCheckboxes) {
c.cancelLongPress();
}
}
}
| 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 org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.activities.DrawActivity;
import org.odk.collect.android.activities.FormEntryActivity;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.utilities.MediaUtils;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
* Signature widget.
*
* @author BehrAtherton@gmail.com
*
*/
public class SignatureWidget extends QuestionWidget implements IBinaryWidget {
private final static String t = "SignatureWidget";
private Button mSignButton;
private String mBinaryName;
private String mInstanceFolder;
private ImageView mImageView;
private TextView mErrorTextView;
public SignatureWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mInstanceFolder =
Collect.getInstance().getFormController().getInstancePath().getParent();
setOrientation(LinearLayout.VERTICAL);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
params.setMargins(7, 5, 7, 5);
mErrorTextView = new TextView(context);
mErrorTextView.setId(QuestionWidget.newUniqueId());
mErrorTextView.setText("Selected file is not a valid image");
// setup Blank Image Button
mSignButton = new Button(getContext());
mSignButton.setId(QuestionWidget.newUniqueId());
mSignButton.setText(getContext().getString(R.string.sign_button));
mSignButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mSignButton.setPadding(20, 20, 20, 20);
mSignButton.setEnabled(!prompt.isReadOnly());
mSignButton.setLayoutParams(params);
// launch capture intent on click
mSignButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "signButton", "click",
mPrompt.getIndex());
launchSignatureActivity();
}
});
// finish complex layout
addView(mSignButton);
addView(mErrorTextView);
// and hide the sign button if read-only
if ( prompt.isReadOnly() ) {
mSignButton.setVisibility(View.GONE);
}
mErrorTextView.setVisibility(View.GONE);
// retrieve answer from data model and update ui
mBinaryName = prompt.getAnswerText();
// Only add the imageView if the user has signed
if (mBinaryName != null) {
mImageView = new ImageView(getContext());
mImageView.setId(QuestionWidget.newUniqueId());
Display display =
((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
File f = new File(mInstanceFolder + File.separator + mBinaryName);
if (f.exists()) {
Bitmap bmp = FileUtils.getBitmapScaledToDisplay(f, screenHeight, screenWidth);
if (bmp == null) {
mErrorTextView.setVisibility(View.VISIBLE);
}
mImageView.setImageBitmap(bmp);
} else {
mImageView.setImageBitmap(null);
}
mImageView.setPadding(10, 10, 10, 10);
mImageView.setAdjustViewBounds(true);
mImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "viewImage",
"click", mPrompt.getIndex());
launchSignatureActivity();
}
});
addView(mImageView);
}
}
private void launchSignatureActivity() {
mErrorTextView.setVisibility(View.GONE);
Intent i = new Intent(getContext(), DrawActivity.class);
i.putExtra(DrawActivity.OPTION, DrawActivity.OPTION_SIGNATURE);
// copy...
if ( mBinaryName != null ) {
File f = new File(mInstanceFolder + File.separator + mBinaryName);
i.putExtra(DrawActivity.REF_IMAGE, Uri.fromFile(f));
}
i.putExtra(DrawActivity.EXTRA_OUTPUT,
Uri.fromFile(new File(Collect.TMPFILE_PATH)));
try {
Collect.getInstance().getFormController().setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i, FormEntryActivity.SIGNATURE_CAPTURE);
}
catch (ActivityNotFoundException e) {
Toast.makeText(getContext(),
getContext().getString(R.string.activity_not_found, "signature capture"),
Toast.LENGTH_SHORT).show();
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
}
private void deleteMedia() {
// get the file path and delete the file
String name = mBinaryName;
// clean up variables
mBinaryName = null;
// delete from media provider
int del = MediaUtils.deleteImageFileFromMediaProvider(mInstanceFolder + File.separator + name);
Log.i(t, "Deleted " + del + " rows from media content provider");
}
@Override
public void clearAnswer() {
// remove the file
deleteMedia();
mImageView.setImageBitmap(null);
mErrorTextView.setVisibility(View.GONE);
// reset buttons
mSignButton.setText(getContext().getString(R.string.sign_button));
}
@Override
public IAnswerData getAnswer() {
if (mBinaryName != null) {
return new StringData(mBinaryName.toString());
} else {
return null;
}
}
@Override
public void setBinaryData(Object answer) {
// you are replacing an answer. delete the previous image using the
// content provider.
if (mBinaryName != null) {
deleteMedia();
}
File newImage = (File) answer;
if (newImage.exists()) {
// Add the new image to the Media content provider so that the
// viewing is fast in Android 2.0+
ContentValues values = new ContentValues(6);
values.put(Images.Media.TITLE, newImage.getName());
values.put(Images.Media.DISPLAY_NAME, newImage.getName());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.Media.DATA, newImage.getAbsolutePath());
Uri imageURI = getContext().getContentResolver().insert(
Images.Media.EXTERNAL_CONTENT_URI, values);
Log.i(t, "Inserting image returned uri = " + imageURI.toString());
mBinaryName = newImage.getName();
Log.i(t, "Setting current answer to " + newImage.getName());
} else {
Log.e(t, "NO IMAGE EXISTS at: " + newImage.getAbsolutePath());
}
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
@Override
public boolean isWaitingForBinaryData() {
return mPrompt.getIndex().equals(Collect.getInstance().getFormController().getIndexWaitingForData());
}
@Override
public void cancelWaitingForBinaryData() {
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mSignButton.setOnLongClickListener(l);
if (mImageView != null) {
mImageView.setOnLongClickListener(l);
}
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mSignButton.cancelLongPress();
if (mImageView != null) {
mImageView.cancelLongPress();
}
}
}
| 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.application.Collect;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.TextKeyListener;
import android.text.method.TextKeyListener.Capitalize;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TableLayout;
/**
* The most basic widget that allows for entry of any text.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class StringWidget extends QuestionWidget {
private static final String ROWS = "rows";
boolean mReadOnly = false;
protected EditText mAnswer;
public StringWidget(Context context, FormEntryPrompt prompt) {
this(context, prompt, true);
setupChangeListener();
}
protected StringWidget(Context context, FormEntryPrompt prompt, boolean derived) {
super(context, prompt);
mAnswer = new EditText(context);
mAnswer.setId(QuestionWidget.newUniqueId());
mReadOnly = prompt.isReadOnly();
mAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
/**
* If a 'rows' attribute is on the input tag, set the minimum number of lines
* to display in the field to that value.
*
* I.e.,
* <input ref="foo" rows="5">
* ...
* </input>
*
* will set the height of the EditText box to 5 rows high.
*/
String height = prompt.getQuestion().getAdditionalAttribute(null, ROWS);
if ( height != null && height.length() != 0 ) {
try {
int rows = Integer.valueOf(height);
mAnswer.setMinLines(rows);
mAnswer.setGravity(Gravity.TOP); // to write test starting at the top of the edit area
} catch (Exception e) {
Log.e(this.getClass().getName(), "Unable to process the rows setting for the answer field: " + e.toString());
}
}
params.setMargins(7, 5, 7, 5);
mAnswer.setLayoutParams(params);
// capitalize the first letter of the sentence
mAnswer.setKeyListener(new TextKeyListener(Capitalize.SENTENCES, false));
// needed to make long read only text scroll
mAnswer.setHorizontallyScrolling(false);
mAnswer.setSingleLine(false);
String s = prompt.getAnswerText();
if (s != null) {
mAnswer.setText(s);
}
if (mReadOnly) {
mAnswer.setBackgroundDrawable(null);
mAnswer.setFocusable(false);
mAnswer.setClickable(false);
}
addView(mAnswer);
}
protected void setupChangeListener() {
mAnswer.addTextChangedListener(new TextWatcher() {
private String oldText = "";
@Override
public void afterTextChanged(Editable s) {
if (!s.toString().equals(oldText)) {
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "answerTextChanged", s.toString(), getPrompt().getIndex());
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
oldText = s.toString();
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) { }
});
}
@Override
public void clearAnswer() {
mAnswer.setText(null);
}
@Override
public IAnswerData getAnswer() {
clearFocus();
String s = mAnswer.getText().toString();
if (s == null || s.equals("")) {
return null;
} else {
return new StringData(s);
}
}
@Override
public void setFocus(Context context) {
// Put focus on text input field and display soft keyboard if appropriate.
mAnswer.requestFocus();
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (!mReadOnly) {
inputManager.showSoftInput(mAnswer, 0);
/*
* If you do a multi-question screen after a "add another group" dialog, this won't
* automatically pop up. It's an Android issue.
*
* That is, if I have an edit text in an activity, and pop a dialog, and in that
* dialog's button's OnClick() I call edittext.requestFocus() and
* showSoftInput(edittext, 0), showSoftinput() returns false. However, if the edittext
* is focused before the dialog pops up, everything works fine. great.
*/
} else {
inputManager.hideSoftInputFromWindow(mAnswer.getWindowToken(), 0);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.isAltPressed() == true) {
return false;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mAnswer.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mAnswer.cancelLongPress();
}
}
| 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 org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.activities.DrawActivity;
import org.odk.collect.android.activities.FormEntryActivity;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.utilities.MediaUtils;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
* Free drawing widget.
*
* @author BehrAtherton@gmail.com
*
*/
public class DrawWidget extends QuestionWidget implements IBinaryWidget {
private final static String t = "DrawWidget";
private Button mDrawButton;
private String mBinaryName;
private String mInstanceFolder;
private ImageView mImageView;
private TextView mErrorTextView;
public DrawWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mErrorTextView = new TextView(context);
mErrorTextView.setId(QuestionWidget.newUniqueId());
mErrorTextView.setText("Selected file is not a valid image");
mInstanceFolder = Collect.getInstance().getFormController()
.getInstancePath().getParent();
setOrientation(LinearLayout.VERTICAL);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
params.setMargins(7, 5, 7, 5);
// setup Blank Image Button
mDrawButton = new Button(getContext());
mDrawButton.setId(QuestionWidget.newUniqueId());
mDrawButton.setText(getContext().getString(R.string.draw_image));
mDrawButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mDrawButton.setPadding(20, 20, 20, 20);
mDrawButton.setEnabled(!prompt.isReadOnly());
mDrawButton.setLayoutParams(params);
// launch capture intent on click
mDrawButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "drawButton", "click",
mPrompt.getIndex());
launchDrawActivity();
}
});
// finish complex layout
addView(mDrawButton);
addView(mErrorTextView);
if (mPrompt.isReadOnly()) {
mDrawButton.setVisibility(View.GONE);
}
mErrorTextView.setVisibility(View.GONE);
// retrieve answer from data model and update ui
mBinaryName = prompt.getAnswerText();
// Only add the imageView if the user has signed
if (mBinaryName != null) {
mImageView = new ImageView(getContext());
mImageView.setId(QuestionWidget.newUniqueId());
Display display = ((WindowManager) getContext().getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
File f = new File(mInstanceFolder + File.separator + mBinaryName);
if (f.exists()) {
Bitmap bmp = FileUtils.getBitmapScaledToDisplay(f,
screenHeight, screenWidth);
if (bmp == null) {
mErrorTextView.setVisibility(View.VISIBLE);
}
mImageView.setImageBitmap(bmp);
} else {
mImageView.setImageBitmap(null);
}
mImageView.setPadding(10, 10, 10, 10);
mImageView.setAdjustViewBounds(true);
mImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "viewImage", "click",
mPrompt.getIndex());
launchDrawActivity();
}
});
addView(mImageView);
}
}
private void launchDrawActivity() {
mErrorTextView.setVisibility(View.GONE);
Intent i = new Intent(getContext(), DrawActivity.class);
i.putExtra(DrawActivity.OPTION, DrawActivity.OPTION_DRAW);
// copy...
if (mBinaryName != null) {
File f = new File(mInstanceFolder + File.separator + mBinaryName);
i.putExtra(DrawActivity.REF_IMAGE, Uri.fromFile(f));
}
i.putExtra(DrawActivity.EXTRA_OUTPUT,
Uri.fromFile(new File(Collect.TMPFILE_PATH)));
try {
Collect.getInstance().getFormController()
.setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.DRAW_IMAGE);
} catch (ActivityNotFoundException e) {
Toast.makeText(
getContext(),
getContext().getString(R.string.activity_not_found,
"draw image"), Toast.LENGTH_SHORT).show();
Collect.getInstance().getFormController()
.setIndexWaitingForData(null);
}
}
private void deleteMedia() {
// get the file path and delete the file
String name = mBinaryName;
// clean up variables
mBinaryName = null;
// delete from media provider
int del = MediaUtils.deleteImageFileFromMediaProvider(mInstanceFolder
+ File.separator + name);
Log.i(t, "Deleted " + del + " rows from media content provider");
}
@Override
public void clearAnswer() {
// remove the file
deleteMedia();
mImageView.setImageBitmap(null);
mErrorTextView.setVisibility(View.GONE);
// reset buttons
mDrawButton.setText(getContext().getString(R.string.draw_image));
}
@Override
public IAnswerData getAnswer() {
if (mBinaryName != null) {
return new StringData(mBinaryName.toString());
} else {
return null;
}
}
@Override
public void setBinaryData(Object answer) {
// you are replacing an answer. delete the previous image using the
// content provider.
if (mBinaryName != null) {
deleteMedia();
}
File newImage = (File) answer;
if (newImage.exists()) {
// Add the new image to the Media content provider so that the
// viewing is fast in Android 2.0+
ContentValues values = new ContentValues(6);
values.put(Images.Media.TITLE, newImage.getName());
values.put(Images.Media.DISPLAY_NAME, newImage.getName());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.Media.DATA, newImage.getAbsolutePath());
Uri imageURI = getContext().getContentResolver().insert(
Images.Media.EXTERNAL_CONTENT_URI, values);
Log.i(t, "Inserting image returned uri = " + imageURI.toString());
mBinaryName = newImage.getName();
Log.i(t, "Setting current answer to " + newImage.getName());
} else {
Log.e(t, "NO IMAGE EXISTS at: " + newImage.getAbsolutePath());
}
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
@Override
public boolean isWaitingForBinaryData() {
return mPrompt.getIndex().equals(
Collect.getInstance().getFormController()
.getIndexWaitingForData());
}
@Override
public void cancelWaitingForBinaryData() {
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mDrawButton.setOnLongClickListener(l);
if (mImageView != null) {
mImageView.setOnLongClickListener(l);
}
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mDrawButton.cancelLongPress();
if (mImageView != null) {
mImageView.cancelLongPress();
}
}
}
| 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.Locale;
import org.javarosa.core.model.Constants;
import org.javarosa.form.api.FormEntryPrompt;
import android.content.Context;
import android.util.Log;
/**
* Convenience class that handles creation of widgets.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class WidgetFactory {
/**
* Returns the appropriate QuestionWidget for the given FormEntryPrompt.
*
* @param fep prompt element to be rendered
* @param context Android context
*/
static public QuestionWidget createWidgetFromPrompt(FormEntryPrompt fep, Context context) {
// get appearance hint and clean it up so it is lower case and never null...
String appearance = fep.getAppearanceHint();
if ( appearance == null ) appearance = "";
// for now, all appearance tags are in english...
appearance = appearance.toLowerCase(Locale.ENGLISH);
QuestionWidget questionWidget = null;
switch (fep.getControlType()) {
case Constants.CONTROL_INPUT:
switch (fep.getDataType()) {
case Constants.DATATYPE_DATE_TIME:
questionWidget = new DateTimeWidget(context, fep);
break;
case Constants.DATATYPE_DATE:
questionWidget = new DateWidget(context, fep);
break;
case Constants.DATATYPE_TIME:
questionWidget = new TimeWidget(context, fep);
break;
case Constants.DATATYPE_DECIMAL:
if ( appearance.startsWith("ex:") ) {
questionWidget = new ExDecimalWidget(context, fep);
} else {
questionWidget = new DecimalWidget(context, fep);
}
break;
case Constants.DATATYPE_INTEGER:
if ( appearance.startsWith("ex:") ) {
questionWidget = new ExIntegerWidget(context, fep);
} else {
questionWidget = new IntegerWidget(context, fep);
}
break;
case Constants.DATATYPE_GEOPOINT:
questionWidget = new GeoPointWidget(context, fep);
break;
case Constants.DATATYPE_BARCODE:
questionWidget = new BarcodeWidget(context, fep);
break;
case Constants.DATATYPE_TEXT:
if (appearance.startsWith("printer")) {
questionWidget = new ExPrinterWidget(context, fep);
} else if (appearance.startsWith("ex:")) {
questionWidget = new ExStringWidget(context, fep);
} else if (appearance.equals("numbers")) {
questionWidget = new StringNumberWidget(context, fep);
} else {
questionWidget = new StringWidget(context, fep);
}
break;
default:
questionWidget = new StringWidget(context, fep);
break;
}
break;
case Constants.CONTROL_IMAGE_CHOOSE:
if (appearance.equals("web")) {
questionWidget = new ImageWebViewWidget(context, fep);
} else if(appearance.equals("signature")) {
questionWidget = new SignatureWidget(context, fep);
} else if(appearance.equals("annotate")) {
questionWidget = new AnnotateWidget(context, fep);
} else if(appearance.equals("draw")) {
questionWidget = new DrawWidget(context, fep);
} else if(appearance.startsWith("align:")) {
questionWidget = new AlignedImageWidget(context, fep);
} else {
questionWidget = new ImageWidget(context, fep);
}
break;
case Constants.CONTROL_AUDIO_CAPTURE:
questionWidget = new AudioWidget(context, fep);
break;
case Constants.CONTROL_VIDEO_CAPTURE:
questionWidget = new VideoWidget(context, fep);
break;
case Constants.CONTROL_SELECT_ONE:
if (appearance.contains("compact")) {
int numColumns = -1;
try {
int idx = appearance.indexOf("-");
if ( idx != -1 ) {
numColumns =
Integer.parseInt(appearance.substring(idx + 1));
}
} catch (Exception e) {
// Do nothing, leave numColumns as -1
Log.e("WidgetFactory", "Exception parsing numColumns");
}
if (appearance.contains("quick")) {
questionWidget = new GridWidget(context, fep, numColumns, true);
} else {
questionWidget = new GridWidget(context, fep, numColumns, false);
}
} else if (appearance.equals("minimal")) {
questionWidget = new SpinnerWidget(context, fep);
}
// else if (appearance != null && appearance.contains("autocomplete")) {
// String filterType = null;
// try {
// filterType = appearance.substring(appearance.indexOf('-') + 1);
// } catch (Exception e) {
// // Do nothing, leave filerType null
// Log.e("WidgetFactory", "Exception parsing filterType");
// }
// questionWidget = new AutoCompleteWidget(context, fep, filterType);
//
// }
else if (appearance.equals("quick")) {
questionWidget = new SelectOneAutoAdvanceWidget(context, fep);
} else if (appearance.equals("list")) {
questionWidget = new ListWidget(context, fep, true);
} else if (appearance.equals("list-nolabel")) {
questionWidget = new ListWidget(context, fep, false);
} else if (appearance.equals("label")) {
questionWidget = new LabelWidget(context, fep);
} else {
questionWidget = new SelectOneWidget(context, fep);
}
break;
case Constants.CONTROL_SELECT_MULTI:
if (appearance.contains("compact")) {
int numColumns = -1;
try {
int idx = appearance.indexOf("-");
if ( idx != -1 ) {
numColumns =
Integer.parseInt(appearance.substring(idx + 1));
}
} catch (Exception e) {
// Do nothing, leave numColumns as -1
Log.e("WidgetFactory", "Exception parsing numColumns");
}
questionWidget = new GridMultiWidget(context, fep, numColumns);
} else if (appearance.equals("minimal")) {
questionWidget = new SpinnerMultiWidget(context, fep);
} else if (appearance.equals("list")) {
questionWidget = new ListMultiWidget(context, fep, true);
} else if (appearance.equals("list-nolabel")) {
questionWidget = new ListMultiWidget(context, fep, false);
} else if (appearance.equals("label")) {
questionWidget = new LabelWidget(context, fep);
} else {
questionWidget = new SelectMultiWidget(context, fep);
}
break;
case Constants.CONTROL_TRIGGER:
questionWidget = new TriggerWidget(context, fep);
break;
default:
questionWidget = new StringWidget(context, fep);
break;
}
return questionWidget;
}
}
| Java |
/*
* Copyright (C) 2013 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.widgets;
import java.io.File;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.activities.FormEntryActivity;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.utilities.MediaUtils;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
* Widget that allows user to invoke the aligned-image camera to take pictures and add them to the form.
* Modified to launch the Aligned-image camera app.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
* @author mitchellsundt@gmail.com
*/
public class AlignedImageWidget extends QuestionWidget implements IBinaryWidget {
private static final String ODK_CAMERA_TAKE_PICTURE_INTENT_COMPONENT = "org.opendatakit.camera.TakePicture";
private static final String ODK_CAMERA_INTENT_PACKAGE = "org.opendatakit.camera";
private static final String RETAKE_OPTION_EXTRA = "retakeOption";
private static final String DIMENSIONS_EXTRA = "dimensions";
private static final String FILE_PATH_EXTRA = "filePath";
private final static String t = "AlignedImageWidget";
private Button mCaptureButton;
private Button mChooseButton;
private ImageView mImageView;
private String mBinaryName;
private String mInstanceFolder;
private TextView mErrorTextView;
private int iArray[] = new int[6];
public AlignedImageWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
String appearance = prompt.getAppearanceHint();
String alignments = appearance.substring(appearance.indexOf(":") + 1);
String[] splits = alignments.split(" ");
if ( splits.length != 6 ) {
Log.w(t, "Only have " + splits.length + " alignment values");
}
for ( int i = 0 ; i < 6 ; ++i ) {
if ( splits.length < i ) {
iArray[i] = 0;
} else {
iArray[i] = Integer.valueOf(splits[i]);
}
}
mInstanceFolder =
Collect.getInstance().getFormController().getInstancePath().getParent();
setOrientation(LinearLayout.VERTICAL);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
params.setMargins(7, 5, 7, 5);
mErrorTextView = new TextView(context);
mErrorTextView.setId(QuestionWidget.newUniqueId());
mErrorTextView.setText("Selected file is not a valid image");
// setup capture button
mCaptureButton = new Button(getContext());
mCaptureButton.setId(QuestionWidget.newUniqueId());
mCaptureButton.setText(getContext().getString(R.string.capture_image));
mCaptureButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mCaptureButton.setPadding(20, 20, 20, 20);
mCaptureButton.setEnabled(!prompt.isReadOnly());
mCaptureButton.setLayoutParams(params);
// launch capture intent on click
mCaptureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "captureButton",
"click", mPrompt.getIndex());
mErrorTextView.setVisibility(View.GONE);
Intent i = new Intent();
i.setComponent(new ComponentName(ODK_CAMERA_INTENT_PACKAGE,
ODK_CAMERA_TAKE_PICTURE_INTENT_COMPONENT));
i.putExtra(FILE_PATH_EXTRA, Collect.CACHE_PATH);
i.putExtra(DIMENSIONS_EXTRA, iArray);
i.putExtra(RETAKE_OPTION_EXTRA, false);
// We give the camera an absolute filename/path where to put the
// picture because of bug:
// http://code.google.com/p/android/issues/detail?id=1480
// The bug appears to be fixed in Android 2.0+, but as of feb 2,
// 2010, G1 phones only run 1.6. Without specifying the path the
// images returned by the camera in 1.6 (and earlier) are ~1/4
// the size. boo.
// if this gets modified, the onActivityResult in
// FormEntyActivity will also need to be updated.
try {
Collect.getInstance().getFormController().setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.ALIGNED_IMAGE);
} catch (ActivityNotFoundException e) {
Toast.makeText(getContext(),
getContext().getString(R.string.activity_not_found, "aligned image capture"),
Toast.LENGTH_SHORT).show();
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
}
});
// setup chooser button
mChooseButton = new Button(getContext());
mChooseButton.setId(QuestionWidget.newUniqueId());
mChooseButton.setText(getContext().getString(R.string.choose_image));
mChooseButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mChooseButton.setPadding(20, 20, 20, 20);
mChooseButton.setEnabled(!prompt.isReadOnly());
mChooseButton.setLayoutParams(params);
// launch capture intent on click
mChooseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "chooseButton",
"click", mPrompt.getIndex());
mErrorTextView.setVisibility(View.GONE);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("image/*");
try {
Collect.getInstance().getFormController()
.setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.IMAGE_CHOOSER);
} catch (ActivityNotFoundException e) {
Toast.makeText(getContext(),
getContext().getString(R.string.activity_not_found, "choose image"),
Toast.LENGTH_SHORT).show();
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
}
});
// finish complex layout
addView(mCaptureButton);
addView(mChooseButton);
addView(mErrorTextView);
// and hide the capture and choose button if read-only
if ( prompt.isReadOnly() ) {
mCaptureButton.setVisibility(View.GONE);
mChooseButton.setVisibility(View.GONE);
}
mErrorTextView.setVisibility(View.GONE);
// retrieve answer from data model and update ui
mBinaryName = prompt.getAnswerText();
// Only add the imageView if the user has taken a picture
if (mBinaryName != null) {
mImageView = new ImageView(getContext());
mImageView.setId(QuestionWidget.newUniqueId());
Display display =
((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
File f = new File(mInstanceFolder + File.separator + mBinaryName);
if (f.exists()) {
Bitmap bmp = FileUtils.getBitmapScaledToDisplay(f, screenHeight, screenWidth);
if (bmp == null) {
mErrorTextView.setVisibility(View.VISIBLE);
}
mImageView.setImageBitmap(bmp);
} else {
mImageView.setImageBitmap(null);
}
mImageView.setPadding(10, 10, 10, 10);
mImageView.setAdjustViewBounds(true);
mImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "viewButton",
"click", mPrompt.getIndex());
Intent i = new Intent("android.intent.action.VIEW");
Uri uri = MediaUtils.getImageUriFromMediaProvider(mInstanceFolder + File.separator + mBinaryName);
if ( uri != null ) {
Log.i(t,"setting view path to: " + uri);
i.setDataAndType(uri, "image/*");
try {
getContext().startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(getContext(),
getContext().getString(R.string.activity_not_found, "view image"),
Toast.LENGTH_SHORT).show();
}
}
}
});
addView(mImageView);
}
}
private void deleteMedia() {
// get the file path and delete the file
String name = mBinaryName;
// clean up variables
mBinaryName = null;
// delete from media provider
int del = MediaUtils.deleteImageFileFromMediaProvider(mInstanceFolder + File.separator + name);
Log.i(t, "Deleted " + del + " rows from media content provider");
}
@Override
public void clearAnswer() {
// remove the file
deleteMedia();
mImageView.setImageBitmap(null);
mErrorTextView.setVisibility(View.GONE);
// reset buttons
mCaptureButton.setText(getContext().getString(R.string.capture_image));
}
@Override
public IAnswerData getAnswer() {
if (mBinaryName != null) {
return new StringData(mBinaryName.toString());
} else {
return null;
}
}
@Override
public void setBinaryData(Object newImageObj) {
// you are replacing an answer. delete the previous image using the
// content provider.
if (mBinaryName != null) {
deleteMedia();
}
File newImage = (File) newImageObj;
if (newImage.exists()) {
// Add the new image to the Media content provider so that the
// viewing is fast in Android 2.0+
ContentValues values = new ContentValues(6);
values.put(Images.Media.TITLE, newImage.getName());
values.put(Images.Media.DISPLAY_NAME, newImage.getName());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.Media.DATA, newImage.getAbsolutePath());
Uri imageURI = getContext().getContentResolver().insert(
Images.Media.EXTERNAL_CONTENT_URI, values);
Log.i(t, "Inserting image returned uri = " + imageURI.toString());
mBinaryName = newImage.getName();
Log.i(t, "Setting current answer to " + newImage.getName());
} else {
Log.e(t, "NO IMAGE EXISTS at: " + newImage.getAbsolutePath());
}
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
@Override
public boolean isWaitingForBinaryData() {
return mPrompt.getIndex().equals(Collect.getInstance().getFormController().getIndexWaitingForData());
}
@Override
public void cancelWaitingForBinaryData() {
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mCaptureButton.setOnLongClickListener(l);
mChooseButton.setOnLongClickListener(l);
if (mImageView != null) {
mImageView.setOnLongClickListener(l);
}
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mCaptureButton.cancelLongPress();
mChooseButton.cancelLongPress();
if (mImageView != null) {
mImageView.cancelLongPress();
}
}
}
| 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;
/**
* Interface implemented by widgets that need binary data.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public interface IBinaryWidget {
public void setBinaryData(Object answer);
public void cancelWaitingForBinaryData();
public boolean isWaitingForBinaryData();
}
/*TODO carlhartung: we might want to move this into the QuestionWidget abstract class?
*
*/
| 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.SelectMultiData;
import org.javarosa.core.model.data.helper.Selection;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.TypedValue;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;
import java.util.Vector;
/**
* SpinnerMultiWidget, like SelectMultiWidget handles multiple selection fields using checkboxes,
* but the user clicks a button to see the checkboxes. The goal is to be more compact. If images,
* audio, or video are specified in the select answers they are ignored. WARNING: There is a bug in
* android versions previous to 2.0 that affects this widget. You can find the report here:
* http://code.google.com/p/android/issues/detail?id=922 This bug causes text to be white in alert
* boxes, which makes the select options invisible in this widget. For this reason, this widget
* should not be used on phones with android versions lower than 2.0.
*
* @author Jeff Beorse (jeff@beorse.net)
*/
public class SpinnerMultiWidget extends QuestionWidget {
Vector<SelectChoice> mItems;
// The possible select answers
CharSequence[] answer_items;
// The button to push to display the answers to choose from
Button button;
// Defines which answers are selected
boolean[] selections;
// The alert box that contains the answer selection view
AlertDialog.Builder alert_builder;
// Displays the current selections below the button
TextView selectionText;
@SuppressWarnings("unchecked")
public SpinnerMultiWidget(final Context context, FormEntryPrompt prompt) {
super(context, prompt);
mItems = prompt.getSelectChoices();
mPrompt = prompt;
selections = new boolean[mItems.size()];
answer_items = new CharSequence[mItems.size()];
alert_builder = new AlertDialog.Builder(context);
button = new Button(context);
selectionText = new TextView(getContext());
// Build View
for (int i = 0; i < mItems.size(); i++) {
answer_items[i] = prompt.getSelectChoiceText(mItems.get(i));
}
selectionText.setText(context.getString(R.string.selected));
selectionText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize);
selectionText.setVisibility(View.GONE);
button.setText(context.getString(R.string.select_answer));
button.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize);
button.setPadding(0, 0, 0, 7);
// Give the button a click listener. This defines the alert as well. All the
// click and selection behavior is defined here.
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
alert_builder.setTitle(mPrompt.getQuestionText()).setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
boolean first = true;
selectionText.setText("");
for (int i = 0; i < selections.length; i++) {
if (selections[i]) {
if (first) {
first = false;
selectionText.setText(context.getString(R.string.selected)
+ answer_items[i].toString());
selectionText.setVisibility(View.VISIBLE);
} else {
selectionText.setText(selectionText.getText() + ", "
+ answer_items[i].toString());
}
}
}
}
});
alert_builder.setMultiChoiceItems(answer_items, selections,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
selections[which] = isChecked;
}
});
AlertDialog alert = alert_builder.create();
alert.show();
}
});
// Fill in previous answers
Vector<Selection> ve = new Vector<Selection>();
if (prompt.getAnswerValue() != null) {
ve = (Vector<Selection>) prompt.getAnswerValue().getValue();
}
if (ve != null) {
boolean first = true;
for (int i = 0; i < selections.length; ++i) {
String value = mItems.get(i).getValue();
boolean found = false;
for (Selection s : ve) {
if (value.equals(s.getValue())) {
found = true;
break;
}
}
selections[i] = found;
if (found) {
if (first) {
first = false;
selectionText.setText(context.getString(R.string.selected)
+ answer_items[i].toString());
selectionText.setVisibility(View.VISIBLE);
} else {
selectionText.setText(selectionText.getText() + ", "
+ answer_items[i].toString());
}
}
}
}
addView(button);
addView(selectionText);
}
@Override
public IAnswerData getAnswer() {
clearFocus();
Vector<Selection> vc = new Vector<Selection>();
for (int i = 0; i < mItems.size(); i++) {
if (selections[i]) {
SelectChoice sc = mItems.get(i);
vc.add(new Selection(sc));
}
}
if (vc.size() == 0) {
return null;
} else {
return new SelectMultiData(vc);
}
}
@Override
public void clearAnswer() {
selectionText.setText(R.string.selected);
selectionText.setVisibility(View.GONE);
for (int i = 0; i < selections.length; i++) {
selections[i] = false;
}
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
button.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
button.cancelLongPress();
}
}
| 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 android.content.Context;
import android.text.InputType;
import android.text.method.DigitsKeyListener;
import android.util.TypedValue;
/**
* Widget that restricts values to integers.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class StringNumberWidget extends StringWidget {
public StringNumberWidget(Context context, FormEntryPrompt prompt) {
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);
mAnswer.setKeyListener(new DigitsKeyListener() {
@Override
protected char[] getAcceptedChars() {
char[] accepted = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '-', '+', ' ', ','
};
return accepted;
}
});
if (prompt.isReadOnly()) {
setBackgroundDrawable(null);
setFocusable(false);
setClickable(false);
}
String s = null;
if (prompt.getAnswerValue() != null)
s = (String) prompt.getAnswerValue().getValue();
if (s != null) {
mAnswer.setText(s);
}
setupChangeListener();
}
@Override
public IAnswerData getAnswer() {
clearFocus();
String s = mAnswer.getText().toString();
if (s == null || s.equals("")) {
return null;
} else {
try {
return new StringData(s);
} catch (Exception NumberFormatException) {
return null;
}
}
}
}
| 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.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 android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.method.TextKeyListener;
import android.text.method.TextKeyListener.Capitalize;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.Toast;
/**
* <p>Launch an external app to supply a string value. If the app
* does not launch, enable the text area for regular data entry.</p>
*
* <p>The default button text is "Launch"
*
* <p>You may override the button text and the error text that is
* displayed when the app is missing by using jr:itext() values.
*
* <p>To use this widget, define an appearance on the <input/>
* tag that begins "ex:" and then contains the intent action to lauch.
*
* <p>e.g.,
*
* <pre>
* <input appearance="ex:change.uw.android.TEXTANSWER" ref="/form/passPhrase" >
* </pre>
* <p>or, to customize the button text and error strings with itext:
* <pre>
* ...
* <bind nodeset="/form/passPhrase" type="string" />
* ...
* <itext>
* <translation lang="English">
* <text id="textAnswer">
* <value form="short">Text question</value>
* <value form="long">Enter your pass phrase</value>
* <value form="buttonText">Get Pass Phrase</value>
* <value form="noAppErrorString">Pass Phrase Tool is not installed!
* Please proceed to manually enter pass phrase.</value>
* </text>
* </translation>
* </itext>
* ...
* <input appearance="ex:change.uw.android.TEXTANSWER" ref="/form/passPhrase">
* <label ref="jr:itext('textAnswer')"/>
* </input>
* </pre>
*
* @author mitchellsundt@gmail.com
*
*/
public class ExStringWidget extends QuestionWidget implements IBinaryWidget {
private boolean mHasExApp = true;
private Button mLaunchIntentButton;
private Drawable mTextBackground;
protected EditText mAnswer;
public ExStringWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
params.setMargins(7, 5, 7, 5);
// set text formatting
mAnswer = new EditText(context);
mAnswer.setId(QuestionWidget.newUniqueId());
mAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mAnswer.setLayoutParams(params);
mTextBackground = mAnswer.getBackground();
mAnswer.setBackgroundDrawable(null);
// capitalize nothing
mAnswer.setKeyListener(new TextKeyListener(Capitalize.NONE, false));
// needed to make long read only text scroll
mAnswer.setHorizontallyScrolling(false);
mAnswer.setSingleLine(false);
String s = prompt.getAnswerText();
if (s != null) {
mAnswer.setText(s);
}
if (mPrompt.isReadOnly()) {
mAnswer.setBackgroundDrawable(null);
}
if (mPrompt.isReadOnly() || mHasExApp) {
mAnswer.setFocusable(false);
mAnswer.setClickable(false);
}
String appearance = prompt.getAppearanceHint();
String[] attrs = appearance.split(":");
final String intentName = attrs[1];
final String buttonText;
final String errorString;
String v = mPrompt.getSpecialFormQuestionText("buttonText");
buttonText = (v != null) ? v : context.getString(R.string.launch_app);
v = mPrompt.getSpecialFormQuestionText("noAppErrorString");
errorString = (v != null) ? v : context.getString(R.string.no_app);
// set button formatting
mLaunchIntentButton = new Button(getContext());
mLaunchIntentButton.setId(QuestionWidget.newUniqueId());
mLaunchIntentButton.setText(buttonText);
mLaunchIntentButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mLaunchIntentButton.setPadding(20, 20, 20, 20);
mLaunchIntentButton.setEnabled(!mPrompt.isReadOnly());
mLaunchIntentButton.setLayoutParams(params);
mLaunchIntentButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(intentName);
try {
Collect.getInstance().getFormController().setIndexWaitingForData(mPrompt.getIndex());
fireActivity(i);
} catch (ActivityNotFoundException e) {
mHasExApp = false;
if ( !mPrompt.isReadOnly() ) {
mAnswer.setBackgroundDrawable(mTextBackground);
mAnswer.setFocusable(true);
mAnswer.setFocusableInTouchMode(true);
mAnswer.setClickable(true);
}
mLaunchIntentButton.setEnabled(false);
mLaunchIntentButton.setFocusable(false);
Collect.getInstance().getFormController().setIndexWaitingForData(null);
Toast.makeText(getContext(),
errorString, Toast.LENGTH_SHORT)
.show();
ExStringWidget.this.mAnswer.requestFocus();
}
}
});
// finish complex layout
addView(mLaunchIntentButton);
addView(mAnswer);
}
protected void fireActivity(Intent i) throws ActivityNotFoundException {
i.putExtra("value", mPrompt.getAnswerText());
Collect.getInstance().getActivityLogger().logInstanceAction(this, "launchIntent",
i.getAction(), mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.EX_STRING_CAPTURE);
}
@Override
public void clearAnswer() {
mAnswer.setText(null);
}
@Override
public IAnswerData getAnswer() {
String s = mAnswer.getText().toString();
if (s == null || s.equals("")) {
return null;
} else {
return new StringData(s);
}
}
/**
* Allows answer to be set externally in {@Link FormEntryActivity}.
*/
@Override
public void setBinaryData(Object answer) {
mAnswer.setText((String) answer);
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setFocus(Context context) {
// Put focus on text input field and display soft keyboard if appropriate.
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if ( mHasExApp ) {
// hide keyboard
inputManager.hideSoftInputFromWindow(mAnswer.getWindowToken(), 0);
// focus on launch button
mLaunchIntentButton.requestFocus();
} else {
if (!mPrompt.isReadOnly()) {
mAnswer.requestFocus();
inputManager.showSoftInput(mAnswer, 0);
/*
* If you do a multi-question screen after a "add another group" dialog, this won't
* automatically pop up. It's an Android issue.
*
* That is, if I have an edit text in an activity, and pop a dialog, and in that
* dialog's button's OnClick() I call edittext.requestFocus() and
* showSoftInput(edittext, 0), showSoftinput() returns false. However, if the edittext
* is focused before the dialog pops up, everything works fine. great.
*/
} else {
inputManager.hideSoftInputFromWindow(mAnswer.getWindowToken(), 0);
}
}
}
@Override
public boolean isWaitingForBinaryData() {
return mPrompt.getIndex().equals(Collect.getInstance().getFormController().getIndexWaitingForData());
}
@Override
public void cancelWaitingForBinaryData() {
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.isAltPressed() == true) {
return false;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mAnswer.setOnLongClickListener(l);
mLaunchIntentButton.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mAnswer.cancelLongPress();
mLaunchIntentButton.cancelLongPress();
}
}
| 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.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.Toast;
/**
* <p>Use the ODK Sensors framework to print data to a connected printer.</p>
*
* <p>The default button text is "Print Label"
*
* <p>You may override the button text and the error text that is
* displayed when the app is missing by using jr:itext() values. The
* special itext form values are 'buttonText' and 'noPrinterErrorString',
* respectively.</p>
*
* <p>To use via XLSForm, specify a 'note' type with a 'calculation' that defines
* the data to be printed and with an 'appearance' as described below.
*
* <p>Within the XForms XML, to use this widget, define an appearance on the
* <input/> tag that begins "printer:" and then contains the intent
* action to launch. That intent starts the printer app. The data to print
* is sent via a broadcast intent to intentname.data The printer then pops
* a UI to initiate the actual printing (or change the destination printer).
* </p>
*
* <p>Implementation-wise, this widget is an ExStringWidget that is read-only.</p>
*
* <p>The ODK Sensors Zebra printer uses this appearance (intent):</p>
* <pre>
* "printer:org.opendatakit.sensors.ZebraPrinter"
* </pre>
*
* <p>The data that is printed should be defined in the calculate attribute
* of the bind. The structure of that string is a <br> separated list
* of values consisting of:</p>
* <ul><li>numeric barcode to emit (optional)</li>
* <li>string qrcode to emit (optional)</li>
* <li>text line 1 (optional)</li>
* <li>additional text line (repeat as needed)</li></ul>
*
* <p>E.g., if you wanted to emit a barcode of 123, a qrcode of "mycode" and
* two text lines of "line 1" and "line 2", you would define the calculate
* as:</p>
*
* <pre>
* <bind nodeset="/printerForm/printme" type="string" readonly="true()"
* calculate="concat('123','<br>','mycode','<br>','line 1','<br>','line 2')" />
* </pre>
*
* <p>Depending upon what you supply, the printer may print just a
* barcode, just a qrcode, just text, or some combination of all 3.</p>
*
* <p>Despite using <br> as a separator, the supplied Zebra
* printer does not recognize html.</p>
*
* <pre>
* <input appearance="ex:change.uw.android.TEXTANSWER" ref="/printerForm/printme" >
* </pre>
* <p>or, to customize the button text and error strings with itext:
* <pre>
* ...
* <bind nodeset="/printerForm/printme" type="string" readonly="true()" calculate="concat('<br>',
* /printerForm/some_text ,'<br>Text: ', /printerForm/shortened_text ,'<br>Integer: ',
* /printerForm/a_integer ,'<br>Decimal: ', /printerForm/a_decimal )"/>
* ...
* <itext>
* <translation lang="English">
* <text id="printAnswer">
* <value form="short">Print your label</value>
* <value form="long">Print your label</value>
* <value form="buttonText">Print now</value>
* <value form="noPrinterErrorString">ODK Sensors Zebra Printer is not installed!
* Please install ODK Sensors Framework and ODK Sensors Zebra Printer from Google Play.</value>
* </text>
* </translation>
* </itext>
* ...
* <input appearance="printer:org.opendatakit.sensors.ZebraPrinter" ref="/form/printme">
* <label ref="jr:itext('printAnswer')"/>
* </input>
* </pre>
*
* @author mitchellsundt@gmail.com
*
*/
public class ExPrinterWidget extends QuestionWidget implements IBinaryWidget {
private Button mLaunchIntentButton;
public ExPrinterWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
params.setMargins(7, 5, 7, 5);
String appearance = prompt.getAppearanceHint();
String[] attrs = appearance.split(":");
final String intentName = (attrs.length < 2 || attrs[1].length() == 0) ? "org.opendatakit.sensors.ZebraPrinter" : attrs[1];
final String buttonText;
final String errorString;
String v = mPrompt.getSpecialFormQuestionText("buttonText");
buttonText = (v != null) ? v : context.getString(R.string.launch_printer);
v = mPrompt.getSpecialFormQuestionText("noPrinterErrorString");
errorString = (v != null) ? v : context.getString(R.string.no_printer);
// set button formatting
mLaunchIntentButton = new Button(getContext());
mLaunchIntentButton.setId(QuestionWidget.newUniqueId());
mLaunchIntentButton.setText(buttonText);
mLaunchIntentButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mLaunchIntentButton.setPadding(20, 20, 20, 20);
mLaunchIntentButton.setLayoutParams(params);
mLaunchIntentButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
Collect.getInstance().getFormController().setIndexWaitingForData(mPrompt.getIndex());
firePrintingActivity(intentName);
} catch (ActivityNotFoundException e) {
Collect.getInstance().getFormController().setIndexWaitingForData(null);
Toast.makeText(getContext(),
errorString, Toast.LENGTH_SHORT)
.show();
}
}
});
// finish complex layout
addView(mLaunchIntentButton);
}
protected void firePrintingActivity(String intentName) throws ActivityNotFoundException {
String s = mPrompt.getAnswerText();
Collect.getInstance().getActivityLogger().logInstanceAction(this, "launchPrinter",
intentName, mPrompt.getIndex());
Intent i = new Intent(intentName);
((Activity) getContext()).startActivity(i);
String[] splits;
if ( s != null ) {
splits = s.split("<br>");
} else {
splits = null;
}
Bundle printDataBundle = new Bundle();
String e;
if (splits != null) {
if ( splits.length >= 1 ) {
e = splits[0];
if ( e.length() > 0) {
printDataBundle.putString("BARCODE", e);
}
}
if ( splits.length >= 2 ) {
e = splits[1];
if ( e.length() > 0) {
printDataBundle.putString("QRCODE", e);
}
}
if ( splits.length > 2 ) {
String[] text = new String[splits.length-2];
for ( int j = 2 ; j < splits.length ; ++j ) {
e = splits[j];
text[j-2] = e;
}
printDataBundle.putStringArray("TEXT-STRINGS", text);
}
}
//send the printDataBundle to the activity via broadcast intent
Intent bcastIntent = new Intent(intentName + ".data");
bcastIntent.putExtra("DATA", printDataBundle);
((Activity) getContext()).sendBroadcast(bcastIntent);
}
@Override
public void clearAnswer() {
}
@Override
public IAnswerData getAnswer() {
return mPrompt.getAnswerValue();
}
/**
* Allows answer to be set externally in {@Link FormEntryActivity}.
*/
@Override
public void setBinaryData(Object answer) {
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setFocus(Context context) {
// focus on launch button
mLaunchIntentButton.requestFocus();
}
@Override
public boolean isWaitingForBinaryData() {
return mPrompt.getIndex().equals(Collect.getInstance().getFormController().getIndexWaitingForData());
}
@Override
public void cancelWaitingForBinaryData() {
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.isAltPressed() == true) {
return false;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mLaunchIntentButton.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mLaunchIntentButton.cancelLongPress();
}
}
| 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.Vector;
import org.javarosa.core.model.SelectChoice;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.utilities.FileUtils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* The Label Widget does not return an answer. The purpose of this widget is to be the top entry in
* a field-list with a bunch of list widgets below. This widget provides the labels, so that the
* list widgets can hide their labels and reduce the screen clutter. This class is essentially
* ListWidget with all the answer generating code removed.
*
* @author Jeff Beorse
*/
public class LabelWidget extends QuestionWidget {
private static final String t = "LabelWidget";
LinearLayout buttonLayout;
LinearLayout questionLayout;
Vector<SelectChoice> mItems;
private TextView mQuestionText;
private TextView mMissingImage;
private ImageView mImageView;
private TextView label;
public LabelWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mItems = prompt.getSelectChoices();
mPrompt = prompt;
buttonLayout = new LinearLayout(context);
if (mItems != null) {
for (int i = 0; i < mItems.size(); i++) {
String imageURI = null;
imageURI =
prompt.getSpecialFormSelectChoiceText(mItems.get(i),
FormEntryCaption.TEXT_FORM_IMAGE);
// build image view (if an image is provided)
mImageView = null;
mMissingImage = null;
final int labelId = QuestionWidget.newUniqueId();
// Now set up the image view
String errorMsg = null;
if (imageURI != null) {
try {
String imageFilename =
ReferenceManager._().DeriveReference(imageURI).getLocalURI();
final File imageFile = new File(imageFilename);
if (imageFile.exists()) {
Bitmap b = null;
try {
Display display =
((WindowManager) getContext().getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
b =
FileUtils.getBitmapScaledToDisplay(imageFile, screenHeight,
screenWidth);
} catch (OutOfMemoryError e) {
errorMsg = "ERROR: " + e.getMessage();
}
if (b != null) {
mImageView = new ImageView(getContext());
mImageView.setPadding(2, 2, 2, 2);
mImageView.setAdjustViewBounds(true);
mImageView.setImageBitmap(b);
mImageView.setId(labelId);
} else if (errorMsg == null) {
// An error hasn't been logged and loading the image failed, so it's
// likely
// a bad file.
errorMsg = getContext().getString(R.string.file_invalid, imageFile);
}
} else if (errorMsg == null) {
// An error hasn't been logged. We should have an image, but the file
// doesn't
// exist.
errorMsg = getContext().getString(R.string.file_missing, imageFile);
}
if (errorMsg != null) {
// errorMsg is only set when an error has occured
Log.e(t, errorMsg);
mMissingImage = new TextView(getContext());
mMissingImage.setText(errorMsg);
mMissingImage.setPadding(2, 2, 2, 2);
mMissingImage.setId(labelId);
}
} catch (InvalidReferenceException e) {
Log.e(t, "image invalid reference exception");
e.printStackTrace();
}
} else {
// There's no imageURI listed, so just ignore it.
}
// build text label. Don't assign the text to the built in label to he
// button because it aligns horizontally, and we want the label on top
label = new TextView(getContext());
label.setText(prompt.getSelectChoiceText(mItems.get(i)));
label.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize);
label.setGravity(Gravity.CENTER_HORIZONTAL);
// answer layout holds the label text/image on top and the radio button on bottom
RelativeLayout answer = new RelativeLayout(getContext());
RelativeLayout.LayoutParams headerParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
headerParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
headerParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
if (mImageView != null) {
mImageView.setScaleType(ScaleType.CENTER);
answer.addView(mImageView, headerParams);
} else if (mMissingImage != null) {
answer.addView(mMissingImage, headerParams);
} else {
label.setId(labelId);
answer.addView(label, headerParams);
}
answer.setPadding(4, 0, 4, 0);
// Each button gets equal weight
LinearLayout.LayoutParams answerParams =
new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
answerParams.weight = 1;
buttonLayout.addView(answer, answerParams);
}
}
// Align the buttons so that they appear horizonally and are right justified
// buttonLayout.setGravity(Gravity.RIGHT);
buttonLayout.setOrientation(LinearLayout.HORIZONTAL);
// LinearLayout.LayoutParams params = new
// LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
// buttonLayout.setLayoutParams(params);
// The buttons take up the right half of the screen
LinearLayout.LayoutParams buttonParams =
new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
buttonParams.weight = 1;
questionLayout.addView(buttonLayout, buttonParams);
addView(questionLayout);
}
@Override
public void clearAnswer() {
// Do nothing, no answers to clear
}
@Override
public IAnswerData getAnswer() {
return null;
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
// Override QuestionWidget's add question text. Build it the same
// but add it to the relative layout
protected void addQuestionText(FormEntryPrompt p) {
// Add the text view. Textview always exists, regardless of whether there's text.
mQuestionText = new TextView(getContext());
mQuestionText.setText(p.getLongText());
mQuestionText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize);
mQuestionText.setTypeface(null, Typeface.BOLD);
mQuestionText.setPadding(0, 0, 0, 7);
mQuestionText.setId(QuestionWidget.newUniqueId()); // assign random id
// Wrap to the size of the parent view
mQuestionText.setHorizontallyScrolling(false);
if (p.getLongText() == null) {
mQuestionText.setVisibility(GONE);
}
// Put the question text on the left half of the screen
LinearLayout.LayoutParams labelParams =
new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
labelParams.weight = 1;
questionLayout = new LinearLayout(getContext());
questionLayout.setOrientation(LinearLayout.HORIZONTAL);
questionLayout.addView(mQuestionText, labelParams);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mQuestionText.cancelLongPress();
if (mMissingImage != null) {
mMissingImage.cancelLongPress();
}
if (mImageView != null) {
mImageView.cancelLongPress();
}
if (label != null) {
label.cancelLongPress();
}
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mQuestionText.setOnLongClickListener(l);
if (mMissingImage != null) {
mMissingImage.setOnLongClickListener(l);
}
if (mImageView != null) {
mImageView.setOnLongClickListener(l);
}
if (label != null) {
label.setOnLongClickListener(l);
}
}
}
| 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.SelectChoice;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.SelectMultiData;
import org.javarosa.core.model.data.helper.Selection;
import org.javarosa.form.api.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.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.Vector;
/**
* SelctMultiWidget handles multiple selection fields using checkboxes.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class SelectMultiWidget extends QuestionWidget {
private boolean mCheckboxInit = true;
Vector<SelectChoice> mItems;
private ArrayList<CheckBox> mCheckboxes;
@SuppressWarnings("unchecked")
public SelectMultiWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mPrompt = prompt;
mCheckboxes = new ArrayList<CheckBox>();
mItems = prompt.getSelectChoices();
setOrientation(LinearLayout.VERTICAL);
Vector<Selection> ve = new Vector<Selection>();
if (prompt.getAnswerValue() != null) {
ve = (Vector<Selection>) prompt.getAnswerValue().getValue();
}
if (mItems != null) {
for (int i = 0; i < mItems.size(); i++) {
// no checkbox group so id by answer + offset
CheckBox c = new CheckBox(getContext());
c.setTag(Integer.valueOf(i));
c.setId(QuestionWidget.newUniqueId());
c.setText(prompt.getSelectChoiceText(mItems.get(i)));
c.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
c.setFocusable(!prompt.isReadOnly());
c.setEnabled(!prompt.isReadOnly());
for (int vi = 0; vi < ve.size(); vi++) {
// match based on value, not key
if (mItems.get(i).getValue().equals(ve.elementAt(vi).getValue())) {
c.setChecked(true);
break;
}
}
mCheckboxes.add(c);
// when clicked, check for readonly before toggling
c.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!mCheckboxInit && mPrompt.isReadOnly()) {
if (buttonView.isChecked()) {
buttonView.setChecked(false);
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onItemClick.deselect",
mItems.get((Integer)buttonView.getTag()).getValue(), mPrompt.getIndex());
} else {
buttonView.setChecked(true);
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onItemClick.select",
mItems.get((Integer)buttonView.getTag()).getValue(), mPrompt.getIndex());
}
}
}
});
String 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), c, audioURI, imageURI, videoURI, bigImageURI);
addView(mediaLayout);
// Last, add the dividing line between elements (except for the last element)
ImageView divider = new ImageView(getContext());
divider.setBackgroundResource(android.R.drawable.divider_horizontal_bright);
if (i != mItems.size() - 1) {
addView(divider);
}
}
}
mCheckboxInit = false;
}
@Override
public void clearAnswer() {
for ( CheckBox c : mCheckboxes ) {
if ( c.isChecked() ) {
c.setChecked(false);
}
}
}
@Override
public IAnswerData getAnswer() {
Vector<Selection> vc = new Vector<Selection>();
for ( int i = 0; i < mCheckboxes.size() ; ++i ) {
CheckBox c = mCheckboxes.get(i);
if ( c.isChecked() ) {
vc.add(new Selection(mItems.get(i)));
}
}
if (vc.size() == 0) {
return null;
} else {
return new SelectMultiData(vc);
}
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
for (CheckBox c : mCheckboxes) {
c.setOnLongClickListener(l);
}
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
for (CheckBox c : mCheckboxes) {
c.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.Video;
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 VideoWidget 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 VideoWidget(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_video));
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(VideoWidget.this, "captureButton",
"click", mPrompt.getIndex());
Intent i = new Intent(
android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
Video.Media.EXTERNAL_CONTENT_URI.toString());
try {
Collect.getInstance().getFormController()
.setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.VIDEO_CAPTURE);
} catch (ActivityNotFoundException e) {
Toast.makeText(
getContext(),
getContext().getString(R.string.activity_not_found,
"capture video"), 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_video));
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(VideoWidget.this, "chooseButton",
"click", mPrompt.getIndex());
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("video/*");
// Intent i =
// new Intent(Intent.ACTION_PICK,
// android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
try {
Collect.getInstance().getFormController()
.setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.VIDEO_CHOOSER);
} catch (ActivityNotFoundException e) {
Toast.makeText(
getContext(),
getContext().getString(R.string.activity_not_found,
"choose video "), 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_video));
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(VideoWidget.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), "video/*");
try {
((Activity) getContext()).startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(
getContext(),
getContext().getString(R.string.activity_not_found,
"video video"), 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.deleteVideoFileFromMediaProvider(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[] videoProjection = { Video.Media.DATA };
Cursor c = null;
try {
c = getContext().getContentResolver().query(uri,
videoProjection, null, null, null);
int column_index = c.getColumnIndexOrThrow(Video.Media.DATA);
String videoPath = null;
if (c.getCount() > 0) {
c.moveToFirst();
videoPath = c.getString(column_index);
}
return videoPath;
} finally {
if (c != null) {
c.close();
}
}
}
}
@Override
public void setBinaryData(Object binaryuri) {
// you are replacing an answer. remove the 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 destVideoPath = mInstanceFolder + File.separator
+ System.currentTimeMillis() + extension;
File source = new File(binaryPath);
File newVideo = new File(destVideoPath);
FileUtils.copyFile(source, newVideo);
if (newVideo.exists()) {
// Add the copy to the content provier
ContentValues values = new ContentValues(6);
values.put(Video.Media.TITLE, newVideo.getName());
values.put(Video.Media.DISPLAY_NAME, newVideo.getName());
values.put(Video.Media.DATE_ADDED, System.currentTimeMillis());
values.put(Video.Media.DATA, newVideo.getAbsolutePath());
Uri VideoURI = getContext().getContentResolver().insert(
Video.Media.EXTERNAL_CONTENT_URI, values);
Log.i(t, "Inserting VIDEO returned uri = " + VideoURI.toString());
} else {
Log.e(t, "Inserting Video file FAILED");
}
mBinaryName = newVideo.getName();
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.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.listeners.AdvanceToNextListener;
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 select-one 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.
*
* @author Jeff Beorse (jeff@beorse.net)
*/
public class GridWidget 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;
// The number of columns in the grid, can be user defined (<= 0 if unspecified)
int numColumns;
// Whether to advance immediately after the image is clicked
boolean quickAdvance;
AdvanceToNextListener listener;
int resizeWidth;
public GridWidget(Context context, FormEntryPrompt prompt, int numColumns,
final boolean quickAdvance) {
super(context, prompt);
mItems = prompt.getSelectChoices();
mPrompt = prompt;
listener = (AdvanceToNextListener) context;
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());
}
this.quickAdvance = quickAdvance;
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("GridWidget", "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("GridWidget", errorMsg);
missingImage.setText(errorMsg);
}
if ( numColumns > 0 ) {
maxColumnWidth = resizeWidth;
// force max width to find 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) {
// Imitate the behavior of a radio button. Clear all buttons
// and then check the one clicked by the user. Update the
// background color accordingly
for (int i = 0; i < selected.length; i++) {
// if we have an audio handler, be sure audio is stopped.
if ( selected[i] && (audioHandlers[i] != null)) {
audioHandlers[i].stopPlaying();
}
selected[i] = false;
if (imageViews[i] != null) {
imageViews[i].setBackgroundColor(Color.WHITE);
}
}
selected[position] = true;
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onItemClick.select",
mItems.get(position).getValue(), mPrompt.getIndex());
imageViews[position].setBackgroundColor(Color.rgb(orangeRedVal, orangeGreenVal,
orangeBlueVal));
if (quickAdvance) {
listener.advance();
} else if ( audioHandlers[position] != null ) {
audioHandlers[position].playAudio(getContext());
}
}
});
// Fill in answer
String s = null;
if (prompt.getAnswerValue() != null) {
s = ((Selection) prompt.getAnswerValue().getValue()).getValue();
}
for (int i = 0; i < mItems.size(); ++i) {
String sMatch = mItems.get(i).getValue();
selected[i] = sMatch.equals(s);
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() {
for (int i = 0; i < choices.length; ++i) {
if (selected[i]) {
SelectChoice sc = mItems.elementAt(i);
return new SelectOneData(new Selection(sc));
}
}
return null;
}
@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) 2012 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.widgets;
import java.io.File;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.activities.DrawActivity;
import org.odk.collect.android.activities.FormEntryActivity;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.utilities.MediaUtils;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
* Image widget that supports annotations on the image.
*
* @author BehrAtherton@gmail.com
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*
*/
public class AnnotateWidget extends QuestionWidget implements IBinaryWidget {
private final static String t = "AnnotateWidget";
private Button mCaptureButton;
private Button mChooseButton;
private Button mAnnotateButton;
private ImageView mImageView;
private String mBinaryName;
private String mInstanceFolder;
private TextView mErrorTextView;
public AnnotateWidget(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);
}
}
});
// setup Blank Image Button
mAnnotateButton = new Button(getContext());
mAnnotateButton.setId(QuestionWidget.newUniqueId());
mAnnotateButton.setText(getContext().getString(R.string.markup_image));
mAnnotateButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP,
mAnswerFontsize);
mAnnotateButton.setPadding(20, 20, 20, 20);
mAnnotateButton.setEnabled(false);
mAnnotateButton.setLayoutParams(params);
// launch capture intent on click
mAnnotateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "annotateButton", "click",
mPrompt.getIndex());
launchAnnotateActivity();
}
});
// finish complex layout
addView(mCaptureButton);
addView(mChooseButton);
addView(mAnnotateButton);
addView(mErrorTextView);
// and hide the capture, choose and annotate button if read-only
if (prompt.isReadOnly()) {
mCaptureButton.setVisibility(View.GONE);
mChooseButton.setVisibility(View.GONE);
mAnnotateButton.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) {
if (!prompt.isReadOnly()) {
mAnnotateButton.setEnabled(true);
}
mImageView = new ImageView(getContext());
mImageView.setId(QuestionWidget.newUniqueId());
Display display = ((WindowManager) getContext().getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
File f = new File(mInstanceFolder + File.separator + mBinaryName);
if (f.exists()) {
Bitmap bmp = FileUtils.getBitmapScaledToDisplay(f,
screenHeight, screenWidth);
if (bmp == null) {
mErrorTextView.setVisibility(View.VISIBLE);
}
mImageView.setImageBitmap(bmp);
} else {
mImageView.setImageBitmap(null);
}
mImageView.setPadding(10, 10, 10, 10);
mImageView.setAdjustViewBounds(true);
mImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "viewImage", "click",
mPrompt.getIndex());
launchAnnotateActivity();
}
});
addView(mImageView);
}
}
private void launchAnnotateActivity() {
mErrorTextView.setVisibility(View.GONE);
Intent i = new Intent(getContext(), DrawActivity.class);
i.putExtra(DrawActivity.OPTION, DrawActivity.OPTION_ANNOTATE);
// copy...
if (mBinaryName != null) {
File f = new File(mInstanceFolder + File.separator + mBinaryName);
i.putExtra(DrawActivity.REF_IMAGE, Uri.fromFile(f));
}
i.putExtra(DrawActivity.EXTRA_OUTPUT,
Uri.fromFile(new File(Collect.TMPFILE_PATH)));
try {
Collect.getInstance().getFormController()
.setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.ANNOTATE_IMAGE);
} catch (ActivityNotFoundException e) {
Toast.makeText(
getContext(),
getContext().getString(R.string.activity_not_found,
"annotate image"), Toast.LENGTH_SHORT).show();
Collect.getInstance().getFormController()
.setIndexWaitingForData(null);
}
}
private void deleteMedia() {
// get the file path and delete the file
String name = mBinaryName;
// clean up variables
mBinaryName = null;
// delete from media provider
int del = MediaUtils.deleteImageFileFromMediaProvider(mInstanceFolder
+ File.separator + name);
Log.i(t, "Deleted " + del + " rows from media content provider");
}
@Override
public void clearAnswer() {
// remove the file
deleteMedia();
mImageView.setImageBitmap(null);
mErrorTextView.setVisibility(View.GONE);
if (!mPrompt.isReadOnly()) {
mAnnotateButton.setEnabled(false);
}
// 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);
mAnnotateButton.setOnLongClickListener(l);
if (mImageView != null) {
mImageView.setOnLongClickListener(l);
}
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mCaptureButton.cancelLongPress();
mChooseButton.cancelLongPress();
mAnnotateButton.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.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 android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
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 scan barcodes and add them to the form.
*
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class BarcodeWidget extends QuestionWidget implements IBinaryWidget {
private Button mGetBarcodeButton;
private TextView mStringAnswer;
public BarcodeWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
setOrientation(LinearLayout.VERTICAL);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
params.setMargins(7, 5, 7, 5);
// set button formatting
mGetBarcodeButton = new Button(getContext());
mGetBarcodeButton.setId(QuestionWidget.newUniqueId());
mGetBarcodeButton.setText(getContext().getString(R.string.get_barcode));
mGetBarcodeButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP,
mAnswerFontsize);
mGetBarcodeButton.setPadding(20, 20, 20, 20);
mGetBarcodeButton.setEnabled(!prompt.isReadOnly());
mGetBarcodeButton.setLayoutParams(params);
// launch barcode capture intent on click
mGetBarcodeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "recordBarcode", "click",
mPrompt.getIndex());
Intent i = new Intent("com.google.zxing.client.android.SCAN");
try {
Collect.getInstance().getFormController()
.setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.BARCODE_CAPTURE);
} catch (ActivityNotFoundException e) {
Toast.makeText(
getContext(),
getContext().getString(
R.string.barcode_scanner_error),
Toast.LENGTH_SHORT).show();
Collect.getInstance().getFormController()
.setIndexWaitingForData(null);
}
}
});
// set text formatting
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) {
mGetBarcodeButton.setText(getContext().getString(
R.string.replace_barcode));
mStringAnswer.setText(s);
}
// finish complex layout
addView(mGetBarcodeButton);
addView(mStringAnswer);
}
@Override
public void clearAnswer() {
mStringAnswer.setText(null);
mGetBarcodeButton.setText(getContext().getString(R.string.get_barcode));
}
@Override
public IAnswerData getAnswer() {
String s = mStringAnswer.getText().toString();
if (s == null || s.equals("")) {
return null;
} else {
return new StringData(s);
}
}
/**
* Allows answer to be set externally in {@Link FormEntryActivity}.
*/
@Override
public void setBinaryData(Object answer) {
mStringAnswer.setText((String) answer);
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) {
mStringAnswer.setOnLongClickListener(l);
mGetBarcodeButton.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mGetBarcodeButton.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.text.DecimalFormat;
import org.javarosa.core.model.data.GeoPointData;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.activities.FormEntryActivity;
import org.odk.collect.android.activities.GeoPointActivity;
import org.odk.collect.android.activities.GeoPointMapActivity;
import org.odk.collect.android.application.Collect;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
/**
* GeoPointWidget is the widget that allows the user to get GPS readings.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class GeoPointWidget extends QuestionWidget implements IBinaryWidget {
public static final String LOCATION = "gp";
public static final String ACCURACY_THRESHOLD = "accuracyThreshold";
public static final double DEFAULT_LOCATION_ACCURACY = 5.0;
private Button mGetLocationButton;
private Button mViewButton;
private TextView mStringAnswer;
private TextView mAnswerDisplay;
private boolean mUseMaps;
private String mAppearance;
private double mAccuracyThreshold;
public GeoPointWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mUseMaps = false;
mAppearance = prompt.getAppearanceHint();
String acc = prompt.getQuestion().getAdditionalAttribute(null, ACCURACY_THRESHOLD);
if ( acc != null && acc.length() != 0 ) {
mAccuracyThreshold = Double.parseDouble(acc);
} else {
mAccuracyThreshold = DEFAULT_LOCATION_ACCURACY;
}
setOrientation(LinearLayout.VERTICAL);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
params.setMargins(7, 5, 7, 5);
mGetLocationButton = new Button(getContext());
mGetLocationButton.setId(QuestionWidget.newUniqueId());
mGetLocationButton.setPadding(20, 20, 20, 20);
mGetLocationButton.setText(getContext()
.getString(R.string.get_location));
mGetLocationButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP,
mAnswerFontsize);
mGetLocationButton.setEnabled(!prompt.isReadOnly());
mGetLocationButton.setLayoutParams(params);
if ( prompt.isReadOnly()) {
mGetLocationButton.setVisibility(View.GONE);
}
// setup play button
mViewButton = new Button(getContext());
mViewButton.setId(QuestionWidget.newUniqueId());
mViewButton.setText(getContext().getString(R.string.show_location));
mViewButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mViewButton.setPadding(20, 20, 20, 20);
mViewButton.setLayoutParams(params);
// on play, launch the appropriate viewer
mViewButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "showLocation", "click",
mPrompt.getIndex());
String s = mStringAnswer.getText().toString();
String[] sa = s.split(" ");
double gp[] = new double[4];
gp[0] = Double.valueOf(sa[0]).doubleValue();
gp[1] = Double.valueOf(sa[1]).doubleValue();
gp[2] = Double.valueOf(sa[2]).doubleValue();
gp[3] = Double.valueOf(sa[3]).doubleValue();
Intent i = new Intent(getContext(), GeoPointMapActivity.class);
i.putExtra(LOCATION, gp);
i.putExtra(ACCURACY_THRESHOLD, mAccuracyThreshold);
((Activity) getContext()).startActivity(i);
}
});
mStringAnswer = new TextView(getContext());
mStringAnswer.setId(QuestionWidget.newUniqueId());
mAnswerDisplay = new TextView(getContext());
mAnswerDisplay.setId(QuestionWidget.newUniqueId());
mAnswerDisplay
.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mAnswerDisplay.setGravity(Gravity.CENTER);
String s = prompt.getAnswerText();
if (s != null && !s.equals("")) {
mGetLocationButton.setText(getContext().getString(
R.string.replace_location));
setBinaryData(s);
mViewButton.setEnabled(true);
} else {
mViewButton.setEnabled(false);
}
// use maps or not
if (mAppearance != null && mAppearance.equalsIgnoreCase("maps")) {
try {
// do google maps exist on the device
Class.forName("com.google.android.maps.MapActivity");
mUseMaps = true;
} catch (ClassNotFoundException e) {
mUseMaps = false;
}
}
// when you press the button
mGetLocationButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "recordLocation", "click",
mPrompt.getIndex());
Intent i = null;
if (mUseMaps) {
i = new Intent(getContext(), GeoPointMapActivity.class);
} else {
i = new Intent(getContext(), GeoPointActivity.class);
}
i.putExtra(ACCURACY_THRESHOLD, mAccuracyThreshold);
Collect.getInstance().getFormController()
.setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.LOCATION_CAPTURE);
}
});
// finish complex layout
// retrieve answer from data model and update ui
addView(mGetLocationButton);
if (mUseMaps) {
addView(mViewButton);
}
addView(mAnswerDisplay);
}
@Override
public void clearAnswer() {
mStringAnswer.setText(null);
mAnswerDisplay.setText(null);
mGetLocationButton.setText(getContext()
.getString(R.string.get_location));
}
@Override
public IAnswerData getAnswer() {
String s = mStringAnswer.getText().toString();
if (s == null || s.equals("")) {
return null;
} else {
try {
// segment lat and lon
String[] sa = s.split(" ");
double gp[] = new double[4];
gp[0] = Double.valueOf(sa[0]).doubleValue();
gp[1] = Double.valueOf(sa[1]).doubleValue();
gp[2] = Double.valueOf(sa[2]).doubleValue();
gp[3] = Double.valueOf(sa[3]).doubleValue();
return new GeoPointData(gp);
} catch (Exception NumberFormatException) {
return null;
}
}
}
private String truncateDouble(String s) {
DecimalFormat df = new DecimalFormat("#.##");
return df.format(Double.valueOf(s));
}
private String formatGps(double coordinates, String type) {
String location = Double.toString(coordinates);
String degreeSign = "\u00B0";
String degree = location.substring(0, location.indexOf("."))
+ degreeSign;
location = "0." + location.substring(location.indexOf(".") + 1);
double temp = Double.valueOf(location) * 60;
location = Double.toString(temp);
String mins = location.substring(0, location.indexOf(".")) + "'";
location = "0." + location.substring(location.indexOf(".") + 1);
temp = Double.valueOf(location) * 60;
location = Double.toString(temp);
String secs = location.substring(0, location.indexOf(".")) + '"';
if (type.equalsIgnoreCase("lon")) {
if (degree.startsWith("-")) {
degree = "W " + degree.replace("-", "") + mins + secs;
} else
degree = "E " + degree.replace("-", "") + mins + secs;
} else {
if (degree.startsWith("-")) {
degree = "S " + degree.replace("-", "") + mins + secs;
} else
degree = "N " + degree.replace("-", "") + mins + secs;
}
return degree;
}
@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 setBinaryData(Object answer) {
String s = (String) answer;
mStringAnswer.setText(s);
String[] sa = s.split(" ");
mAnswerDisplay.setText(getContext().getString(R.string.latitude) + ": "
+ formatGps(Double.parseDouble(sa[0]), "lat") + "\n"
+ getContext().getString(R.string.longitude) + ": "
+ formatGps(Double.parseDouble(sa[1]), "lon") + "\n"
+ getContext().getString(R.string.altitude) + ": "
+ truncateDouble(sa[2]) + "m\n"
+ getContext().getString(R.string.accuracy) + ": "
+ truncateDouble(sa[3]) + "m");
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@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) {
mViewButton.setOnLongClickListener(l);
mGetLocationButton.setOnLongClickListener(l);
mStringAnswer.setOnLongClickListener(l);
mAnswerDisplay.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mViewButton.cancelLongPress();
mGetLocationButton.cancelLongPress();
mStringAnswer.cancelLongPress();
mAnswerDisplay.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.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 gov.nasa.anml;
import java.io.File;
import java.io.IOException;
import org.antlr.runtime.*;
import org.antlr.runtime.tree.*;
import gov.nasa.anml.lifted.Domain;
import gov.nasa.anml.parsing.*;
import gov.nasa.anml.parsing.ANMLParser.model_return;
import gov.nasa.anml.utility.SimpleString;
public class Main {
public static SimpleString dName;
public static ANMLCharStream input;
public static boolean readArgs(String args[]) {
if (args.length == 0) {
try {
input = new ANMLInputStream(System.in);
dName = Domain.defaultName;
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
try {
File f = new File(args[0]);
input = new ANMLFileStream(args[0]);
if (args.length == 1) {
String name = f.getName();
int index = name.indexOf('.');
if (index > 0)
name = name.substring(0,index);
dName = new SimpleString(name);
} else {
dName = new SimpleString(args[1]);
}
return true;
} catch (IOException e) {
System.out.println("Provide an anml file as first argument, optionally followed by the desired domain name. Or use stdin and deal with the name TheDomain.");
return false;
}
}
public static void main(String args[]) {
if (!readArgs(args)) return;
// create top level for anml and pddl
// (the anml top level is needed for the parse)
Domain d = new Domain(dName);
PDDL pddl = new PDDL();
// setup character->token, token->tree
ANMLLexer lex = new ANMLLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lex);
ANMLParser parser = new ANMLParser(tokens);
ANMLTreeAdaptor adaptor = new ANMLTreeAdaptor(parser.tokenNames);
parser.setTreeAdaptor(adaptor);
// do the initial parse
ANMLParser.model_return r;
try {
r = parser.model(d);
Tree t = (Tree) r.getTree();
// show the AST produced, for debugging
System.out.println(t.toStringTree());
System.out.println("\n\n\n\n\n");
// setup tree->anml-model
CommonTreeNodeStream nodes = new CommonTreeNodeStream(adaptor,t);
nodes.setTokenStream(tokens);
ANMLTree walker = new ANMLTree(nodes);
// process the tree
walker.model(d);
// do anml-model->pddl-model
d.translate(pddl);
// setup printing the pddl model, anticipating large models
StringBuilder buf = new StringBuilder(100000);
// do pddl-model->character
pddl.append(buf);
// ...and show the result
System.out.println(buf.toString());
} catch (RecognitionException e) {
e.printStackTrace();
}
}
}
| Java |
package gov.nasa.anml.utility;
import java.util.Collection;
import java.util.Set;
import gov.nasa.anml.utility.iHashMap.Entry;
public interface pMap<V> {
public static interface Entry<V> {
public abstract V getValue();
public abstract V setValue(V newValue);
}
/**
* @return the number of key-value mappings in this map
*/
public abstract int size();
/**
* @return <tt>true</tt> if this map contains no key-value mappings
*/
public abstract boolean isEmpty();
/**
* Removes all of the mappings from this map.
* The map will be empty after this call returns.
*/
public abstract void clear();
public abstract boolean containsValue(V value);
/**
* Returns a deep-ish copy of this <tt>iHashMap</tt> instance;
* the values are not cloned, but the references are.
*
* Changing a key-value mapping in a clone does not alter the original --
* but directly altering a value is reflected in all references to that
* value, e.g., in all clones.
*
* The keys are primitives and therefore copied.
*
* @return a shallow copy of this map
*/
public abstract pMap<V> clone();
/**
* Returns a {@link Collection} view of the values contained in this map.
* The collection is backed by the map, so changes to the map are
* reflected in the collection, and vice-versa. If the map is
* modified while an iteration over the collection is in progress
* (except through the iterator's own <tt>remove</tt> operation),
* the results of the iteration are undefined. The collection
* supports element removal, which removes the corresponding
* mapping from the map, via the <tt>Iterator.remove</tt>,
* <tt>Collection.remove</tt>, <tt>removeAll</tt>,
* <tt>retainAll</tt> and <tt>clear</tt> operations. It does not
* support the <tt>add</tt> or <tt>addAll</tt> operations.
*/
public abstract Collection<V> values();
} | Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.