I've been trying to get some AR (Augmented Reality) SDK's working in a Fragment.
However, I can't seem to get it working.
I've found some code of someone who has got Metaio (AR Framework) working in a fragment.
So I've applied that code to my own project, it is working but the code is not programmed to scan a picture. I want to scan a picture mark with it.
I copied some code to scan a picture mark from a Sample Project of Metaio, but it doesn't work.
Right now it is failing at (Debug logs after that don't get logged):
trackingConfigFile = AssetsManager.getAssetPath(getActivity().getApplicationContext(), "AEDApp/Assets/TrackingData_PictureMarker.xml");
This is my full code:
package com.example.bt6_aedapp;
import android.app.Application;
import android.content.res.Configuration;
import android.hardware.Camera.CameraInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.metaio.cloud.plugin.MetaioCloudPlugin;
import com.metaio.sdk.MetaioDebug;
import com.metaio.sdk.MetaioSurfaceView;
import com.metaio.sdk.SensorsComponentAndroid;
import com.metaio.sdk.jni.ERENDER_SYSTEM;
import com.metaio.sdk.jni.ESCREEN_ROTATION;
import com.metaio.sdk.jni.IGeometry;
import com.metaio.sdk.jni.IMetaioSDKAndroid;
import com.metaio.sdk.jni.IMetaioSDKCallback;
import com.metaio.sdk.jni.MetaioSDK;
import com.metaio.sdk.jni.TrackingValuesVector;
import com.metaio.sdk.jni.Vector3d;
import com.metaio.tools.Screen;
import com.metaio.tools.SystemInfo;
import com.metaio.tools.io.AssetsManager;
public class fragmentA extends Fragment implements MetaioSurfaceView.Callback {
private Application mAppContext;
private ViewGroup mRootLayout;
String trackingConfigFile;
private MetaioSDKCallbackHandler mCallback;
private IGeometry mModel;
private IMetaioSDKAndroid mMetaioSDK;
private MetaioSurfaceView mSurfaceView;
private static boolean mNativeLibsLoaded = false;
private boolean mRendererInitialized;
private SensorsComponentAndroid mSensors;
static {
mNativeLibsLoaded = IMetaioSDKAndroid.loadNativeLibs();
}
#Override
public void onCreate(Bundle savedInstanceState) {
MetaioCloudPlugin.startJunaio(null, getActivity().getApplicationContext());
super.onCreate(savedInstanceState);
Log.d("LifeCycle", "onCreate");
mAppContext = getActivity().getApplication();
mMetaioSDK = null;
mSurfaceView = null;
mRendererInitialized = false;
try {
mCallback = new MetaioSDKCallbackHandler();
if (!mNativeLibsLoaded){
throw new Exception("Unsupported platform, failed to load the native libs");
}
// Create sensors component
mSensors = new SensorsComponentAndroid(mAppContext);
// Create Unifeye Mobile by passing Activity instance and
// application signature
mMetaioSDK = MetaioSDK.CreateMetaioSDKAndroid(getActivity(), getResources().getString(R.string.metaioSDKSignature));
mMetaioSDK.registerSensorsComponent(mSensors);
} catch (Throwable e) {
MetaioDebug.log(Log.ERROR, "ArCameraFragment.onCreate: failed to create or intialize metaio SDK: " + e.getMessage());
return;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d("LifeCycle", "onCreateView");
View view = inflater.inflate(R.layout.fragment_a, container, false);
mRootLayout = (ViewGroup)getActivity().findViewById(R.id.pager);
return view;
}
#Override
public void onStart() {
super.onStart();
Log.d("LifeCycle", "onStart");
if(mMetaioSDK == null){
return;
}
MetaioDebug.log("ArCameraFragment.onStart()");
try {
mSurfaceView = null;
// Start camera
startCamera();
// Add Unifeye GL Surface view
mSurfaceView = new MetaioSurfaceView(mAppContext);
mSurfaceView.registerCallback(this);
mSurfaceView.setKeepScreenOn(true);
MetaioDebug.log("ArCameraFragment.onStart: addContentView(mMetaioSurfaceView)");
mRootLayout.addView(mSurfaceView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
mSurfaceView.setZOrderMediaOverlay(true);
} catch (Exception e) {
MetaioDebug.log(Log.ERROR, "Error creating views: " + e.getMessage());
MetaioDebug.printStackTrace(Log.ERROR, e);
}
}
#Override
public void onResume() {
super.onResume();
Log.d("LifeCycle", "onResume");
// make sure to resume the OpenGL surface
if (mSurfaceView != null) {
mSurfaceView.onResume();
}
if(mMetaioSDK != null){
mMetaioSDK.resume();
}
}
#Override
public void onPause() {
super.onPause();
Log.d("LifeCycle", "onPause");
// pause the OpenGL surface
if (mSurfaceView != null) {
mSurfaceView.onPause();
}
if (mMetaioSDK != null) {
// Disable the camera
mMetaioSDK.pause();
}
}
#Override
public void onStop() {
super.onStop();
Log.d("LifeCycle", "onStop");
if (mMetaioSDK != null) {
// Disable the camera
mMetaioSDK.stopCamera();
}
if (mSurfaceView != null) {
mRootLayout.removeView(mSurfaceView);
}
System.runFinalization();
System.gc();
}
#Override
public void onDestroy() {
super.onDestroy();
mCallback.delete();
mCallback = null;
/*Log.d("LifeCycle", "onDestroy");
try {
mRendererInitialized = false;
} catch (Exception e) {
MetaioDebug.printStackTrace(Log.ERROR, e);
}
MetaioDebug.log("ArCameraFragment.onDestroy");
if (mMetaioSDK != null) {
mMetaioSDK.delete();
mMetaioSDK = null;
}
MetaioDebug.log("ArCameraFragment.onDestroy releasing sensors");
if (mSensors != null) {
mSensors.registerCallback(null);
mSensors.release();
mSensors.delete();
mSensors = null;
}
// Memory.unbindViews(activity.findViewById(android.R.id.content));
System.runFinalization();
System.gc();*/
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
final ESCREEN_ROTATION rotation = Screen.getRotation(getActivity());
mMetaioSDK.setScreenRotation(rotation);
MetaioDebug.log("onConfigurationChanged: " + rotation);
}
#Override
public void onDrawFrame() {
if(mMetaioSDK != null) {
TrackingValuesVector poses = mMetaioSDK.getTrackingValues();
if(poses.size() != 0) {
mModel.setCoordinateSystemID(poses.get(0).getCoordinateSystemID());
}
}
// Log.d("LifeCycle", "onDrawFrame");
/* if (mRendererInitialized) {
mMetaioSDK.render();
} */
}
#Override
public void onSurfaceCreated() {
Log.d("LifeCycle", "onSurfaceCreated");
try {
if (!mRendererInitialized) {
mMetaioSDK.initializeRenderer(mSurfaceView.getWidth(), mSurfaceView.getHeight(), Screen.getRotation(getActivity()),
ERENDER_SYSTEM.ERENDER_SYSTEM_OPENGL_ES_2_0);
mRendererInitialized = true;
} else {
MetaioDebug.log("ArCameraFragment.onSurfaceCreated: Reloading textures...");
mMetaioSDK.reloadTextures();
}
MetaioDebug.log("ArCameraFragment.onSurfaceCreated: Registering audio renderer...");
// mMetaioSDK.registerAudioCallback(mSurfaceView.getAudioRenderer());
mMetaioSDK.registerCallback(mCallback);
MetaioDebug.log("ARViewActivity.onSurfaceCreated");
} catch (Exception e) {
MetaioDebug.log(Log.ERROR, "ArCameraFragment.onSurfaceCreated: " + e.getMessage());
}
mSurfaceView.queueEvent(new Runnable() {
#Override
public void run() {
loadContents();
}
});
}
private void loadContents() {
try {
trackingConfigFile = AssetsManager.getAssetPath(getActivity().getApplicationContext(), "AEDApp/Assets/TrackingData_PictureMarker.xml");
boolean result = mMetaioSDK.setTrackingConfiguration(trackingConfigFile);
Log.d("result", Boolean.toString(result));
MetaioDebug.log("Tracking data loaded: " + result);
String aedLogo = AssetsManager.getAssetPath(getActivity().getApplicationContext(), "AEDApp/Assets/metaioman.md2");
Log.d("aedLogo", "aaa: " + aedLogo);
if(aedLogo != null) {
mModel = mMetaioSDK.createGeometry(aedLogo);
if(mModel != null) {
mModel.setScale(new Vector3d(4.0f, 4.0f, 4.0f));
}
else {
MetaioDebug.log(Log.ERROR, "Error loading geometry: " + aedLogo);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onSurfaceChanged(int width, int height) {
Log.d("LifeCycle", "onSurfaceChanged");
mMetaioSDK.resizeRenderer(width, height);
}
#Override
public void onSurfaceDestroyed() {
Log.d("LifeCycle", "onSurfaceDestroyed");
MetaioDebug.log("ArCameraFragment.onSurfaceDestroyed(){");
mSurfaceView = null;
// mMetaioSDK.registerAudioCallback(null);
}
protected void startCamera() {
final int cameraIndex = SystemInfo.getCameraIndex(CameraInfo.CAMERA_FACING_BACK);
if (mMetaioSDK != null) {
mMetaioSDK.startCamera(cameraIndex, 640, 480);
}
}
final class MetaioSDKCallbackHandler extends IMetaioSDKCallback {
#Override
public void onTrackingEvent(final TrackingValuesVector trackingValues) {
super.onTrackingEvent(trackingValues);
if(!trackingValues.isEmpty() && trackingValues.get(0).isTrackingState()){
Log.d("Track", "NOT EMPTY");
}
}
}
}
I really hope someone can help me with this as I can not figure it out.. :(
EDIT
The Error (e.printStackTrace()) is throwing is:
03-24 20:25:19.068: W/System.err(28062): java.lang.NullPointerException: null string
03-24 20:25:19.068: W/System.err(28062): at com.metaio.sdk.jni.MetaioSDKJNI.IMetaioSDK_setTrackingConfiguration__SWIG_1(Native Method)
03-24 20:25:19.068: W/System.err(28062): at com.metaio.sdk.jni.IMetaioSDK.setTrackingConfiguration(IMetaioSDK.java:106)
03-24 20:25:19.068: W/System.err(28062): at com.example.bt6_aedapp.fragmentA.loadContents(fragmentA.java:278)
03-24 20:25:19.068: W/System.err(28062): at com.example.bt6_aedapp.fragmentA.access$0(fragmentA.java:274)
03-24 20:25:19.068: W/System.err(28062): at com.example.bt6_aedapp.fragmentA$1.run(fragmentA.java:268)
03-24 20:25:19.068: W/System.err(28062): at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1463)
03-24 20:25:19.068: W/System.err(28062): at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1240)
What I want to do with it:
Being able to 'scan' a picture (https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQFqKIurD3QMU0zVeiwEhtm1twLmTCDlnFulfCwDkxTA1_XQjIQ) and detect the image in the app. The image is referenced in the app in the Assets folder of the project, and I've made a xml file where the marker for it is defined as is stated on the Metaio website. After detecting I'm going to do some database stuff, but for now I need to get the detecting part working.
EDIT
If anyone knows how i can make another AR Framework in Fragments I would love tot know.
I don't know pretty much anything about fragments but as for the null string I think that happens because you haven't extracted the assets.
In this video http://youtu.be/KVtCi-WwmFU?t=30m29s it's explained.
Basically what you have to do is add this code
private class AssetsExtracter extends AsyncTask<Integer, Integer, Boolean>{
#Override
protected Boolean doInBackground(Integer... params){
try
{
AssetsManager.extractAllAssets(getApplicationContext(), BuildConfig.DEBUG);
}catch (IOException e){
MetaioDebug.printStackTrace(Log.ERROR, e);
return false;
}
return true;
}
}
to your activity (or in this case, I guess, your fragment).
Then you have to add a field of this class like
private AssetsExtracter mTask;
and inside the onCreate() method you put
mTask = new AssetsExtracter();
mTask.execute(0);
After that your assets should be avaliable from AssetsManager.getAssetPath(..) and it shouldn't return a null string anymore.
Related
on line 370 i need a way to look for a string of 'f's' in the advertisement data from a TI CC2650. I found this template online but I'm looking for specific advertising data. Please let me know what string array I need to look at to find this.
package net.jmodwyer.beacon.beaconPoC;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Bundle;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.text.util.Linkify;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import net.jmodwyer.ibeacon.ibeaconPoC.R;
import org.altbeacon.beacon.Beacon;
import org.altbeacon.beacon.BeaconConsumer;
import org.altbeacon.beacon.BeaconManager;
import org.altbeacon.beacon.RangeNotifier;
import org.altbeacon.beacon.Region;
import org.altbeacon.beacon.utils.UrlBeaconUrlCompressor;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
/**
* Adapted from original code written by D Young of Radius Networks.
* #author dyoung, jodwyer
*
*/
public class ScanActivity extends Activity implements BeaconConsumer,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
// Constant Declaration
private static final String PREFERENCE_SCANINTERVAL = "scanInterval";
private static final String PREFERENCE_TIMESTAMP = "timestamp";
private static final String PREFERENCE_POWER = "power";
private static final String PREFERENCE_PROXIMITY = "proximity";
private static final String PREFERENCE_RSSI = "rssi";
private static final String PREFERENCE_MAJORMINOR = "majorMinor";
private static final String PREFERENCE_UUID = "uuid";
private static final String PREFERENCE_INDEX = "index";
private static final String PREFERENCE_LOCATION = "location";
private static final String PREFERENCE_REALTIME = "realTimeLog";
private static final String MODE_SCANNING = "Stop Scanning";
private static final String MODE_STOPPED = "Start Scanning";
protected static final String TAG = "ScanActivity";
/*
* Define a request code to send to Google Play services
* This code is returned in Activity.onActivityResult
*/
private final static int
CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private FileHelper fileHelper;
private BeaconManager beaconManager;
private Region region;
private int eventNum = 1;
// This StringBuffer will hold the scan data for any given scan.
private StringBuffer logString;
// Preferences - will actually have a boolean value when loaded.
private Boolean index;
private Boolean location;
private Boolean uuid;
private Boolean majorMinor;
private Boolean rssi;
private Boolean proximity;
private Boolean power;
private Boolean timestamp;
private String scanInterval;
// Added following a feature request from D.Schmid.
private Boolean realTimeLog;
// LocationClient for Google Play Location Services
LocationClient locationClient;
private ScrollView scroller;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
verifyBluetooth();
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
BeaconScannerApp app = (BeaconScannerApp)this.getApplication();
beaconManager = app.getBeaconManager();
//beaconManager.setForegroundScanPeriod(10);
region = app.getRegion();
beaconManager.bind(this);
locationClient = new LocationClient(this, this, this);
fileHelper = app.getFileHelper();
scroller = (ScrollView)ScanActivity.this.findViewById(R.id.scanScrollView);
editText = (EditText)ScanActivity.this.findViewById(R.id.scanText);
// Initialise scan button.
getScanButton().setText(MODE_STOPPED);
}
#Override
public void onResume() {
super.onResume();
beaconManager.bind(this);
}
#Override
public void onPause() {
super.onPause();
// Uncommenting the following leak prevents a ServiceConnection leak when using the back
// arrow in the Action Bar to come out of the file list screen. Unfortunately it also kills
// background scanning, and as I have no workaround right now I'm settling for the lesser of
// two evils.
// beaconManager.unbind(this);
}
public String getCurrentLocation() {
/** Default "error" value is set for location, will be overwritten with the correct lat and
* long values if we're ble to connect to location services and get a reading.
*/
String location = "Unavailable";
if (locationClient.isConnected()) {
Location currentLocation = locationClient.getLastLocation();
if (currentLocation != null) {
location = Double.toString(currentLocation.getLatitude()) + "," +
Double.toString(currentLocation.getLongitude());
}
}
return location;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public void onBeaconServiceConnect() {}
/**
*
* #param view
*/
public void onScanButtonClicked(View view) {
toggleScanState();
}
// Handle the user selecting "Settings" from the action bar.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.Settings:
// Show settings
Intent api = new Intent(this, AppPreferenceActivity.class);
startActivityForResult(api, 0);
return true;
case R.id.action_listfiles:
// Launch list files activity
Intent fhi = new Intent(this, FileHandlerActivity.class);
startActivity(fhi);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Start and stop scanning, and toggle button label appropriately.
*/
private void toggleScanState() {
Button scanButton = getScanButton();
String currentState = scanButton.getText().toString();
if (currentState.equals(MODE_SCANNING)) {
stopScanning(scanButton);
} else {
startScanning(scanButton);
}
}
/**
* start looking for beacons.
*/
private void startScanning(Button scanButton) {
// Set UI elements to the correct state.
scanButton.setText(MODE_SCANNING);
((EditText)findViewById(R.id.scanText)).setText("");
// Reset event counter
eventNum = 1;
// Get current values for logging preferences
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
HashMap <String, Object> prefs = new HashMap<String, Object>();
prefs.putAll(sharedPrefs.getAll());
index = (Boolean)prefs.get(PREFERENCE_INDEX);
location = (Boolean)prefs.get(PREFERENCE_LOCATION);
uuid = (Boolean)prefs.get(PREFERENCE_UUID);
majorMinor = (Boolean)prefs.get(PREFERENCE_MAJORMINOR);
rssi = (Boolean)prefs.get(PREFERENCE_RSSI);
proximity = (Boolean)prefs.get(PREFERENCE_PROXIMITY);
power = (Boolean)prefs.get(PREFERENCE_POWER);
timestamp = (Boolean)prefs.get(PREFERENCE_TIMESTAMP);
scanInterval = (String)prefs.get(PREFERENCE_SCANINTERVAL);
realTimeLog = (Boolean)prefs.get(PREFERENCE_REALTIME);
// Get current background scan interval (if specified)
if (prefs.get(PREFERENCE_SCANINTERVAL) != null) {
beaconManager.setBackgroundBetweenScanPeriod(Long.parseLong(scanInterval));
}
logToDisplay("Scanning...");
// Initialise scan log
logString = new StringBuffer();
//Start scanning again.
beaconManager.setRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
if (beacons.size() > 0) {
Iterator <Beacon> beaconIterator = beacons.iterator();
while (beaconIterator.hasNext()) {
Beacon beacon = beaconIterator.next();
// Debug - logging a beacon - checking background logging is working.
System.out.println("Logging another beacon.");
logBeaconData(beacon);
}
}
}
});
try {
beaconManager.startRangingBeaconsInRegion(region);
} catch (RemoteException e) {
// TODO - OK, what now then?
}
}
/**
* Stop looking for beacons.
*/
private void stopScanning(Button scanButton) {
try {
beaconManager.stopRangingBeaconsInRegion(region);
} catch (RemoteException e) {
// TODO - OK, what now then?
}
String scanData = logString.toString();
if (scanData.length() > 0) {
// Write file
fileHelper.createFile(scanData);
// Display file created message.
Toast.makeText(getBaseContext(),
"File saved to:" + getFilesDir().getAbsolutePath(),
Toast.LENGTH_SHORT).show();
scanButton.setText(MODE_STOPPED);
} else {
// We didn't get any data, so there's no point writing an empty file.
Toast.makeText(getBaseContext(),
"No data captured during scan, output file will not be created.",
Toast.LENGTH_SHORT).show();
scanButton.setText(MODE_STOPPED);
}
}
/**
*
* #return reference to the start/stop scanning button
*/
private Button getScanButton() {
return (Button)findViewById(R.id.scanButton);
}
/**
*
* #param beacon The detected beacon
*/
private void logBeaconData(Beacon beacon) {
StringBuilder scanString = new StringBuilder();
if (index) {
scanString.append(eventNum++);
}
if (beacon.getServiceUuid() == 0xfeaa) {
if (beacon.getBeaconTypeCode() == 0x00) {
scanString.append(" Eddystone-UID -> ");
scanString.append(" Namespace : ").append(beacon.getId1());
scanString.append(" Identifier : ").append(beacon.getId2());
logEddystoneTelemetry(scanString, beacon);
} else if (beacon.getBeaconTypeCode() == 0x10) {
String url = UrlBeaconUrlCompressor.uncompress(beacon.getId1().toByteArray());
scanString.append(" Eddystone-URL -> " + url);
} else if (beacon.getBeaconTypeCode() == 0x20) {
scanString.append(" Eddystone-TLM -> ");
logEddystoneTelemetry(scanString, beacon);
}
} else {
// Just an old fashioned iBeacon or AltBeacon...
logGenericBeacon(scanString, beacon);
}
logToDisplay(scanString.toString());
scanString.append("\n");
// Code added following a feature request by D.Schmid - writes a single entry to a file
// every time a beacon is detected, the file will only ever have one entry as it will be
// recreated on each call to this method.
// Get current background scan interval (if specified)
if (realTimeLog) {
// We're in realtime logging mode, create a new log file containing only this entry.
fileHelper.createFile(scanString.toString(), "realtimelog.txt");
}
logString.append(scanString.toString());
}
/**
* Logs iBeacon & AltBeacon data.
*/
private void logGenericBeacon(StringBuilder scanString, Beacon beacon) {
// Comment stuff out for whatever reason
/*
if (location) {
scanString.append(" Location: ").append(getCurrentLocation()).append(" ");
}
`
*/
if (uuid) {
scanString.append(" UUID: ").append(beacon.getId1());
if (beacon.getId1().equals("ffffffff-ffff-ffff-ffff-ffffffffffff ")){
scanString.append("WE DID IT!!!!!!!!!!!");
}else{
scanString.append(" WE DID NOT DO IT =( ");
}
/*
if ((beacon.getId1()).equals ("f")){
scanString.append("WE DID IT!!!!!!!!!!!");
}else{
scanString.append(" WE DID NOT DO IT!!!!!!!!!!! ");
}
*/
}
// Making if statements to test for advertising data
/*
if (majorMinor) {
scanString.append(" Maj. Mnr.: ");
if (beacon.getId2() != null) {
scanString.append(beacon.getId2());
}
scanString.append("-");
if (beacon.getId3() != null) {
scanString.append(beacon.getId3());
}
}
if (rssi) {
scanString.append(" RSSI: ").append(beacon.getRssi());
}
if (proximity) {
scanString.append(" Proximity: ").append(BeaconHelper.getProximityString(beacon.getDistance()));
}
if (power) {
scanString.append(" Power: ").append(beacon.getTxPower());
}
if (timestamp) {
scanString.append(" Timestamp: ").append(BeaconHelper.getCurrentTimeStamp());
} */
}
private void logEddystoneTelemetry(StringBuilder scanString, Beacon beacon) {
// Do we have telemetry data?
if (beacon.getExtraDataFields().size() > 0) {
long telemetryVersion = beacon.getExtraDataFields().get(0);
long batteryMilliVolts = beacon.getExtraDataFields().get(1);
long pduCount = beacon.getExtraDataFields().get(3);
long uptime = beacon.getExtraDataFields().get(4);
scanString.append(" Telemetry version : " + telemetryVersion);
scanString.append(" Uptime (sec) : " + uptime);
scanString.append(" Battery level (mv) " + batteryMilliVolts);
scanString.append(" Tx count: " + pduCount);
}
}
/**
*
* #param line
*/
private void logToDisplay(final String line) {
runOnUiThread(new Runnable() {
public void run() {
editText.append(line + "\n");
// Temp code - don't really want to do this for every line logged, will look for a
// workaround.
Linkify.addLinks(editText, Linkify.WEB_URLS);
scroller.fullScroll(View.FOCUS_DOWN);
}
});
}
private void verifyBluetooth() {
try {
if (!BeaconManager.getInstanceForApplication(this).checkAvailability()) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Bluetooth not enabled");
builder.setMessage("Please enable bluetooth in settings and restart this application.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
finish();
System.exit(0);
}
});
builder.show();
}
}
catch (RuntimeException e) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Bluetooth LE not available");
builder.setMessage("Sorry, this device does not support Bluetooth LE.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
finish();
System.exit(0);
}
});
builder.show();
}
}
/* Location services code follows */
#Override
protected void onStart() {
super.onStart();
// Connect the client.
locationClient.connect();
}
#Override
protected void onStop() {
// Disconnect the client.
locationClient.disconnect();
super.onStop();
}
#Override
public void onConnected(Bundle dataBundle) {
// Uncomment the following line to display the connection status.
// Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
}
#Override
public void onDisconnected() {
// Display the connection status
Toast.makeText(this, "Disconnected. Please re-connect.",
Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Toast.makeText(getBaseContext(),
"Location services not available, cannot track device location.",
Toast.LENGTH_SHORT).show();
}
}
// Define a DialogFragment that displays the error dialog
public static class ErrorDialogFragment extends DialogFragment {
// Global field to contain the error dialog
private Dialog mDialog;
// Default constructor. Sets the dialog field to null
public ErrorDialogFragment() {
super();
mDialog = null;
}
// Set the dialog to display
public void setDialog(Dialog dialog) {
mDialog = dialog;
}
// Return a Dialog to the DialogFragment.
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return mDialog;
}
}
/*
* Handle results returned to the FragmentActivity
* by Google Play services
*/
#Override
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
// Decide what to do based on the original request code
switch (requestCode) {
case CONNECTION_FAILURE_RESOLUTION_REQUEST :
/*
* If the result code is Activity.RESULT_OK, try
* to connect again
*/
switch (resultCode) {
case Activity.RESULT_OK :
/*
* TODO - Try the request again
*/
break;
}
}
}
}
Need to cast to string first .toString
if (uuid) {
scanString.append(" UUID: ").append(beacon.getId1());
// Making if statements to look for all f's in advertising data
if (beacon.getId1().toString().equals(Str1)){
scanString.append("\nAlarm ACTIVATED\n");
}else{
scanString.append("\n Alarm NOT active\n");
}
}
I'm trying to create an app with a OCR Scanner by using the tessract/tess-two library, I've successful access to the Phone camera, I can do the manual focus but when I take a picture the following error:
07-18 19:07:06.335 2585-2585/com.fastnetserv.myapp D/DBG_com.fastnetserv.myapp.MainActivity: Picture taken
07-18 19:07:06.335 2585-2585/com.fastnetserv.myapp D/DBG_com.fastnetserv.myapp.MainActivity: Got null data
07-18 19:07:06.405 2585-2585/com.fastnetserv.myapp D/DBG_com.fastnetserv.myapp.MainActivity: Picture taken
07-18 19:07:06.426 2585-2585/com.fastnetserv.myapp D/DBG_com.fastnetserv.myapp.MainActivity: Got bitmap
07-18 19:07:06.427 2585-11599/com.fastnetserv.myapp E/DBG_com.fastnetserv.myapp.TessAsyncEngine: Error passing parameter to execute(context, bitmap)
07-18 19:07:14.111 2585-2585/com.fastnetserv.myapp D/DBG_com.fastnetserv.myapp.CameraUtils: CameraEngine Stopped
Here the CameraFragment code:
package com.fastnetserv.myapp;
import android.content.Context;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.googlecode.tesseract.android.TessBaseAPI;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link //CameraFragment.//OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link CameraFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class CameraFragment extends Fragment implements SurfaceHolder.Callback, View.OnClickListener,
Camera.PictureCallback, Camera.ShutterCallback {
static final String TAG = "DBG_" + MainActivity.class.getName();
Button shutterButton;
Button focusButton;
FocusBoxView focusBox;
SurfaceView cameraFrame;
CameraEngine cameraEngine;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public CameraFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment CameraFragment.
*/
// TODO: Rename and change types and number of parameters
public static CameraFragment newInstance(String param1, String param2) {
CameraFragment fragment = new CameraFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_camera, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mListener = (OnFragmentInteractionListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
// Camera Code
public String detectText(Bitmap bitmap) {
TessDataManager.initTessTrainedData(getActivity());
TessBaseAPI tessBaseAPI = new TessBaseAPI();
String path = "/mnt/sdcard/com.fastnetserv.myapp/tessdata/ita.traineddata";
Log.d(TAG, "Check data path: " + path);
tessBaseAPI.setDebug(true);
tessBaseAPI.init(path, "ita"); //Init the Tess with the trained data file, with english language
//For example if we want to only detect numbers
tessBaseAPI.setVariable(TessBaseAPI.VAR_CHAR_WHITELIST, "1234567890");
tessBaseAPI.setVariable(TessBaseAPI.VAR_CHAR_BLACKLIST, "!##$%^&*()_+=-qwertyuiop[]}{POIU" +
"YTREWQasdASDfghFGHjklJKLl;L:'\"\\|~`xcvXCVbnmBNM,./<>?");
tessBaseAPI.setImage(bitmap);
String text = tessBaseAPI.getUTF8Text();
//Log.d(TAG, "Got data: " + result);
tessBaseAPI.end();
return text;
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "Surface Created - starting camera");
if (cameraEngine != null && !cameraEngine.isOn()) {
cameraEngine.start();
}
if (cameraEngine != null && cameraEngine.isOn()) {
Log.d(TAG, "Camera engine already on");
return;
}
cameraEngine = CameraEngine.New(holder);
cameraEngine.start();
Log.d(TAG, "Camera engine started");
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
#Override
public void onResume() {
super.onResume();
cameraFrame = (SurfaceView) getActivity().findViewById(R.id.camera_frame);
shutterButton = (Button) getActivity().findViewById(R.id.shutter_button);
focusBox = (FocusBoxView) getActivity().findViewById(R.id.focus_box);
focusButton = (Button) getActivity().findViewById(R.id.focus_button);
shutterButton.setOnClickListener(this);
focusButton.setOnClickListener(this);
SurfaceHolder surfaceHolder = cameraFrame.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
cameraFrame.setOnClickListener(this);
}
#Override
public void onPause() {
super.onPause();
if (cameraEngine != null && cameraEngine.isOn()) {
cameraEngine.stop();
}
SurfaceHolder surfaceHolder = cameraFrame.getHolder();
surfaceHolder.removeCallback(this);
}
#Override
public void onClick(View v) {
if(v == shutterButton){
if(cameraEngine != null && cameraEngine.isOn()){
cameraEngine.takeShot(this, this, this);
}
}
if(v == focusButton){
if(cameraEngine!=null && cameraEngine.isOn()){
cameraEngine.requestFocus();
}
}
}
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Log.d(TAG, "Picture taken");
if (data == null) {
Log.d(TAG, "Got null data");
return;
}
Bitmap bmp = Tools.getFocusedBitmap(getActivity(), camera, data, focusBox.getBox());
Log.d(TAG, "Got bitmap");
new TessAsyncEngine().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, this, bmp);
}
#Override
public void onShutter() {
}
}
And here the TessAsyncEngine:
package com.fastnetserv.myapp;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.util.Log;
import com.fastnetserv.myapp.ImageDialog;
import com.fastnetserv.myapp.Tools;
/**
* Created by Fadi on 6/11/2014.
*/
public class TessAsyncEngine extends AsyncTask<Object, Void, String> {
static final String TAG = "DBG_" + TessAsyncEngine.class.getName();
private Bitmap bmp;
private Activity context;
#Override
protected String doInBackground(Object... params) {
try {
if(params.length < 2) {
Log.e(TAG, "Error passing parameter to execute - missing params");
return null;
}
if(!(params[0] instanceof Activity) || !(params[1] instanceof Bitmap)) {
Log.e(TAG, "Error passing parameter to execute(context, bitmap)");
return null;
}
context = (Activity)params[0];
bmp = (Bitmap)params[1];
if(context == null || bmp == null) {
Log.e(TAG, "Error passed null parameter to execute(context, bitmap)");
return null;
}
int rotate = 0;
if(params.length == 3 && params[2]!= null && params[2] instanceof Integer){
rotate = (Integer) params[2];
}
if(rotate >= -180 && rotate <= 180 && rotate != 0)
{
bmp = Tools.preRotateBitmap(bmp, rotate);
Log.d(TAG, "Rotated OCR bitmap " + rotate + " degrees");
}
TessEngine tessEngine = TessEngine.Generate(context);
bmp = bmp.copy(Bitmap.Config.ARGB_8888, true);
String result = tessEngine.detectText(bmp);
Log.d(TAG, result);
return result;
} catch (Exception ex) {
Log.d(TAG, "Error: " + ex + "\n" + ex.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String s) {
if(s == null || bmp == null || context == null)
return;
ImageDialog.New()
.addBitmap(bmp)
.addTitle(s)
.show(context.getFragmentManager(), TAG);
super.onPostExecute(s);
}
}
I have followed this tutorial (http://www.codeproject.com/Tips/840623/Android-Character-Recognition) but probably I forgot something due to the lack of my knowledge with Android
That if(context == null || bmp == null) is not needed, as you already tested those values with instanceof.
But I'm guessing your main problem is passing this from Fragment as Activity parameter, which is not.
To fix.. I overall would try to not toss Activity pointer around wildly, as those have quite limited life cycle on android. I have an app with tess-two and I don't recall ever needing Activity to init it (although usually I init it from native C++, so YMMV).
Isn't just the Context needed for that call? If yes, I would suggest to move to getApplicationContext() value instead. I think this is directly or indirectly accessible from Fragment too.
Sorry for not trying your code, but this is something you can debug quite easily.
One more note to android and tesseract usage. What is Tools.getFocusedBitmap? Will it cut down the pic reasonably? If it keeps full size, and your Camera is set to full size, you are tossing around 5-10+MP Bitmaps around, which in Android means to hit Out-Of-Memory (OOM) almost instantly. Either set Camera to reasonably low resolution, or cut-out designed part of photo ASAP and drop the whole Image, ideally as first step of processing.
Also you may want to reconsider whole tess-two thing, and try the official Google Text API from Google play services.
https://developers.google.com/android/reference/com/google/android/gms/vision/text/Text
It's brand new addition, inside I guess it will use the second generation of Tesseract engine with latest improvements, so very likely to get better results and better speed, than from tess-two.
I think it's accessible only from Android 4.4 and only on devices with Google Play Services, and cross-platform sucks, so I'm staying with tess-two in my projects - as I have to support also iOS and Windows Phone.
And generally I don't believe things which don't come with source along, SW without source is zombie, already dead while you are using it (will take at most 30-50y to die), and it's a waste of time and skill of those programmers.
I am using the following code to make the android device a ftp server (Android Internal storage). I am getting the exception of os.android.NetworkOnMainThread. I have tried to put the onStart code in the AsyncTask but app never executes and crashes on launch. Any help regarding the ftp server on Android will be great as i have no idea how to get it working.
Here is the MainActivity Code
package com.googlecode.simpleftp;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class FTPServer extends Activity {
private static int COMMAND_PORT = 2121;
static final int DIALOG_ALERT_ID = 0;
private static ExecutorService executor = Executors.newCachedThreadPool();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.new_game:
System.out.println("New game button is pressed!");
//newGame();
return true;
case R.id.quit:
System.out.println("Quit button is pressed!");
showDialog(DIALOG_ALERT_ID);
return true;
default:
return super.onOptionsItemSelected(item); }
}
#Override
protected Dialog onCreateDialog(int id){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false).setPositiveButton("yes", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int id){
FTPServer.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
return alert;
}
HEre is the ServerPI Code
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ServerPI implements Runnable{
private Socket clientSocket;
private BufferedReader in;
private PrintWriter out;
private String baseDir;
private String relativeDir;
private String absoluteDir;
private String fileName;
private String filePath;
public ServerPI(Socket incoming) throws IOException{
this.clientSocket = incoming;
in = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
out = new PrintWriter(this.clientSocket.getOutputStream(), true);
baseDir = new File("").getAbsolutePath();
relativeDir = "/";
absoluteDir = baseDir + relativeDir;
fileName = "";
filePath = absoluteDir + "/" + fileName;
}
private void readCommandLoop() throws IOException {
String line = null;
reply(220, "Welcome to the SimpleFTP server!");
while((line = in.readLine()) != null){
int replyCode = executeCommand(line.trim());
if(replyCode == 221){
return;
}
}
}
private int executeCommand(String trim) {
// TODO Auto-generated method stub
return 0;
}
public int reply(int statusCode, String statusMessage){
out.println(statusCode + " " + statusMessage);
return statusCode;
}
#Override
public void run(){
try{
this.readCommandLoop();
} catch (IOException e){
e.printStackTrace();
}
finally {
try {
if(in != null){
in.close();
in = null;
}
if(out != null){
out.close();
out = null;
}
if (clientSocket != null){
clientSocket.close();
clientSocket = null;
}
}
catch (IOException e){
e.printStackTrace();
}
}
}
}
I have put the code in the AsyncTask, here it is
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
ServerSocket s = null;
Socket incoming = null;
try{
s = new ServerSocket(COMMAND_PORT);
String ip = (s.getInetAddress()).getHostAddress();
Context context = this.getApplicationContext();
CharSequence text = ip;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
Thread.sleep(1000);
toast.show();
while(true){
incoming = s.accept();
executor.execute(new ServerPI(incoming));
}
}
catch(Exception e){
System.out.println(e.toString());
e.printStackTrace();
}
finally{
try
{
if(incoming != null)incoming.close();
}
catch(IOException ignore)
{
//ignore
}
try
{
if (s!= null)
{
s.close();
}
}
catch(IOException ignore)
{
//ignore
}
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
Iam calling the longOpertation in onCreate method. What is the problem that the app crashes on launch.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
new LongOperation().execute();
}
Maybe because you didn't set up the permissions in the manifest? You've to set permission for internet usage.
If this doesn't work, please tell us which line is it throwing the exception.
while(true){ incoming = s.accept(); ...} You cannot put that in OnStart(). That should be done in a thread. So ServerSocket s = null; should be a variable of you activity.
So I went with Swiftp application (open source) as a service in my application which helped me to achieve my task. Thanks everyone who stepped forward to help. Here is the link if someone wants to follow
Please post your code here.
NetworkOnMainthreadException occurs because you maybe running Network related operation on the Main UI Thread. You should use asynctask for this purpose
This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged.
http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
class TheTask extends AsyncTask<Void,Void,Void>
{
protected void onPreExecute()
{ super.onPreExecute();
//display progressdialog.
}
protected void doInBackground(Void ...params)//return result here
{
//http request. do not update ui here
//call webservice
//return result here
return null;
}
protected void onPostExecute(Void result)//result of doInBackground is passed a parameter
{
super.onPostExecute(result);
//dismiss progressdialog.
//update ui using the result returned form doInbackground()
}
}
http://developer.android.com/reference/android/os/AsyncTask.html. Check the topic under the heading The 4 Steps.
A working example of asynctask # To use the tutorial in android 4.0.3 if had to work with AsynxTasc but i still dont work?.
The above makes a webserive call in doInBakckground(). Returns result and updates the ui by setting the result in textview in onPostExecute().
You can not do network operation in main thread in android 3.0 higher. Use AsyncTask for this network operation. See this for further explanation
package info.testing;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.widget.Toast;
public class SoupActivity extends Activity {
private static final String TAG = "SoupActivity";
private static final String DATA = null;
private String data = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if(savedInstanceState != null)
{
data = savedInstanceState.getString(DATA);
showResults();
}
else
{
parsePage();
}
}
protected void parsePage(){
Document doc = null;
try {
doc = Jsoup.connect("http://www.mydata.html").get();
Toast.makeText(this, R.string.success, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this, R.string.error, Toast.LENGTH_SHORT).show();
}
Elements rows = doc.select("tr[class]");
data = "<table>" + rows.toString() + "</table>";
showResults();
}
protected void showResults(){
WebView web = (WebView)findViewById(R.id.web);
web.loadData(data, "text/html", "utf-8");
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
savedInstanceState.putString(DATA, data);
super.onSaveInstanceState(savedInstanceState);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState){
if(savedInstanceState != null)
{
data = savedInstanceState.getString(DATA);
}
super.onRestoreInstanceState(savedInstanceState);
}
}
Flash/Flex developer here starting to get in to Android development, I must admit I am loving it so far, but obviously taking a long time to work out why things happen the way they do.
So the problem I have is that my app crashes without an Internet connection - The application (process.testing) has stopped unexpectedly. This only happens when there is no internet connection and works perfectly if there is one. The only part of my code that accesses the Internet is in a try catch block, can anyone see what I'm doing wrong or how I can handle the error when there is no Internet connection available?
You can use this function to see if a connection is available :
/**
* Check the network state
* #param context context of application
* #return true if the phone is connected
*/
public static boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
return true;
}
return false;
}
When you have no internet connection, doc is probably null and you get NullPointerException because you don't check this case:
Document doc = null;
try {
// connect throws an exception, doc still null
doc = Jsoup.connect("http://www.mydata.html").get();
Toast.makeText(this, R.string.success, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this, R.string.error, Toast.LENGTH_SHORT).show();
}
// dereferencing null (doc) throws NullPointerException
Elements rows = doc.select("tr[class]");
We are using android phones to communicate with sensors via bluetooth. The phone needs to connect the sensor periodically to collect physiological data and between two connections the sensors can be switched off automatically to save power.
Now the problem is: after around 500 times, the system reboots. We then wrote a small piece of test program to simulate the whole process. The small test program, too, crashes the android phone.
Can anybody please help me on this ? Thanks! Here is the small test program.
package zhb.test.MhubTestBtConnect;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MhubTestBtConnect extends Activity implements OnClickListener{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnStart = (Button) findViewById(R.id.btn_start_test);
btnStart.setOnClickListener(this);
Button btnStop = (Button) findViewById(R.id.btn_stop_test);
btnStop.setOnClickListener(this);
fBeginView = (TextView) findViewById(R.id.begin_time);
fBeginView.setText("off line");
fEndView = (TextView) findViewById(R.id.end_time);
fEndView.setText("off line");
fShowView = (TextView) findViewById(R.id.show_status);
fShowView.setText("off line");
fShowRunTimesView = (TextView) findViewById(R.id.show_times_status);
fShowRunTimesView.setText("off line");
fInputMac = (EditText) findViewById(R.id.edit_add_mac);
fInputMac.setText("00:19:5D:24:CB:A9");
fDisconnectGap = (EditText) findViewById(R.id.edit_disconnect_gap);
fDisconnectGap.setText("500");
fconnectGap = (EditText) findViewById(R.id.edit_connect_gap);
fconnectGap.setText("1000");
fRunning = false;
}
#Override
public void onClick(View v)
{
switch ( v.getId() )
{
case R.id.btn_start_test:
start();
break;
case R.id.btn_stop_test:
stop();
break;
default:
break;
}
}
private synchronized void start()
{
if ( fRunning == false )
{
fRunning = true;
fMac = fInputMac.getText().toString().toUpperCase();
fConnectRunnable = new ConnectRunnable();
fBeginView.setText(new Date().toLocaleString());
fConnectTimes = 0;
fRunOkTimes = 0;
new Thread(fConnectRunnable).start();
}
}
private synchronized void stop()
{
if ( fRunning == true )
{
fRunning = false;
fConnectRunnable.cancel();
try
{
Thread.sleep(500);
}
catch (InterruptedException exception)
{
exception.printStackTrace();
}
fEndView.setText(new Date().toLocaleString());
}
}
private void connect()
{
Log.d(TAG,"---------- run "+fConnectTimes++ +" times");
String UUID_STRING = "00001101-0000-1000-8000-00805F9B34FB";
// may throws exception
UUID uuid = UUID.fromString(UUID_STRING);
// get adapter
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
// get remote device
BluetoothDevice btDevice = adapter.getRemoteDevice(fMac);
if ( btDevice == null )
{
Log.e(TAG,"can't get remote device from given MAC : " + fMac);
return;
}
int runResult = 0;
// may throws exception
fBtSocket = null;
try
{
fBtSocket = btDevice.createRfcommSocketToServiceRecord(uuid);
if ( adapter.isDiscovering() == true )
{
adapter.cancelDiscovery();
Log.d(TAG,"cancel discover");
}
fBtSocket.connect();
runResult = 1;
Log.d(TAG,"connect socket OK");
Log.d(TAG,"---------- run OK "+fRunOkTimes++ +" times");
}
catch (IOException exception)
{
//adapter.cancelDiscovery();
Log.d(TAG,"connect socket error",exception);
if ( fBtSocket != null )
{
try
{
fBtSocket.close();
}
catch (IOException exception1)
{
Log.d(TAG,"close socket error",exception1);
}
}
else
{
Log.d(TAG,"create socket NULL");
}
btDevice = null;
//update ui
Message msgRun = new Message();
msgRun.what = R.id.show_status;
msgRun.arg1 = SV_START_RUN;
msgRun.arg2 = runResult;
fMessHandler.sendMessage(msgRun);
}
//Note: You should always ensure that the device is not performing device discovery when you call connect().
//If discovery is in progress, then the connection attempt will be significantly slowed and is more likely to fail.
//adapter.cancelDiscovery();
}
private void close()
{
//update ui
Message msgShut = new Message();
msgShut.what = R.id.show_status;
msgShut.arg1 = SV_SHUT_DOWN;
fMessHandler.sendMessage(msgShut);
if ( fBtSocket != null )
{
Log.d(TAG,"close socket");
try
{
fBtSocket.close();
}
catch (IOException exception1)
{
Log.d(TAG,"close socket error",exception1);
}
fBtSocket = null;
}
}
private Handler fMessHandler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
switch ( msg.what )
{
case R.id.show_status:
if ( msg.arg1 == SV_START_RUN )
{
if ( msg.arg2 == 1)
fShowView.setText("run OK");
else
fShowView.setText("run Failed");
fShowRunTimesView.setText("run "+fConnectTimes+", OK "+fRunOkTimes);
}
else if ( msg.arg1 == SV_SHUT_DOWN )
fShowView.setText("shut down ...");
break;
default:
break;
}
};
};
private long fConnectTimes;
private long fRunOkTimes;
private static final String TAG = "..MhubTestBtConnect";
private BluetoothSocket fBtSocket;
private ConnectRunnable fConnectRunnable;
private String fMac;
private boolean fRunning;
private TextView fBeginView;
private TextView fEndView;
private TextView fShowView;
private TextView fShowRunTimesView;
private EditText fInputMac;
private EditText fDisconnectGap;
private EditText fconnectGap;
private static final int SV_START_RUN = 1;
private static final int SV_SHUT_DOWN = 2;
private class ConnectRunnable implements Runnable
{
public ConnectRunnable()
{
fCancelled = false;
}
#Override
public void run()
{
if (Looper.myLooper() == null) {
Looper.prepare();
}
long afterConnectSleep = 500;
long afterCloseSleep = 1000;
try
{
afterCloseSleep = Integer.parseInt(fconnectGap.getText().toString());
afterConnectSleep = Integer.parseInt(fDisconnectGap.getText().toString());
}
catch(Exception exception)
{
afterConnectSleep = 500;
afterCloseSleep = 1000;
}
while ( fCancelled == false )
{
connect();
try
{
Thread.sleep(afterConnectSleep);
}
catch (InterruptedException exception)
{
exception.printStackTrace();
}
close();
try
{
Thread.sleep(afterCloseSleep);
}
catch (InterruptedException exception)
{
exception.printStackTrace();
}
}
}
public void cancel()
{
fCancelled = true;
}
private boolean fCancelled;
}
}
This is a bug I reported a while back regarding failed bluetooth connects (512 to be exact) and a memory leak leading to "referencetable overflow. I'll dig up the link when I'm back at my PC =)
Link: http://code.google.com/p/android/issues/detail?id=8676
Solution: avoid failed bluetooth connects by performing a Bluetooth discovery first to see if the device is in range. If so, cancel discovery and connect to it.