I'm trying to make a compass and want to print out the current location in a Textview. However, when I do that it gives me the latitude and longitude for Tehran (Iran) which isn't correct.
public class Kompas extends AppCompatActivity implements AnimationListener,
OnSharedPreferenceChangeListener, ConstantUtilInterface {
private boolean faceUp = true;
private boolean gpsLocationFound = true;
private String location_line2 = "";
public Location currentLocation = null;
private double lastTargetAngle = 0;
private double lastNorthAngle = 0;
private double lastTargetAngleFromN = 0;
// This animation is used to rotate north and target images
private RotateAnimation animation;
private ImageView compassImageView;
private ImageView locationImageView;
private final LocationCompassManager locationCompassManager = new LocationCompassManager(this);
private boolean angleSignaled = false;
private Timer timer = null;
private SharedPreferences perfs;
public boolean isRegistered = false;
public boolean isGPSRegistered = false;
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message message) {
if (message.what == ROTATE_IMAGES_MESSAGE) {
Bundle bundle = message.getData();
boolean isTargetChanged = bundle.getBoolean(IS_TARGET_CHANGED);
boolean isCompassChanged = bundle
.getBoolean(IS_COMPASS_CHANGED);
double targetNewAngle = 0;
double compassNewAngle = 0;
if (isTargetChanged)
targetNewAngle = (Double) bundle.get(TARGET_BUNDLE_DELTA_KEY);
if (isCompassChanged) {
compassNewAngle = (Double) bundle
.get(COMPASS_BUNDLE_DELTA_KEY);
}
// This
syncTargetAndNorthArrow(compassNewAngle, targetNewAngle,
isCompassChanged, isTargetChanged);
angleSignaled = false;
}
}
};
public void setLocationText(String textToShow) {
this.location_line2 = textToShow;
}
private TimerTask getTimerTask() {
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
if (angleSignaled && !ConcurrencyUtil.isAnyAnimationOnRun()) {
// numAnimationOnRun += 2;
Map<String, Double> newAnglesMap = locationCompassManager
.fetchDeltaAngles();
Double newNorthAngle = newAnglesMap
.get(LocationCompassManager.NORTH_CHANGED_MAP_KEY);
Double newTargetAngle = newAnglesMap
.get(LocationCompassManager.TARGET_CHANGED_MAP_KEY);
Message message = mHandler.obtainMessage();
message.what = ROTATE_IMAGES_MESSAGE;
Bundle b = new Bundle();
if (newNorthAngle == null) {
b.putBoolean(IS_COMPASS_CHANGED, false);
} else {
ConcurrencyUtil.incrementAnimation();
b.putBoolean(IS_COMPASS_CHANGED, true);
b.putDouble(COMPASS_BUNDLE_DELTA_KEY, newNorthAngle);
}
if (newTargetAngle == null) {
b.putBoolean(IS_TARGET_CHANGED, false);
} else {
ConcurrencyUtil.incrementAnimation();
b.putBoolean(IS_TARGET_CHANGED, true);
b.putDouble(TARGET_BUNDLE_DELTA_KEY, newTargetAngle);
}
message.setData(b);
mHandler.sendMessage(message);
} else if (ConcurrencyUtil.getNumAimationsOnRun() < 0) {
}
}
};
return timerTask;
}
private void schedule() {
if (timer == null) {
timer = new Timer();
this.timer.schedule(getTimerTask(), 0, 200);
} else {
timer.cancel();
timer = new Timer();
timer.schedule(getTimerTask(), 0, 200);
}
}
private void cancelSchedule() {
if (timer == null)
return;
// timer.cancel();
}
private void onInvalidateLocation(String message) {
}
private void requestForValidationOfLocation() {
// TextView textView = (TextView)
// findViewById(R.id.location_text_line1);
TextView textView2 = (TextView) findViewById(R.id.location_text_line2);
ImageView arrow = ((ImageView) findViewById(R.id.arrowImage));
ImageView compass = ((ImageView) findViewById(R.id.compassImage));
ImageView frame = ((ImageView) findViewById(R.id.frameImage));
FrameLayout targetFrame = ((FrameLayout) findViewById(R.id.targetLayout));
LinearLayout noLocationLayout = ((LinearLayout) findViewById(R.id.noLocationLayout));
if (faceUp && (gpsLocationFound || currentLocation != null)) {
textView2.setVisibility(View.VISIBLE);
textView2.setText(location_line2);
((LinearLayout) findViewById(R.id.textLayout))
.setVisibility(View.VISIBLE);
noLocationLayout.setVisibility(View.INVISIBLE);
targetFrame.setVisibility(View.VISIBLE);
arrow.setVisibility(View.VISIBLE);
compass.setVisibility(View.VISIBLE);
frame.setVisibility(View.VISIBLE);
} else {
if (!faceUp) {
onScreenDown();
} else if (!(gpsLocationFound || currentLocation != null)) {
onGPSOn();
}
}
}
private void onGPSOn() {
gpsLocationFound = false;
onInvalidateLocation(getString(R.string.no_location_yet));
}
public void onScreenDown() {
faceUp = false;
onInvalidateLocation(getString(R.string.screen_down_text));
}
public void onScreenUp() {
faceUp = true;
requestForValidationOfLocation();
}
public void onNewLocationFromGPS(Location location) {
gpsLocationFound = true;
currentLocation = location;
requestForValidationOfLocation();
}
private void onGPSOff(Location defaultLocation) {
currentLocation = defaultLocation;
gpsLocationFound = false;
requestForValidationOfLocation();
}
private String getLocationForPrint(double latitude, double longitude) {
int latDegree = (new Double(Math.floor(latitude))).intValue();
int longDegree = (new Double(Math.floor(longitude))).intValue();
String latEnd = getString(R.string.latitude_south);
String longEnd = getString(R.string.longitude_west);
if (latDegree > 0) {
latEnd = getString(R.string.latitude_north);
}
if (longDegree > 0) {
longEnd = getString(R.string.longitude_east);
}
double latSecond = (latitude - latDegree) * 100;
double latMinDouble = (latSecond * 3d / 5d);
int latMinute = new Double(Math.floor(latMinDouble)).intValue();
double longSecond = (longitude - longDegree) * 100;
double longMinDouble = (longSecond * 3d / 5d);
int longMinute = new Double(Math.floor(longMinDouble)).intValue();
return String.format(getString(R.string.geo_location_info), latDegree,
latMinute, latEnd, longDegree, longMinute, longEnd);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.kompas);
registerListeners();
Context context = getApplicationContext();
perfs = PreferenceManager.getDefaultSharedPreferences(context);
perfs.registerOnSharedPreferenceChangeListener(this);
String gpsPerfKey = getString(R.string.gps_pref_key);
TextView text1 = (TextView) findViewById(R.id.location_text_line2);
TextView text2 = (TextView) findViewById(R.id.noLocationText);
getLocationName(currentLocation.getLatitude(), currentLocation.getLongitude());
getSupportActionBar().setTitle("Qiblah");
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8b4513")));
boolean isGPS = false;
try {
isGPS = Boolean.parseBoolean(perfs.getString(gpsPerfKey, "false"));
} catch (ClassCastException e) {
isGPS = perfs.getBoolean(gpsPerfKey, false);
}
if (!isGPS) {
unregisterForGPS();
useDefaultLocation(perfs,
getString(R.string.state_location_pref_key));
} else {
registerForGPS();
onGPSOn();
}
this.locationImageView = (ImageView) findViewById(R.id.arrowImage);
this.compassImageView = (ImageView) findViewById(R.id.compassImage);
}
private void unregisterListeners() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
((LocationManager) getSystemService(Context.LOCATION_SERVICE))
.removeUpdates(locationCompassManager);
((LocationManager) getSystemService(Context.LOCATION_SERVICE))
.removeUpdates(locationCompassManager);
SensorManager mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor gsensor = mSensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
Sensor msensor = mSensorManager
.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
mSensorManager.unregisterListener(locationCompassManager, gsensor);
mSensorManager.unregisterListener(locationCompassManager, msensor);
cancelSchedule();
}
public void getLocationName(double lattitude, double longitude) {
}
private void registerForGPS() {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setSpeedRequired(false);
criteria.setCostAllowed(true);
LocationManager locationManager = ((LocationManager) getSystemService(Context.LOCATION_SERVICE));
String provider = locationManager.getBestProvider(criteria, true);
if (provider != null) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(provider, MIN_LOCATION_TIME,
MIN_LOCATION_DISTANCE, locationCompassManager);
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_LOCATION_TIME, MIN_LOCATION_DISTANCE, locationCompassManager);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, MIN_LOCATION_TIME,
MIN_LOCATION_DISTANCE, locationCompassManager);
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null) {
location = ((LocationManager) getSystemService(Context.LOCATION_SERVICE))
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
if (location != null) {
locationCompassManager.onLocationChanged(location);
}
}
private void unregisterForGPS() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
((LocationManager) getSystemService(Context.LOCATION_SERVICE))
.removeUpdates(locationCompassManager);
}
private void registerListeners() {
SharedPreferences perfs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
if (perfs.getBoolean(getString(R.string.gps_pref_key), false)) {
registerForGPS();
} else {
useDefaultLocation(perfs,
getString(R.string.state_location_pref_key));
}
SensorManager mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor gsensor = mSensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
Sensor msensor = mSensorManager
.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
mSensorManager.registerListener(locationCompassManager, gsensor,
SensorManager.SENSOR_DELAY_GAME);
mSensorManager.registerListener(locationCompassManager, msensor,
SensorManager.SENSOR_DELAY_GAME);
schedule();
isRegistered = true;
}
#Override
protected void onResume() {
super.onResume();
registerListeners();
}
#Override
protected void onPause() {
super.onPause();
ConcurrencyUtil.setToZero();
ConcurrencyUtil.directionChangedLock.readLock();
unregisterListeners();
}
public void syncTargetAndNorthArrow(double northNewAngle,
double targetNewAngle, boolean northChanged, boolean targetChanged) {
if (northChanged) {
lastNorthAngle = rotateImageView(northNewAngle, lastNorthAngle,
compassImageView);
if (targetChanged == false && targetNewAngle != 0) {
lastTargetAngleFromN = targetNewAngle;
lastTargetAngle = rotateImageView(targetNewAngle + northNewAngle,
lastTargetAngle, locationImageView);
} else if (targetChanged == false && targetNewAngle == 0)
lastTargetAngle = rotateImageView(lastTargetAngleFromN
+ northNewAngle, lastTargetAngle, locationImageView);
}
if (targetChanged) {
lastTargetAngleFromN = targetNewAngle;
lastTargetAngle = rotateImageView(targetNewAngle + lastNorthAngle,
lastTargetAngle, locationImageView);
}
}
private double rotateImageView(double newAngle, double fromDegree,
ImageView imageView) {
newAngle = newAngle % 360;
double rotationDegree = fromDegree - newAngle;
rotationDegree = rotationDegree % 360;
long duration = new Double(Math.abs(rotationDegree) * 2000 / 360)
.longValue();
if (rotationDegree > 180)
rotationDegree -= 360;
FrameLayout frameLayout = (FrameLayout) findViewById(R.id.targetLayout);
float toDegree = new Double(newAngle % 360).floatValue();
final int width = Math.abs(frameLayout.getRight()
- frameLayout.getLeft());
final int height = Math.abs(frameLayout.getBottom()
- frameLayout.getTop());
LinearLayout main = (LinearLayout) findViewById(R.id.mainLayout);
float pivotX = width / 2f;
float pivotY = height / 2f;
animation = new RotateAnimation(new Double(fromDegree).floatValue(),
toDegree, pivotX, pivotY);
animation.setRepeatCount(0);
animation.setDuration(duration);
animation.setInterpolator(new LinearInterpolator());
animation.setFillEnabled(true);
animation.setFillAfter(true);
animation.setAnimationListener(this);
imageView.startAnimation(animation);
return toDegree;
}
public void signalForAngleChange() {
this.angleSignaled = true;
}
public void onAnimationEnd(Animation animation) {
if (ConcurrencyUtil.getNumAimationsOnRun() <= 0) {
} else {
ConcurrencyUtil.decrementAnimation();
}
schedule();
}
public void onAnimationRepeat(Animation animation) {
}
public void onAnimationStart(Animation animation) {
cancelSchedule();
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
String gpsPerfKey = getString(R.string.gps_pref_key);
String defaultLocationPerfKey = getString(R.string.state_location_pref_key);
if (gpsPerfKey.equals(key)) {
boolean isGPS = false;
try {
isGPS = Boolean.parseBoolean(sharedPreferences.getString(key,
"false"));
} catch (ClassCastException e) {
isGPS = sharedPreferences.getBoolean(key, false);
}
if (isGPS) {
registerForGPS();
currentLocation = null;
onGPSOn();
} else {
useDefaultLocation(sharedPreferences, defaultLocationPerfKey);
unregisterForGPS();
}
} else if (defaultLocationPerfKey.equals(key)) {
sharedPreferences.edit().putBoolean(gpsPerfKey, false);
sharedPreferences.edit().commit();
unregisterForGPS();
useDefaultLocation(sharedPreferences, key);
}
}
private void useDefaultLocation(SharedPreferences perfs, String key) {
int defLocationID = Integer.parseInt(perfs.getString(key, ""
+ LocationEnum.MENU_TEHRAN.getId()));
LocationEnum locationEnum = LocationEnum.values()[defLocationID - 1];
Location location = locationEnum.getLocation();
locationCompassManager.onLocationChanged(location);
onGPSOff(location);
}
#Override
public void onBackPressed() {
finish();
}
}
The way I found out was that I printed out the city name and the latitude/longitude and they gave me Tehran. I've written the correct permissions in the Manifest, and the GPS/Location is turned on, on my device
You want to implement an so called DEG to DMS conversion (decimal degrees to Degrees minutes, seconds).
Your formula seems to be wrong:
Especially the longSecond * 3d / 5d);
For correct formula look at the first lines of:
https://en.wikipedia.org/wiki/Geographic_coordinate_conversion
Related
i made a googlemap app where my markers are displyed.
the problem is when there no internet, the app is crashing. The code under onResume does not solve the problem.
also i want to refresh the map or markers each second on the map.
if you have any ideas please i am here to learn from all of you.
here is my MapActivity code :
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback
{
private static final String TAG = "MapActivity";
#Bind(R.id.back)
View back;
#Bind(R.id.zoom_in)
View zoom_in;
#Bind(R.id.zoom_out)
View zoom_out;
#Bind(R.id.updatetimer)
TextView updatetimer;
#Bind(R.id.autozoom)
ImageView autozoom;
#Bind(R.id.showtails)
ImageView showtails;
#Bind(R.id.geofences)
ImageView showGeofences;
#Bind(R.id.map_layer)
ImageView map_layer_icon;
private GoogleMap map;
#Bind(R.id.content_layout)
View content_layout;
#Bind(R.id.loading_layout)
View loading_layout;
#Bind(R.id.nodata_layout)
View nodata_layout;
private Timer timer;
private int autoZoomedTimes = 0;// dėl bugo osmdroid library, zoom'inam du kartus ir paskui po refresh'o nebe, nes greičiausiai user'is bus pakeitęs zoom'ą
private HashMap<Integer, Marker> deviceIdMarkers;
private HashMap<String, Device> markerIdDevices;
private HashMap<Integer, Polyline> deviceIdPolyline;
private HashMap<Integer, LatLng> deviceIdLastLatLng;
// private HashMap<Integer, Marker> deviceIdSmallMarkerInfo;
private long lastRefreshTime;
boolean isAutoZoomEnabled = true;
boolean isShowTitlesEnabled;
boolean isShowTailsEnabled = true;
boolean isShowGeofencesEnabled = true;
private String stopTime;
private AsyncTask downloadingAsync;
private boolean isRefreshLoced = false;
ApiInterface.GetGeofencesResult geofencesResult;
ArrayList<PolygonWithName> polygonsWithDetails = new ArrayList<>();
float previousZoomLevel = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
ButterKnife.bind(this);
deviceIdMarkers = new HashMap<>();
markerIdDevices = new HashMap<>();
deviceIdPolyline = new HashMap<>();
deviceIdLastLatLng = new HashMap<>();
// deviceIdSmallMarkerInfo = new HashMap<>();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
protected void onResume()
{
super.onResume();
timer = new Timer();
timer.schedule(new TimerTask()
{
#Override
public void run()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
float timeleft = 10 - Math.round(System.currentTimeMillis() - lastRefreshTime) / 1000f;
if (timeleft < 0)
timeleft = 0;
updatetimer.setText(String.format("%.0f", timeleft));
if (System.currentTimeMillis() - lastRefreshTime >= 10 * 1000)
if (map != null)
refresh();
}
});
}
}, 0, 1000);
}
#Override
protected void onPause()
{
super.onPause();
try
{
timer.cancel();
timer.purge();
downloadingAsync.cancel(true);
} catch (Exception e)
{
e.printStackTrace();
}
}
private void refresh()
{
if (isRefreshLoced)
return;
isRefreshLoced = true;
lastRefreshTime = System.currentTimeMillis();
final String api_key = (String) DataSaver.getInstance(this).load("api_key");
API.getApiInterface(this).getDevices(api_key, getResources().getString(R.string.lang), new Callback<ArrayList<ApiInterface.GetDevicesItem>>()
{
#Override
public void success(final ArrayList<ApiInterface.GetDevicesItem> getDevicesItems, Response response)
{
Log.d(TAG, "success: loaded devices array");
final ArrayList<Device> allDevices = new ArrayList<>();
if (getDevicesItems != null)
for (ApiInterface.GetDevicesItem item : getDevicesItems)
allDevices.addAll(item.items);
API.getApiInterface(MapActivity.this).getFieldsDataForEditing(api_key, getResources().getString(R.string.lang), 1, new Callback<ApiInterface.GetFieldsDataForEditingResult>()
{
#Override
public void success(final ApiInterface.GetFieldsDataForEditingResult getFieldsDataForEditingResult, Response response)
{
Log.d(TAG, "success: loaded icons");
downloadingAsync = new AsyncTask<Void, Void, Void>()
{
ArrayList<MarkerOptions> markers;
ArrayList<Integer> deviceIds;
#Override
protected Void doInBackground(Void... params)
{
// add markers
int dp100 = Utils.dpToPx(MapActivity.this, 50);
markers = new ArrayList<>();
deviceIds = new ArrayList<>();
if (getFieldsDataForEditingResult == null || getFieldsDataForEditingResult.device_icons == null)
return null;
for (Device item : allDevices)
{
if (isCancelled())
break;
if (item.device_data.active == 1)
{
// ieškom ikonos masyve
DeviceIcon mapIcon = null;
for (DeviceIcon icon : getFieldsDataForEditingResult.device_icons)
if (item.device_data.icon_id == icon.id)
mapIcon = icon;
String server_base = (String) DataSaver.getInstance(MapActivity.this).load("server_base");
try
{
Log.d("MapActivity", "DOWNLOADING BITMAP: " + server_base + mapIcon.path);
Bitmap bmp = BitmapFactory.decodeStream(new URL(server_base + mapIcon.path).openConnection().getInputStream());
int srcWidth = bmp.getWidth();
int srcHeight = bmp.getHeight();
int maxWidth = Utils.dpToPx(MapActivity.this, mapIcon.width);
int maxHeight = Utils.dpToPx(MapActivity.this, mapIcon.height);
float ratio = Math.min((float) maxWidth / (float) srcWidth, (float) maxHeight / (float) srcHeight);
int dstWidth = (int) (srcWidth * ratio);
int dstHeight = (int) (srcHeight * ratio);
bmp = bmp.createScaledBitmap(bmp, dp100, dp100, true);
// marker
MarkerOptions m = new MarkerOptions();
m.position(new LatLng(item.lat, item.lng));
// marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
// marker.setIcon(new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bmp, dstWidth, dstHeight, true)));
m.icon(BitmapDescriptorFactory.fromBitmap(Bitmap.createScaledBitmap(bmp, dstWidth, dstHeight, true)));
// info window
// MapMarkerInfoWindow infoWindow = new MapMarkerInfoWindow(MapActivity.this, item, R.layout.layout_map_infowindow, map);
// marker.setInfoWindow(infoWindow);
markers.add(m);
deviceIds.add(item.id);
} catch (OutOfMemoryError outOfMemoryError)
{
Toast.makeText(MapActivity.this, "Out of memory! Too many devices are selected to be displayed", Toast.LENGTH_LONG).show();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid)
{
ArrayList<GeoPoint> points = new ArrayList<>();
if (autoZoomedTimes < 1)
{
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
if (markers.size() > 1)
{
try
{
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (MarkerOptions item : markers)
builder.include(item.getPosition());
LatLngBounds bounds = builder.build();
// int padding = 0; // offset from edges of the map in pixels
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, Utils.dpToPx(MapActivity.this, 50));
map.animateCamera(cu);
} catch (Exception e)
{
}
} else if (markers.size() > 0)
{
map.moveCamera(CameraUpdateFactory.newLatLngZoom(markers.get(0).getPosition(), 15));
}
autoZoomedTimes++;
}
});
}
}, 50);
} else if (isAutoZoomEnabled)
{
if (markers.size() > 1)
{
try
{
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (MarkerOptions item : markers)
builder.include(item.getPosition());
LatLngBounds bounds = builder.build();
// int padding = 0; // offset from edges of the map in pixels
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, Utils.dpToPx(MapActivity.this, 50));
map.animateCamera(cu);
} catch (Exception e)
{
}
} else if (markers.size() > 0)
{
map.moveCamera(CameraUpdateFactory.newLatLngZoom(markers.get(0).getPosition(), 15));
}
autoZoomedTimes++;
}
Log.d(TAG, "onPostExecute: icons downloaded and added to map, total markers: " + markers.size());
loading_layout.setVisibility(View.GONE);
if (markers.size() != 0)
content_layout.setVisibility(View.VISIBLE);
else
nodata_layout.setVisibility(View.VISIBLE);
for (int i = 0; i < markers.size(); i++)
{
MarkerOptions options = markers.get(i);
int deviceId = deviceIds.get(i);
Marker m;
Polyline polyline;
if (deviceIdMarkers.containsKey(deviceId))
{
Log.d("aa", "moving to" + options.getPosition());
deviceIdMarkers.get(deviceId).setPosition(new LatLng(options.getPosition().latitude, options.getPosition().longitude));
m = deviceIdMarkers.get(deviceId);
polyline = deviceIdPolyline.get(deviceId);
} else
{
Log.d("aa", "putting new");
m = map.addMarker(options);
deviceIdMarkers.put(deviceId, m);
polyline = map.addPolyline(new PolylineOptions());
deviceIdPolyline.put(deviceId, polyline);
}
Device thatonedevice = null;
for (Device device : allDevices)
if (device.id == deviceId)
thatonedevice = device;
markerIdDevices.put(m.getId(), thatonedevice);
// update marker rotation based on driving direction
if (thatonedevice != null && deviceIdLastLatLng.containsKey(deviceId))
{
double dirLat = thatonedevice.lat - deviceIdLastLatLng.get(deviceId).latitude;
double dirLng = thatonedevice.lng - deviceIdLastLatLng.get(deviceId).longitude;
m.setRotation((float) Math.toDegrees(Math.atan2(dirLng, dirLat)));
}
deviceIdLastLatLng.put(deviceId, new LatLng(thatonedevice.lat, thatonedevice.lng));
List<LatLng> polylinePoints = new ArrayList<>();
for (TailItem item : thatonedevice.tail)
polylinePoints.add(new LatLng(Double.valueOf(item.lat), Double.valueOf(item.lng)));
polyline.setPoints(polylinePoints);
polyline.setWidth(Utils.dpToPx(MapActivity.this, 2));
polyline.setColor(Color.parseColor(thatonedevice.device_data.tail_color));
}
// else
map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter()
{
#Override
public View getInfoWindow(Marker marker)
{
return null;
}
#Override
public View getInfoContents(final Marker marker)
{
synchronized (this)
{
}
final Device device = markerIdDevices.get(marker.getId());
if (device != null)
{
View view = getLayoutInflater().inflate(R.layout.layout_map_infowindow, null);
view.bringToFront();
view.findViewById(R.id.close).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
marker.hideInfoWindow();
}
});
TextView device_name = (TextView) view.findViewById(R.id.device_name);
device_name.setText(device.name);
TextView altitude = (TextView) view.findViewById(R.id.altitude);
altitude.setText(String.valueOf(device.altitude) + " " + device.unit_of_altitude);
TextView time = (TextView) view.findViewById(R.id.time);
time.setText(device.time);
TextView stopTimeView = (TextView) view.findViewById(R.id.stopTime);
stopTimeView.setText(stopTime);
TextView speed = (TextView) view.findViewById(R.id.speed);
speed.setText(device.speed + " " + device.distance_unit_hour);
TextView address = (TextView) view.findViewById(R.id.address);
address.setText(device.address);
final ArrayList<Sensor> showableSensors = new ArrayList<>();
for (Sensor item : device.sensors)
if (item.show_in_popup > 0)
showableSensors.add(item);
ListView sensors_list = (ListView) view.findViewById(R.id.sensors_list);
sensors_list.setAdapter(new AwesomeAdapter<Sensor>(MapActivity.this)
{
#Override
public int getCount()
{
return showableSensors.size();
}
#NonNull
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent)
{
if (convertView == null)
convertView = getLayoutInflater().inflate(R.layout.adapter_map_sensorslist, null);
Sensor item = showableSensors.get(position);
TextView name = (TextView) convertView.findViewById(R.id.name);
name.setText(item.name);
TextView value = (TextView) convertView.findViewById(R.id.value);
value.setText(item.value);
return convertView;
}
});
List<Address> addresses;
try
{
addresses = new Geocoder(MapActivity.this).getFromLocation(device.lat, device.lng, 1);
if (addresses.size() > 0)
address.setText(addresses.get(0).getAddressLine(0));
} catch (IOException e)
{
e.printStackTrace();
}
return view;
}
return null;
}
});
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener()
{
#Override
public boolean onMarkerClick(final Marker marker)
{
int px = Utils.dpToPx(MapActivity.this, 300);
map.setPadding(0, px, 0, 0);
stopTime = "...";
final Device device = markerIdDevices.get(marker.getId());
if (device != null)
{
API.getApiInterface(MapActivity.this).deviceStopTime((String) DataSaver.getInstance(MapActivity.this).load("api_key"), "en", device.id, new Callback<ApiInterface.DeviceStopTimeResult>()
{
#Override
public void success(ApiInterface.DeviceStopTimeResult result, Response response)
{
stopTime = result.time;
marker.showInfoWindow();
}
#Override
public void failure(RetrofitError retrofitError)
{
Toast.makeText(MapActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
}
});
}
return false;
}
});
map.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener()
{
#Override
public void onInfoWindowClick(Marker marker)
{
marker.hideInfoWindow();
}
});
map.setOnInfoWindowCloseListener(new GoogleMap.OnInfoWindowCloseListener()
{
#Override
public void onInfoWindowClose(Marker marker)
{
map.setPadding(0, 0, 0, 0);
}
});
// updateSmallMarkerData(allDevices);
isRefreshLoced = false;
}
}.execute();
}
#Override
public void failure(RetrofitError retrofitError)
{
Toast.makeText(MapActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
isRefreshLoced = false;
}
});
}
#Override
public void failure(RetrofitError retrofitError)
{
Toast.makeText(MapActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
isRefreshLoced = false;
}
});
}
#Override
public void onMapReady(GoogleMap googleMap)
{
map = googleMap;
refresh();
}
this MapActivity is slow to load, could you teach me a way to make it goes faster?
Best regard :)
waiting for your propositions.
PS: i have removed some functions to make the code look short but i kept the most important in is case.
For the crashing issue
create a class
public class NetWorkChecker {
static NetworkInfo wifi, mobile;
public static Boolean check(Context c) {
ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
} catch (Exception e) {
e.printStackTrace();
}
if (wifi != null && wifi.isConnected() && wifi.isAvailable()) {
return true;
} else if (mobile != null && mobile.isAvailable() && mobile.isConnected()) {
return true;
} else {
//Toast.makeText(c, "No Network Connection", Toast.LENGTH_SHORT).show();
// ((Activity) c).finish();
displayMobileDataSettingsDialog(c,"No Network Connection","No Network Connection");
return false;
}
}
public static AlertDialog displayMobileDataSettingsDialog(final Context context, String title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message);
builder.setCancelable(false);
builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
context.startActivity(intent);
}
});
builder.show();
return builder.create();
}
}
to check if the devise have an active internet connection
call
if (!NetWorkChecker.check(this)){
////do your refres
}
I added my application to Github to find my bug.
So the bug is like when I open my app for a first time and open "info" then "settings" and click thought all options, then "new measurement" then it goes to previous screen (settings) instead of new measurement. Could anybody help me?
Here is the link to app
Edit:
Here are probably the meaningfull classes:
Stages.java
public class Stages extends BaseActivity {
private final Stage0StageFragment stageZeroFragment = new Stage0StageFragment();
private final Stage1StageFragment stageOneFragment = new Stage1StageFragment();
private final Stage2StageFragment stageTwoFragment = new Stage2StageFragment();
private final Stage3StageFragment stageThreeFragment = new Stage3StageFragment();
private BottomNavigationView bottomNavView;
private int startingPosition, newPosition;
OnSwitchFragmentFromStageTwo onSwitchFragmentFromStageTwo;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Util.setThemeBasedOnPrefs(this);
setContentView(R.layout.stages);
spEditor.putBoolean("wantToClosePxCmInfo", false).apply();
bottomNavView = findViewById(R.id.bottom_navigation);
bottomNavView.setItemIconTintList(null);
bottomNavView.setOnNavigationItemSelectedListener(item -> {
if (bottomNavView.getSelectedItemId() == R.id.navigation_stage_zero) {
if (!sp.getBoolean("correctionDone", false)) {
AlertDialog alertDialog = Util.createAlertDialog(Stages.this, android.R.drawable.ic_dialog_info, R.string.hide_dialog_title, getString(R.string.stage_zero_confirmation), (dialog, which) -> {
spEditor.putBoolean("correctionDone", true).apply();
bottomNavView.setSelectedItemId(item.getItemId());
showFragment(item.getItemId());
});
alertDialog.setOnShowListener(arg0 -> setAlertDialogButtonsAttributes(alertDialog));
alertDialog.show();
return false;
} else {
showFragment(item.getItemId());
return true;
}
} else if (bottomNavView.getSelectedItemId() == R.id.navigation_stage_two) {
try {
if (onSwitchFragmentFromStageTwo.onSwitchFragmentFromFragmentTwo() <= 0.5 && !sp.getBoolean("wantToClosePxCmInfo", false)) {
AlertDialog ad = Util.createAlertDialog(Stages.this, android.R.drawable.ic_dialog_alert, R.string.hide_dialog_title_alert,
getResources().getString(R.string.benchmark_not_drawn), (dialog, which) -> {
spEditor.putBoolean("wantToClosePxCmInfo", true).apply();
bottomNavView.setSelectedItemId(item.getItemId());
showFragment(item.getItemId());
});
ad.setOnShowListener(arg0 -> setAlertDialogButtonsAttributes(ad));
ad.show();
return false;
} else {
showFragment(item.getItemId());
return true;
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
} else {
showFragment(item.getItemId());
}
return true;
});
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (!sp.getBoolean("correctionDone", false))
ft.replace(R.id.content_frame, stageZeroFragment);
else {
ft.replace(R.id.content_frame, stageOneFragment);
bottomNavView.setSelectedItemId(R.id.navigation_stage_one);
}
ft.commit();
}
#Override
BaseActivity getActivity() {
return this;
}
private void setAlertDialogButtonsAttributes(AlertDialog alertDialog2) {
alertDialog2.getButton(DialogInterface.BUTTON_NEGATIVE).setBackground(AppCompatResources.getDrawable(this, R.drawable.button_selector));
alertDialog2.getButton(DialogInterface.BUTTON_POSITIVE).setBackground(AppCompatResources.getDrawable(this, R.drawable.button_selector));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT,
1.0f
);
params.setMargins(10, 0, 10, 0);
alertDialog2.getButton(DialogInterface.BUTTON_NEGATIVE).setLayoutParams(params);
alertDialog2.getButton(DialogInterface.BUTTON_POSITIVE).setLayoutParams(params);
}
public void showFragment(int viewId) {
Fragment fragment = null;
switch (viewId) {
case R.id.navigation_stage_zero:
if (bottomNavView.getSelectedItemId() != R.id.navigation_stage_zero) {
fragment = stageZeroFragment;
newPosition = 0;
}
break;
case R.id.navigation_stage_one:
if (bottomNavView.getSelectedItemId() != R.id.navigation_stage_one) {
fragment = stageOneFragment;
newPosition = 1;
}
break;
case R.id.navigation_stage_two:
if (bottomNavView.getSelectedItemId() != R.id.navigation_stage_two) {
fragment = stageTwoFragment;
newPosition = 2;
}
break;
case R.id.navigation_stage_three:
if (bottomNavView.getSelectedItemId() != R.id.navigation_stage_three) {
fragment = stageThreeFragment;
newPosition = 3;
}
break;
}
if (fragment != null) {
if (startingPosition > newPosition) {
getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right)
.replace(R.id.content_frame, fragment).commit();
}
if (startingPosition < newPosition) {
getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left)
.replace(R.id.content_frame, fragment).commit();
}
startingPosition = newPosition;
}
}
}
Stage0StageFragment.java
public class Stage0StageFragment extends AbstractStageFragment {
private CheckBox checkboxSkip;
private int xCorrection, yCorrection;
private IndicatorSeekBar indicatorSeekBar;
private IndicatorSeekBar indicatorSeekBar2;
private AlertDialog alertDialog;
#Override
int getLayout() {
return R.layout.stage_zero;
}
#Override
public void onResume() {
super.onResume();
new CameraOpenerTask(this).execute();
}
#Override
public void onPause() {
super.onPause();
spEditor.putInt("indicator1", indicatorSeekBar.getProgress());
spEditor.putInt("indicator2", indicatorSeekBar2.getProgress());
spEditor.apply();
if (alertDialog.isShowing())
alertDialog.dismiss();
}
#Override
#SuppressLint({"ClickableViewAccessibility", "CommitPrefEdits"})
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.setOnTouchListener((v, event) -> {
int aktX = (int) event.getX();
int aktY = (int) event.getY();
setParamsToDrawRectangle(aktX, aktY);
return true;
});
configureSeekBars(view);
configureInitDialog();
}
#Override
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
Imgproc.cvtColor(inputFrame.rgba(), mRgba, Imgproc.COLOR_RGBA2RGB, 1);
Core.transpose(mGray, mGray);
Core.flip(mGray, mGray, -1);
Imgproc.line(mRgba, p1, p2, Util.BLUE);
Imgproc.line(mRgba, p3, p4, Util.BLUE);
Imgproc.rectangle(mRgba, new Point(touchedYD, touchedXL), new Point(touchedYU, touchedXR), Util.WHITE, 2);
return mRgba;
}
private void setParamsToDrawRectangle(int aktX, int aktY) {
// poziomo
if (-aktX + camLayHeight + (xCorrection * 10) < (camLayHeight / 2)) {
touchedXR = -aktX + camLayHeight + (xCorrection * 10);
if (touchedXR < 0) touchedXR = 0;
} else {
touchedXL = -aktX + camLayHeight + (xCorrection * 10);
if (touchedXL > camLayHeight) touchedXL = camLayHeight;
}
// pionowo
if (aktY - (yCorrection * 10) < (camLayWidth / 2)) {
touchedYU = aktY - (yCorrection * 10);
if (touchedYU < 0) touchedYU = 0;
} else {
touchedYD = aktY - (yCorrection * 10);
if (touchedYD > camLayWidth) touchedYD = camLayWidth;
}
}
public void configureSeekBars(View view) {
indicatorSeekBar = view.findViewById(R.id.percent_indicator);
indicatorSeekBar.setOnSeekChangeListener(new MyOnSeekChangeListener("x"));
indicatorSeekBar2 = view.findViewById(R.id.percent_indicator2);
indicatorSeekBar2.setOnSeekChangeListener(new MyOnSeekChangeListener("y"));
TextView tv = view.findViewById(R.id.info_about_indicators);
if (sp.getInt("indicator1", 0) != 0)
indicatorSeekBar.setProgress(sp.getInt("indicator1", 0));
if (sp.getInt("indicator2", 0) != 0)
indicatorSeekBar2.setProgress(sp.getInt("indicator2", 0));
if (sp.getInt("indicator1", 0) != 0 || sp.getInt("indicator2", 0) != 0)
tv.setVisibility(View.VISIBLE);
}
public void setScrollViewParamsDependingOnFont(View checkboxLayout) {
ScrollView layout = checkboxLayout.findViewById(R.id.scrollView);
ViewGroup.LayoutParams params = layout.getLayoutParams();
String fontPref = sp.getString("font", "Arial");
if (fontPref.equals("Ginger"))
params.height = (int) getResources().getDimension(R.dimen.height_of_checkbox);
if (fontPref.equals("Arial")) params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
layout.setLayoutParams(params);
}
void configureInitDialog() {
View checkboxLayout = View.inflate(getActivity(), R.layout.checkbox, null);
setScrollViewParamsDependingOnFont(checkboxLayout);
alertDialog = new AlertDialog.Builder(getActivity(), R.style.MyStyle).create();
alertDialog.setView(checkboxLayout);
alertDialog.setIcon(android.R.drawable.ic_dialog_info);
alertDialog.setTitle("Info");
alertDialog.setMessage(getResources().getString(R.string.stage_zero_dialog));
alertDialog.setCancelable(false);
alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL, "Ok", (dialogInterface, i) -> {
String checkBoxResult = "";
checkboxSkip = checkboxLayout.findViewById(R.id.checkboxSkip);
if (checkboxSkip.isChecked())
checkBoxResult = "linia2";
if (checkBoxResult.equals("linia2"))
spEditor.putBoolean("hideDialog", true).apply();
});
alertDialog.setOnShowListener(arg0 -> alertDialog.getButton(DialogInterface.BUTTON_NEUTRAL).setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_selector, null)));
if (!sp.getBoolean("hideDialog", false))
alertDialog.show();
}
public class MyOnSeekChangeListener implements OnSeekChangeListener {
private final String axisCorrection;
MyOnSeekChangeListener(String axisCorrection) {
this.axisCorrection = axisCorrection;
}
#Override
public void onSeeking(SeekParams seekParams) {
if (axisCorrection.equals("x"))
xCorrection = seekParams.progress;
if (axisCorrection.equals("y"))
yCorrection = seekParams.progress;
spEditor.putInt("xCorrection", xCorrection);
spEditor.putInt("yCorrection", yCorrection);
spEditor.apply();
}
#Override
public void onStartTrackingTouch(IndicatorSeekBar indicatorSeekBar) {
}
#Override
public void onStopTrackingTouch(IndicatorSeekBar indicatorSeekBar) {
}
}
Something wrong happen in those classes probably when opening "new measurement".
I am new to Java coding for android. I need to understand why does my code generate 2 threads. The problem that can be created over here is perhaps competition for Camera Resources which results in the camera not being used by the user. Kindly suggest a solution to my problem as well.
I have also attached a picture where there are 2 requests for a new activity. There is also proof by having 2 thread IDs active.
EDIT for clarity:
I want to generate a new thread which solely handles the activity to record the video, no other thread should be doing it. But there are two that are performing their own activity to record video.
public class MainActivity extends AppCompatActivity implements SensorEventListener/*, ActivityCompat.OnRequestPermissionsResultCallback*/ {
private Camera c;
private MainActivity reference_this = this;
private BooleanObject recorded_video = new BooleanObject("recorded_video",false);
private BooleanObject recorded_motions_chest = new BooleanObject("recorded_motions_chest", false);
private ChangeListener listener_change;
public void setListener(ChangeListener arg_listener_change) {
listener_change = arg_listener_change;
}
public interface ChangeListener {
void onChange(String arg_name);
}
public void set_recorded_video(boolean arg_recorded_video) {
recorded_video.set_value(arg_recorded_video);
if (listener_change != null) { listener_change.onChange(recorded_video.get_name()); }
}
public void set_recorded_motions_chest(boolean arg_recorded_motions_chest) {
recorded_motions_chest.set_value(arg_recorded_motions_chest);
if (listener_change != null) { listener_change.onChange(recorded_motions_chest.get_name()); }
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!(getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA))) {
this.finish();
System.exit(0);
}
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
this.setListener(new MainActivity.ChangeListener() {
#Override
public void onChange(String arg_name) {
Log.i("CHNG", "fired");
if (arg_name.equals(recorded_video.get_name())) {
VideoCapture video_capture = new VideoCapture();
video_capture.open(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/video_finger.mp4");
Mat frame = new Mat();
int length_video = (int) video_capture.get(Videoio.CAP_PROP_FRAME_COUNT);
int rate_frame = (int) video_capture.get(Videoio.CAP_PROP_FPS);
while (true) {
video_capture.read(frame);
Size size_img = frame.size();
Log.i("MAT", String.valueOf(size_img.width) + ' ' + String.valueOf(size_img.height));
}
}
else if (arg_name.equals(recorded_motions_chest.get_name())) {}
}
});
// new Thread(new Runnable() {
// public void run() {
Button button_symptoms = (Button) findViewById(R.id.button_symptoms);
Button button_upload_signs = (Button) findViewById(R.id.button_upload_signs);
Button button_measure_heart_rate = (Button) findViewById(R.id.button_measure_heart_rate);
Button button_measure_respiratory_rate = (Button) findViewById(R.id.button_measure_respiratory_rate);
CameraView cv1 = new CameraView(getApplicationContext(), reference_this);
FrameLayout view_camera = (FrameLayout) findViewById(R.id.view_camera);
view_camera.addView(cv1);
TextView finger_on_sensor = (TextView) findViewById(R.id.text_finger_on_sensor);
finger_on_sensor.setVisibility(View.INVISIBLE);
finger_on_sensor.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch (View arg_view, MotionEvent arg_me){
finger_on_sensor.setVisibility(View.INVISIBLE);
/*GENERATING THREADS OVER HERE*/ new Thread(new Runnable() {
public void run() {
File file_video = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/video_finger.mp4");
// final int REQUEST_WRITE_PERMISSION = 786;
final int VIDEO_CAPTURE = 1;
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent intent_record_video = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent_record_video.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 45);
Uri fileUri = FileProvider.getUriForFile(MainActivity.this, "com.example.cse535a1.provider", file_video);
intent_record_video.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
if (intent_record_video.resolveActivity(getPackageManager()) != null) {
Log.i("CAM", "CAM requeted");
Log.i("Thread ID", String.valueOf(Thread.currentThread().getId()));
startActivityForResult(intent_record_video, VIDEO_CAPTURE);
// reference_this.set_recorded_video(true);
}
}
}).start();
return true;
}
});
button_symptoms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View arg_view){
Intent intent = new Intent(getApplicationContext(), Loggin_symptoms.class);
startActivity(intent);
}
});
button_upload_signs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View arg_view){
}
});
button_measure_heart_rate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View arg_view){ finger_on_sensor.setVisibility(View.VISIBLE); }
});
button_measure_respiratory_rate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg_view) {
SensorManager manager_sensor = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor sensor_accelerometer = manager_sensor.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
manager_sensor.registerListener(MainActivity.this, sensor_accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
});
// }}).start();
}
public void setCam(Camera arg_camera) { c = arg_camera; }
#Override
public void onSensorChanged(SensorEvent arg_event) {
float x = arg_event.values[0];
float y = arg_event.values[1];
float z = arg_event.values[2];
Log.i("ACCELEROMETER", String.valueOf(x) + ' ' + String.valueOf(y) + ' ' + String.valueOf(z));
}
#Override
public void onAccuracyChanged(Sensor arg_sensor, int arg_accuracy) {
}
#Override
protected void onPause() {
super.onPause();
c.unlock();
// Log.i("CAM", "unlocked");
// if (c != null) {
// c.stopPreview();
//// c.release();
//// c = null;
// }
}
#Override
protected void onResume() {
super.onResume();
if (c != null) c.lock();
// if (c != null) {
// c.stopPreview();
// c.release();
// c = null;
/// }
// cv1 = new CameraView(getApplicationContext(), this);
// view_camera.addView(cv1);
}
#Override
protected void onDestroy() {
if (c != null) {
// c.unlock();
c.stopPreview();
c.release();
c = null;
}
super.onDestroy();
}
private static class BooleanObject {
private String name = "BooleanObject";
private boolean value = false;
public BooleanObject(String arg_name, boolean arg_value) {
name = arg_name;
value = arg_value;
}
public String set_name(String arg_name) {
name = arg_name;
return name;
}
public boolean set_value(boolean arg_value) {
value = arg_value;
return value;
}
public String get_name() { return name; }
public boolean get_value() { return value; }
};
}
Every time you tap on TextView, as you are using onTouchListener, it will be fired twice, once for ACTION_DOWN and ACTION_UP, so check for ACTION_UP as in
finger_on_sensor.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch (View arg_view, MotionEvent arg_me){
if(arg_me.getAction() == MotionEvent.ACTION_UP){ //add this condition
finger_on_sensor.setVisibility(View.INVISIBLE);
new Thread(new Runnable() {
public void run() {
File file_video = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/video_finger.mp4");
// final int REQUEST_WRITE_PERMISSION = 786;
final int VIDEO_CAPTURE = 1;
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent intent_record_video = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent_record_video.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 45);
Uri fileUri = FileProvider.getUriForFile(MainActivity.this, "com.example.cse535a1.provider", file_video);
intent_record_video.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
if (intent_record_video.resolveActivity(getPackageManager()) != null) {
Log.i("CAM", "CAM requeted");
Log.i("Thread ID", String.valueOf(Thread.currentThread().getId()));
startActivityForResult(intent_record_video, VIDEO_CAPTURE);
//reference_this.set_recorded_video(true);
}
}
}).start();
return true;
}
});
Ill try my best to explain.
I have a page on my android app that is a google map that has stores locations on it.
Depending on the type of store, it has a custom icon. The link for the custom icon I retrieved trough MySQL.
The problem I am having is when I open the page instead of showing me the custom icons for the stores it shows me the default icon. But when I go to another page on the app and go back to the maps page it loads all the custom icons. It seems to me that on the first page launch it does not replace the default icon.
Since im new to programming ive added the whole page because I might be missing something. I think that the reason this is happening is due to the method "parseData()"
Thank you,
public class MapFragment extends Fragment implements
OnInfoWindowClickListener, OnMapClickListener,
OnClickListener, OnDrawingViewListener, GoogleMap.OnMapLoadedCallback{
private View viewInflate;
private GoogleMap googleMap;
private Location myLocation;
private HashMap<String, Store> markers;
private ArrayList<Marker> markerList;
private DisplayImageOptions options;
private MGSliding frameSliding;
private DrawingView drawingView;
private GMapV2Direction gMapV2;
private ArrayList<Store> storeList;
private ArrayList<Store> selectedStoreList;
private Store selectedStore;
Queries q;
MGAsyncTask task;
public MapFragment() { }
#Override
public void onDestroyView() {
super.onDestroyView();
try {
if (googleMap != null) {
FragmentManager fManager = this.getActivity().getSupportFragmentManager();
fManager.beginTransaction()
.remove(fManager.findFragmentById(R.id.googleMap)).commit();
googleMap = null;
}
if (viewInflate != null) {
ViewGroup parentViewGroup = (ViewGroup) viewInflate.getParent();
if (parentViewGroup != null) {
parentViewGroup.removeAllViews();
}
}
}
catch(Exception e) { }
if(task != null)
task.cancel(true);
}
#SuppressLint("InflateParams")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
viewInflate = inflater.inflate(R.layout.fragment_map2, null);
return viewInflate;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(UIConfig.SLIDER_PLACEHOLDER)
.showImageForEmptyUri(UIConfig.SLIDER_PLACEHOLDER)
.showImageOnFail(UIConfig.SLIDER_PLACEHOLDER)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
final MainActivity main = (MainActivity) getActivity();
q = main.getQueries();
frameSliding = (MGSliding) viewInflate.findViewById(R.id.frameSliding);
Animation animationIn = AnimationUtils.loadAnimation(this.getActivity(),
R.anim.slide_up2);
// int i = android.R.anim.slide_out_right;
Animation animationOut = AnimationUtils.loadAnimation(this.getActivity(),
R.anim.slide_down2);
frameSliding.setInAnimation(animationIn);
frameSliding.setOutAnimation(animationOut);
frameSliding.setVisibility(View.GONE);
ImageView imgViewDraw = (ImageView)viewInflate.findViewById(R.id.imgViewDraw);
imgViewDraw.setOnClickListener(this);
ImageView imgViewRefresh = (ImageView)viewInflate.findViewById(R.id.imgViewRefresh);
imgViewRefresh.setOnClickListener(this);
ImageView imgViewRoute = (ImageView)viewInflate.findViewById(R.id.imgViewRoute);
imgViewRoute.setOnClickListener(this);
ImageView imgViewLocation = (ImageView)viewInflate.findViewById(R.id.imgViewLocation);
imgViewLocation.setOnClickListener(this);
ImageView imgViewNearby = (ImageView)viewInflate.findViewById(R.id.imgViewNearby);
imgViewNearby.setOnClickListener(this);
main.showSwipeProgress();
FragmentManager fManager = getChildFragmentManager();
SupportMapFragment supportMapFragment =
((SupportMapFragment) fManager.findFragmentById(R.id.googleMap));
if(supportMapFragment == null) {
fManager = getActivity().getSupportFragmentManager();
supportMapFragment = ((SupportMapFragment) fManager.findFragmentById(R.id.googleMap));
}
googleMap = supportMapFragment.getMap();
googleMap.setOnMapLoadedCallback(this);
markers = new HashMap<String, Store>();
markerList = new ArrayList<Marker>();
}
#Override
public void onMapLoaded() {
FragmentManager fManager = getChildFragmentManager();
SupportMapFragment supportMapFragment =
((SupportMapFragment) fManager.findFragmentById(R.id.googleMap));
if(supportMapFragment == null) {
fManager = getActivity().getSupportFragmentManager();
supportMapFragment = ((SupportMapFragment) fManager.findFragmentById(R.id.googleMap));
}
googleMap = supportMapFragment.getMap();
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.setMyLocationEnabled(true);
googleMap.setOnMapClickListener(this);
googleMap.setOnInfoWindowClickListener(this);
googleMap.setOnMyLocationChangeListener(new OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
// TODO Auto-generated method stub
myLocation = location;
}
});
googleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition cameraPosition) {
if(frameSliding.getVisibility() == View.VISIBLE)
frameSliding.setVisibility(View.INVISIBLE);
}
});
gMapV2 = new GMapV2Direction();
drawingView = (DrawingView) viewInflate.findViewById(R.id.drawingView);
drawingView.setBrushSize(5);
drawingView.setPolygonFillColor(getResources().getColor(R.color.theme_black_color_opacity));
drawingView.setColor(getResources().getColor(R.color.theme_black_color));
drawingView.setPolylineColor(getResources().getColor(R.color.theme_black_color));
drawingView.setGoogleMap(googleMap);
drawingView.setOnDrawingViewListener(this);
if(MGUtilities.isLocationEnabled(getActivity())) {
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
getData();
}
}, Config.DELAY_SHOW_ANIMATION + 500);
}
else {
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
getData();
}
}, Config.DELAY_SHOW_ANIMATION + 500);
}
}
#SuppressLint("DefaultLocale")
#Override
public void onInfoWindowClick(Marker marker) {
// TODO Auto-generated method stub
final Store store = markers.get(marker.getId());
selectedStore = store;
if(myLocation != null) {
Location loc = new Location("marker");
loc.setLatitude(marker.getPosition().latitude);
loc.setLongitude(marker.getPosition().longitude);
double meters = myLocation.distanceTo(loc);
double miles = meters * 0.000621371f;
String str = String.format("%.1f %s",
miles,
MGUtilities.getStringFromResource(getActivity(), R.string.mi));
TextView tvDistance = (TextView) viewInflate.findViewById(R.id.tvDistance);
tvDistance.setText(str);
}
final MainActivity main = (MainActivity) getActivity();
q = main.getQueries();
frameSliding.setVisibility(View.VISIBLE);
ImageView imgViewThumb = (ImageView) viewInflate.findViewById(R.id.imageViewThumb);
Photo p = q.getPhotoByStoreId(store.getStore_id());
if(p != null) {
MainActivity.getImageLoader().displayImage(p.getPhoto_url(), imgViewThumb, options);
}
else {
imgViewThumb.setImageResource(UIConfig.SLIDER_PLACEHOLDER);
}
imgViewThumb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity(), DetailActivity.class);
i.putExtra("store", store);
getActivity().startActivity(i);
}
});
TextView tvTitle = (TextView) viewInflate.findViewById(R.id.tvTitle);
TextView tvSubtitle = (TextView) viewInflate.findViewById(R.id.tvSubtitle);
tvTitle.setText(Html.fromHtml(store.getStore_name()));
tvSubtitle.setText(Html.fromHtml(store.getIdade()));
ToggleButton toggleButtonFave = (ToggleButton) viewInflate.findViewById(R.id.toggleButtonFave);
toggleButtonFave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
checkFave(v, store);
}
});
Favorite fave = q.getFavoriteByStoreId(store.getStore_id());
toggleButtonFave.setChecked(true);
if(fave == null)
toggleButtonFave.setChecked(false);
}
#Override
public void onMapClick(LatLng point) {
// TODO Auto-generated method stub
frameSliding.setVisibility(View.INVISIBLE);
}
private void checkFave(View view, Store store) {
MainActivity mainActivity = (MainActivity)this.getActivity();
Queries q = mainActivity.getQueries();
Favorite fave = q.getFavoriteByStoreId(store.getStore_id());
if(fave != null) {
q.deleteFavorite(store.getStore_id());
((ToggleButton) view).setChecked(false);
}
else {
fave = new Favorite();
fave.setStore_id(store.getStore_id());
q.insertFavorite(fave);
((ToggleButton) view).setChecked(true);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()) {
case R.id.imgViewDraw:
drawingView.enableDrawing(true);
drawingView.startDrawingPolygon(true);
break;
case R.id.imgViewRefresh:
addStoreMarkers();
break;
case R.id.imgViewRoute:
getDirections();
break;
case R.id.imgViewLocation:
getMyLocation();
break;
case R.id.imgViewNearby:
getNearby();
break;
}
}
ArrayList<Marker> markers1;
#SuppressLint("DefaultLocale")
#Override
public void onUserDidFinishDrawPolygon(PolygonOptions polygonOptions) {
// TODO Auto-generated method stub
googleMap.clear();
googleMap.addPolygon( polygonOptions );
markers1 = getMarkersInsidePoly(polygonOptions, null, markerList);
markers = new HashMap<String, Store>();
markerList = new ArrayList<Marker>();
selectedStoreList = new ArrayList<Store>();
markerList.clear();
markers.clear();
for(Marker mark1 : markers1) {
for(Store entry : storeList) {
if(mark1.getTitle().toLowerCase().compareTo(entry.getStore_name().toLowerCase()) == 0) {
Marker mark = createMarker(entry);
markerList.add(mark);
markers.put(mark.getId(), entry);
selectedStoreList.add(entry);
break;
}
}
}
drawingView.enableDrawing(false);
drawingView.resetPolygon();
drawingView.startNew();
}
#Override
public void onUserDidFinishDrawPolyline(PolylineOptions polylineOptions) { }
public ArrayList<Marker> getMarkersInsidePoly(PolygonOptions polygonOptions,
PolylineOptions polylineOptions, ArrayList<Marker> markers) {
ArrayList<Marker> markersFound = new ArrayList<Marker>();
for(Marker mark : markers) {
Boolean isFound = polygonOptions != null ?
drawingView.latLongContainsInPolygon(mark.getPosition(), polygonOptions) :
drawingView.latLongContainsInPolyline(mark.getPosition(), polylineOptions);
if(isFound) {
markersFound.add(mark);
}
}
return markersFound;
}
public void addStoreMarkers() {
if(googleMap != null)
googleMap.clear();
try {
MainActivity main = (MainActivity) this.getActivity();
Queries q = main.getQueries();
storeList = q.getStores();
markerList.clear();
markers.clear();
for(Store entry: storeList) {
if(entry.getLat() == 0 || entry.getLon() == 0)
continue;
Marker mark = createMarker(entry);
markerList.add(mark);
markers.put(mark.getId(), entry);
}
showBoundedMap();
}
catch(Exception e) {
e.printStackTrace();
}
}
public void getDirections() {
if(selectedStore == null) {
Toast.makeText(getActivity(), R.string.select_one_store, Toast.LENGTH_SHORT).show();
return;
}
MGAsyncTask asyncTask = new MGAsyncTask(getActivity());
asyncTask.setMGAsyncTaskListener(new OnMGAsyncTaskListener() {
private ArrayList<ArrayList<LatLng>> allDirections;
#Override
public void onAsyncTaskProgressUpdate(MGAsyncTask asyncTask) { }
#Override
public void onAsyncTaskPreExecute(MGAsyncTask asyncTask) {
// TODO Auto-generated method stub
allDirections = new ArrayList<ArrayList<LatLng>>();
}
#Override
public void onAsyncTaskPostExecute(MGAsyncTask asyncTask) {
// TODO Auto-generated method stub
for(ArrayList<LatLng> directions : allDirections) {
PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);
for(LatLng latLng : directions) {
rectLine.add(latLng);
}
googleMap.addPolyline(rectLine);
}
if(allDirections.size() <= 0) {
Toast.makeText(getActivity(), R.string.cannot_determine_direction, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onAsyncTaskDoInBackground(MGAsyncTask asyncTask) {
// TODO Auto-generated method stub
parseData();
if(myLocation != null && selectedStore != null) {
LatLng marker1 = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
LatLng marker2 = new LatLng(selectedStore.getLat(), selectedStore.getLon());
Document doc = gMapV2.getDocument1(
marker1, marker2, GMapV2Direction.MODE_DRIVING);
ArrayList<LatLng> directionPoint = gMapV2.getDirection(doc);
allDirections.add(directionPoint);
}
}
});
asyncTask.startAsyncTask();
}
private void getMyLocation() {
if(myLocation == null) {
MGUtilities.showAlertView(
getActivity(),
R.string.location_error,
R.string.cannot_determine_location);
return;
}
addStoreMarkers();
CameraUpdate zoom = CameraUpdateFactory.zoomTo(Config.MAP_ZOOM_LEVEL);
googleMap.moveCamera(zoom);
CameraUpdate center = CameraUpdateFactory.newLatLng(
new LatLng(myLocation.getLatitude(), myLocation.getLongitude()));
googleMap.animateCamera(center);
}
private void getNearby() {
if(googleMap != null)
googleMap.clear();
if(myLocation == null) {
MGUtilities.showAlertView(
getActivity(),
R.string.route_error,
R.string.route_error_details);
return;
}
try {
MainActivity main = (MainActivity) this.getActivity();
Queries q = main.getQueries();
storeList = q.getStores();
markerList.clear();
markers.clear();
for(Store entry: storeList) {
Location destination = new Location("Origin");
destination.setLatitude(entry.getLat());
destination.setLongitude(entry.getLon());
double distance = myLocation.distanceTo(destination);
if(distance <= Config.MAX_RADIUS_NEARBY_IN_METERS) {
Marker mark = createMarker(entry);
markerList.add(mark);
markers.put(mark.getId(), entry);
}
}
CameraUpdate zoom = CameraUpdateFactory.zoomTo(Config.MAP_ZOOM_LEVEL);
googleMap.moveCamera(zoom);
CameraUpdate center = CameraUpdateFactory.newLatLng(
new LatLng(myLocation.getLatitude(), myLocation.getLongitude()));
googleMap.animateCamera(center);
}
catch(Exception e) {
e.printStackTrace();
}
}
private void showBoundedMap() {
if(markerList == null && markerList.size() == 0 ) {
MGUtilities.showNotifier(this.getActivity(), MainActivity.offsetY, R.string.failed_data);
return;
}
if(markerList.size() > 0) {
LatLngBounds.Builder bld = new LatLngBounds.Builder();
for (int i = 0; i < markerList.size(); i++) {
Marker marker = markerList.get(i);
bld.include(marker.getPosition());
}
LatLngBounds bounds = bld.build();
googleMap.moveCamera(
CameraUpdateFactory.newLatLngBounds(bounds,
this.getResources().getDisplayMetrics().widthPixels,
this.getResources().getDisplayMetrics().heightPixels,
70));
}
else {
MGUtilities.showNotifier(this.getActivity(), MainActivity.offsetY, R.string.no_results_found);
Location loc = MainActivity.location;
if(loc != null) {
googleMap.moveCamera(
CameraUpdateFactory.newLatLngZoom(new LatLng(loc.getLatitude(), loc.getLongitude()), 70));
}
}
}
private Marker createMarker(Store store) {
final MarkerOptions markerOptions = new MarkerOptions();
Spanned name = Html.fromHtml(store.getStore_name());
name = Html.fromHtml(name.toString());
Spanned storeAddress = Html.fromHtml("R$ " + store.getHora() + " /hr");
storeAddress = Html.fromHtml(storeAddress.toString());
markerOptions.title( name.toString() );
String address = storeAddress.toString();
if(address.length() > 50)
address = storeAddress.toString().substring(0, 50) + "...";
markerOptions.snippet(address);
markerOptions.position(new LatLng(store.getLat(), store.getLon()));
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.map_pin_orange));
Marker mark = googleMap.addMarker(markerOptions);
mark.setInfoWindowAnchor(Config.MAP_INFO_WINDOW_X_OFFSET, 0);
Category cat = q.getCategoryByCategoryId(store.getCategory_id());
if(cat != null && cat.getCategory_icon() != null) {
MGHSquareImageView imgView = new MGHSquareImageView(getActivity());
imgView.setMarker(mark);
imgView.setMarkerOptions(markerOptions);
imgView.setTag(store);
MainActivity.getImageLoader().displayImage(
cat.getCategory_icon(), imgView, options, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) { }
#Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) { }
#Override
public void onLoadingComplete(String imageUri, final View view, final Bitmap loadedImage) {
// TODO Auto-generated method stub
if(loadedImage != null) {
MGHSquareImageView v = (MGHSquareImageView)view;
Marker m = (Marker)v.getMarker();
m.remove();
MarkerOptions opt = (MarkerOptions)v.getMarkerOptions();
opt.icon(BitmapDescriptorFactory.fromBitmap(loadedImage));
Marker mark = googleMap.addMarker(opt);
Store s = (Store) v.getTag();
if(markers.containsKey(m.getId())) {
markerList.remove(m);
markerList.add(mark);
markers.remove(m);
markers.put(mark.getId(), s);
}
else {
markers.put(mark.getId(), s);
}
}
else {
Log.e("LOADED IMAGE", "IS NULL");
}
}
#Override
public void onLoadingCancelled(String imageUri, View view) { }
});
}
return mark;
}
public void getData() {
final MainActivity main = (MainActivity) getActivity();
main.showSwipeProgress();
task = new MGAsyncTask(getActivity());
task.setMGAsyncTaskListener(new OnMGAsyncTaskListener() {
#Override
public void onAsyncTaskProgressUpdate(MGAsyncTask asyncTask) { }
#Override
public void onAsyncTaskPreExecute(MGAsyncTask asyncTask) {
asyncTask.dialog.hide();
}
#Override
public void onAsyncTaskPostExecute(MGAsyncTask asyncTask) {
// TODO Auto-generated method stub
main.hideSwipeProgress();
new Handler().postDelayed(new Runnable() {
public void run() {
viewInflate.findViewById(R.id.imgViewRefresh4).setVisibility(View.GONE);
}
}, 0);
addStoreMarkers();
CameraUpdate zoom = CameraUpdateFactory.zoomTo(Config.MAP_ZOOM_LEVEL);
googleMap.moveCamera(zoom);
CameraUpdate center = CameraUpdateFactory.newLatLng(
new LatLng(myLocation.getLatitude(), myLocation.getLongitude()));
googleMap.animateCamera(center);
}
#Override
public void onAsyncTaskDoInBackground(MGAsyncTask asyncTask) {
// TODO Auto-generated method stub
parseData();
}
});
task.execute();
}
public void parseData() {
MainActivity main = (MainActivity) this.getActivity();
Queries q = main.getQueries();
DataParser parser = new DataParser();
Data data = parser.getData(Config.GET_STORES_JSON_URL);
if(data != null) {
if(data.getStores() != null && data.getStores().size() > 0) {
q.deleteTable("stores");
for(Store store : data.getStores()) {
q.insertStore(store);
}
}
if(data.getCategories() != null && data.getCategories().size() > 0) {
q.deleteTable("categories");
for(Category cat : data.getCategories()) {
q.insertCategory(cat);
}
}
if(data.getPhotos() != null && data.getPhotos().size() > 0) {
q.deleteTable("photos");
for(Photo photo : data.getPhotos()) {
q.insertPhoto(photo);
}
}
}
}
}
Check this documentation on how to customize the marker image.
You can replace the default marker image with a custom marker image, often called an icon. Custom icons are always set as a BitmapDescriptor, and defined using one of the methods in the BitmapDescriptorFactory class.
Here is a sample code on how to create a marker with a custom icon.
private static final LatLng MELBOURNE = new LatLng(-37.813, 144.962);
private Marker melbourne = mMap.addMarker(new MarkerOptions()
.position(MELBOURNE)
.title("Melbourne")
.snippet("Population: 4,137,400")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow)));
NOTE:
getMap() is already deprecated, so use getMapAsync() in your code.
For more information, check these related SO question.
How to create a custom-shaped bitmap marker with Android map API v2
create custom marker icons on runtime using android xml
How can I put the result of the QR "SCAN_RESULT" in different activity, this is my problem.
In the splash screen I need to go to the QRScanner (CaptureActivity), and then, to the ActivityQR who will send the info. to the SQLite.
The problem is: When I get de QRCode in string ("SCAN_RESULT") on "CaptureActivity.java", the app close because the app need "back" to the previous activity with this:
getIntent();
I try to modify this codeline, but this not solve my problem.
How can I put the "SCAN_RESULT" in the ActivityQR? I don't know how open other activity (this case ActivityQR) when the code had gottenm and put this String value on the ActivityQR
I Use "CaptureActivity" of ZXing (ZebraCrossing)
Thanks in advance.
SplashScreen.java :
{
Intent mainIntent = new Intent().setClass(SplashScreenActivity.this, com.google.zxing.client.android.CaptureActivity.class);
startActivity(mainIntent)
}
ActivityQR.java
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(REQUEST_CODE == requestCode && RESULT_OK == resultCode){
txResult.setText(data.getStringExtra("SCAN_RESULT"));
}
}
CaptureActivity.java
public class CaptureActivity extends Activity implements SurfaceHolder.Callback {
private static final String TAG = CaptureActivity.class.getSimpleName();
private static final long DEFAULT_INTENT_RESULT_DURATION_MS = 1500L;
private static final long BULK_MODE_SCAN_DELAY_MS = 1000L;
private static final String[] ZXING_URLS = { "http://zxing.appspot.com/scan", "zxing://scan/" };
public static final int HISTORY_REQUEST_CODE = 0x0000bacc;
private static final Collection<ResultMetadataType> DISPLAYABLE_METADATA_TYPES =
EnumSet.of(ResultMetadataType.ISSUE_NUMBER,
ResultMetadataType.SUGGESTED_PRICE,
ResultMetadataType.ERROR_CORRECTION_LEVEL,
ResultMetadataType.POSSIBLE_COUNTRY);
private CameraManager cameraManager;
private CaptureActivityHandler handler;
private Result savedResultToShow;
private ViewfinderView viewfinderView;
private TextView statusView;
private View resultView;
private Result lastResult;
private boolean hasSurface;
private boolean copyToClipboard;
private IntentSource source;
private String sourceUrl;
private ScanFromWebPageManager scanFromWebPageManager;
private Collection<BarcodeFormat> decodeFormats;
private Map<DecodeHintType,?> decodeHints;
private String characterSet;
private HistoryManager historyManager;
private InactivityTimer inactivityTimer;
private BeepManager beepManager;
private AmbientLightManager ambientLightManager;
ViewfinderView getViewfinderView() {
return viewfinderView;
}
public Handler getHandler() {
return handler;
}
CameraManager getCameraManager() {
return cameraManager;
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.capture);
hasSurface = false;
historyManager = new HistoryManager(this);
historyManager.trimHistory();
inactivityTimer = new InactivityTimer(this);
beepManager = new BeepManager(this);
ambientLightManager = new AmbientLightManager(this);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
}
#Override
protected void onResume() {
super.onResume();
// CameraManager must be initialized here, not in onCreate(). This is necessary because we don't
// want to open the camera driver and measure the screen size if we're going to show the help on
// first launch. That led to bugs where the scanning rectangle was the wrong size and partially
// off screen.
cameraManager = new CameraManager(getApplication());
viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
viewfinderView.setCameraManager(cameraManager);
resultView = findViewById(R.id.result_view);
statusView = (TextView) findViewById(R.id.status_view);
handler = null;
lastResult = null;
resetStatusView();
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
SurfaceHolder surfaceHolder = surfaceView.getHolder();
if (hasSurface) {
// The activity was paused but not stopped, so the surface still exists. Therefore
// surfaceCreated() won't be called, so init the camera here.
initCamera(surfaceHolder);
} else {
// Install the callback and wait for surfaceCreated() to init the camera.
surfaceHolder.addCallback(this);
}
beepManager.updatePrefs();
ambientLightManager.start(cameraManager);
inactivityTimer.onResume();
Intent intent = getIntent();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
copyToClipboard = prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true)
&& (intent == null || intent.getBooleanExtra(Intents.Scan.SAVE_HISTORY, true));
source = IntentSource.NONE;
decodeFormats = null;
characterSet = null;
if (intent != null) {
String action = intent.getAction();
String dataString = intent.getDataString();
if (Intents.Scan.ACTION.equals(action)) {
// Scan the formats the intent requested, and return the result to the calling activity.
source = IntentSource.NATIVE_APP_INTENT;
decodeFormats = DecodeFormatManager.parseDecodeFormats(intent);
decodeHints = DecodeHintManager.parseDecodeHints(intent);
if (intent.hasExtra(Intents.Scan.WIDTH) && intent.hasExtra(Intents.Scan.HEIGHT)) {
int width = intent.getIntExtra(Intents.Scan.WIDTH, 0);
int height = intent.getIntExtra(Intents.Scan.HEIGHT, 0);
if (width > 0 && height > 0) {
cameraManager.setManualFramingRect(width, height);
}
}
String customPromptMessage = intent.getStringExtra(Intents.Scan.PROMPT_MESSAGE);
if (customPromptMessage != null) {
statusView.setText(customPromptMessage);
}
} else if (dataString != null &&
dataString.contains("http://www.google") &&
dataString.contains("/m/products/scan")) {
// Scan only products and send the result to mobile Product Search.
source = IntentSource.PRODUCT_SEARCH_LINK;
sourceUrl = dataString;
decodeFormats = DecodeFormatManager.PRODUCT_FORMATS;
} else if (isZXingURL(dataString)) {
// Scan formats requested in query string (all formats if none specified).
// If a return URL is specified, send the results there. Otherwise, handle it ourselves.
source = IntentSource.ZXING_LINK;
sourceUrl = dataString;
Uri inputUri = Uri.parse(dataString);
scanFromWebPageManager = new ScanFromWebPageManager(inputUri);
decodeFormats = DecodeFormatManager.parseDecodeFormats(inputUri);
// Allow a sub-set of the hints to be specified by the caller.
decodeHints = DecodeHintManager.parseDecodeHints(inputUri);
}
characterSet = intent.getStringExtra(Intents.Scan.CHARACTER_SET);
}
}
private static boolean isZXingURL(String dataString) {
if (dataString == null) {
return false;
}
for (String url : ZXING_URLS) {
if (dataString.startsWith(url)) {
return true;
}
}
return false;
}
#Override
protected void onPause() {
if (handler != null) {
handler.quitSynchronously();
handler = null;
}
inactivityTimer.onPause();
ambientLightManager.stop();
cameraManager.closeDriver();
if (!hasSurface) {
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
SurfaceHolder surfaceHolder = surfaceView.getHolder();
surfaceHolder.removeCallback(this);
}
super.onPause();
}
#Override
protected void onDestroy() {
inactivityTimer.shutdown();
super.onDestroy();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (source == IntentSource.NATIVE_APP_INTENT) {
setResult(RESULT_CANCELED);
finish();
return true;
}
if ((source == IntentSource.NONE || source == IntentSource.ZXING_LINK) && lastResult != null) {
restartPreviewAfterDelay(0L);
return true;
}
break;
case KeyEvent.KEYCODE_FOCUS:
case KeyEvent.KEYCODE_CAMERA:
// Handle these events so they don't launch the Camera app
return true;
// Use volume up/down to turn on light
case KeyEvent.KEYCODE_VOLUME_DOWN:
cameraManager.setTorch(false);
return true;
case KeyEvent.KEYCODE_VOLUME_UP:
cameraManager.setTorch(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.capture, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
switch (item.getItemId()) {
case R.id.menu_share:
intent.setClassName(this, ShareActivity.class.getName());
startActivity(intent);
break;
case R.id.menu_history:
intent.setClassName(this, HistoryActivity.class.getName());
startActivityForResult(intent, HISTORY_REQUEST_CODE);
break;
case R.id.menu_settings:
intent.setClassName(this, PreferencesActivity.class.getName());
startActivity(intent);
break;
case R.id.menu_help:
intent.setClassName(this, HelpActivity.class.getName());
startActivity(intent);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode == RESULT_OK) {
if (requestCode == HISTORY_REQUEST_CODE) {
int itemNumber = intent.getIntExtra(Intents.History.ITEM_NUMBER, -1);
if (itemNumber >= 0) {
HistoryItem historyItem = historyManager.buildHistoryItem(itemNumber);
decodeOrStoreSavedBitmap(null, historyItem.getResult());
}
}
}
}
private void decodeOrStoreSavedBitmap(Bitmap bitmap, Result result) {
// Bitmap isn't used yet -- will be used soon
if (handler == null) {
savedResultToShow = result;
} else {
if (result != null) {
savedResultToShow = result;
}
if (savedResultToShow != null) {
Message message = Message.obtain(handler, R.id.decode_succeeded, savedResultToShow);
handler.sendMessage(message);
}
savedResultToShow = null;
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (holder == null) {
Log.e(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!");
}
if (!hasSurface) {
hasSurface = true;
initCamera(holder);
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
hasSurface = false;
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
/**
* A valid barcode has been found, so give an indication of success and show the results.
*
* #param rawResult The contents of the barcode.
* #param scaleFactor amount by which thumbnail was scaled
* #param barcode A greyscale bitmap of the camera data which was decoded.
*/
public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) {
Intent it = getIntent();
it.putExtra("SCAN_RESULT", rawResult.getText());
it.putExtra("SCAN_FORMAT", rawResult.getBarcodeFormat().toString());
setResult(Activity.RESULT_OK, it);
finish();
inactivityTimer.onActivity();
lastResult = rawResult;
ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
boolean fromLiveScan = barcode != null;
if (fromLiveScan) {
historyManager.addHistoryItem(rawResult, resultHandler);
// Then not from history, so beep/vibrate and we have an image to draw on
beepManager.playBeepSoundAndVibrate();
drawResultPoints(barcode, scaleFactor, rawResult);
}
switch (source) {
case NATIVE_APP_INTENT:
case PRODUCT_SEARCH_LINK:
handleDecodeExternally(rawResult, resultHandler, barcode);
break;
case ZXING_LINK:
if (scanFromWebPageManager == null || !scanFromWebPageManager.isScanFromWebPage()) {
handleDecodeInternally(rawResult, resultHandler, barcode);
} else {
handleDecodeExternally(rawResult, resultHandler, barcode);
}
break;
case NONE:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (fromLiveScan && prefs.getBoolean(PreferencesActivity.KEY_BULK_MODE, false)) {
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.msg_bulk_mode_scanned) + " (" + rawResult.getText() + ')',
Toast.LENGTH_SHORT).show();
// Wait a moment or else it will scan the same barcode continuously about 3 times
restartPreviewAfterDelay(BULK_MODE_SCAN_DELAY_MS);
} else {
handleDecodeInternally(rawResult, resultHandler, barcode);
}
break;
}
}
/**
* Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
*
* #param barcode A bitmap of the captured image.
* #param scaleFactor amount by which thumbnail was scaled
* #param rawResult The decoded results which contains the points to draw.
*/
private void drawResultPoints(Bitmap barcode, float scaleFactor, Result rawResult) {
ResultPoint[] points = rawResult.getResultPoints();
if (points != null && points.length > 0) {
Canvas canvas = new Canvas(barcode);
Paint paint = new Paint();
paint.setColor(getResources().getColor(R.color.result_points));
if (points.length == 2) {
paint.setStrokeWidth(4.0f);
drawLine(canvas, paint, points[0], points[1], scaleFactor);
} else if (points.length == 4 &&
(rawResult.getBarcodeFormat() == BarcodeFormat.UPC_A ||
rawResult.getBarcodeFormat() == BarcodeFormat.EAN_13)) {
// Hacky special case -- draw two lines, for the barcode and metadata
drawLine(canvas, paint, points[0], points[1], scaleFactor);
drawLine(canvas, paint, points[2], points[3], scaleFactor);
} else {
paint.setStrokeWidth(10.0f);
for (ResultPoint point : points) {
if (point != null) {
canvas.drawPoint(scaleFactor * point.getX(), scaleFactor * point.getY(), paint);
}
}
}
}
}
private static void drawLine(Canvas canvas, Paint paint, ResultPoint a, ResultPoint b, float scaleFactor) {
if (a != null && b != null) {
canvas.drawLine(scaleFactor * a.getX(),
scaleFactor * a.getY(),
scaleFactor * b.getX(),
scaleFactor * b.getY(),
paint);
}
}
// Put up our own UI for how to handle the decoded contents.
private void handleDecodeInternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {
statusView.setVisibility(View.GONE);
viewfinderView.setVisibility(View.GONE);
resultView.setVisibility(View.VISIBLE);
ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
if (barcode == null) {
barcodeImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(),
R.drawable.launcher_icon));
} else {
barcodeImageView.setImageBitmap(barcode);
}
TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
formatTextView.setText(rawResult.getBarcodeFormat().toString());
TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
typeTextView.setText(resultHandler.getType().toString());
DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
TextView timeTextView = (TextView) findViewById(R.id.time_text_view);
timeTextView.setText(formatter.format(new Date(rawResult.getTimestamp())));
TextView metaTextView = (TextView) findViewById(R.id.meta_text_view);
View metaTextViewLabel = findViewById(R.id.meta_text_view_label);
metaTextView.setVisibility(View.GONE);
metaTextViewLabel.setVisibility(View.GONE);
Map<ResultMetadataType,Object> metadata = rawResult.getResultMetadata();
if (metadata != null) {
StringBuilder metadataText = new StringBuilder(20);
for (Map.Entry<ResultMetadataType,Object> entry : metadata.entrySet()) {
if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) {
metadataText.append(entry.getValue()).append('\n');
}
}
if (metadataText.length() > 0) {
metadataText.setLength(metadataText.length() - 1);
metaTextView.setText(metadataText);
metaTextView.setVisibility(View.VISIBLE);
metaTextViewLabel.setVisibility(View.VISIBLE);
}
}
TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
CharSequence displayContents = resultHandler.getDisplayContents();
contentsTextView.setText(displayContents);
// Crudely scale betweeen 22 and 32 -- bigger font for shorter text
int scaledSize = Math.max(22, 32 - displayContents.length() / 4);
contentsTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize);
TextView supplementTextView = (TextView) findViewById(R.id.contents_supplement_text_view);
supplementTextView.setText("");
supplementTextView.setOnClickListener(null);
if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
PreferencesActivity.KEY_SUPPLEMENTAL, true)) {
SupplementalInfoRetriever.maybeInvokeRetrieval(supplementTextView,
resultHandler.getResult(),
historyManager,
this);
}
int buttonCount = resultHandler.getButtonCount();
ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
buttonView.requestFocus();
for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
TextView button = (TextView) buttonView.getChildAt(x);
if (x < buttonCount) {
button.setVisibility(View.VISIBLE);
button.setText(resultHandler.getButtonText(x));
button.setOnClickListener(new ResultButtonListener(resultHandler, x));
} else {
button.setVisibility(View.GONE);
}
}
if (copyToClipboard && !resultHandler.areContentsSecure()) {
ClipboardInterface.setText(displayContents, this);
}
}
// Briefly show the contents of the barcode, then handle the result outside Barcode Scanner.
private void handleDecodeExternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {
if (barcode != null) {
viewfinderView.drawResultBitmap(barcode);
}
long resultDurationMS;
if (getIntent() == null) {
resultDurationMS = DEFAULT_INTENT_RESULT_DURATION_MS;
} else {
resultDurationMS = getIntent().getLongExtra(Intents.Scan.RESULT_DISPLAY_DURATION_MS,
DEFAULT_INTENT_RESULT_DURATION_MS);
}
if (resultDurationMS > 0) {
String rawResultString = String.valueOf(rawResult);
if (rawResultString.length() > 32) {
rawResultString = rawResultString.substring(0, 32) + " ...";
}
statusView.setText(getString(resultHandler.getDisplayTitle()) + " : " + rawResultString);
}
if (copyToClipboard && !resultHandler.areContentsSecure()) {
CharSequence text = resultHandler.getDisplayContents();
ClipboardInterface.setText(text, this);
}
if (source == IntentSource.NATIVE_APP_INTENT) {
// Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when
// the deprecated intent is retired.
Intent intent = new Intent(getIntent().getAction());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
byte[] rawBytes = rawResult.getRawBytes();
if (rawBytes != null && rawBytes.length > 0) {
intent.putExtra(Intents.Scan.RESULT_BYTES, rawBytes);
}
Map<ResultMetadataType,?> metadata = rawResult.getResultMetadata();
if (metadata != null) {
if (metadata.containsKey(ResultMetadataType.UPC_EAN_EXTENSION)) {
intent.putExtra(Intents.Scan.RESULT_UPC_EAN_EXTENSION,
metadata.get(ResultMetadataType.UPC_EAN_EXTENSION).toString());
}
Number orientation = (Number) metadata.get(ResultMetadataType.ORIENTATION);
if (orientation != null) {
intent.putExtra(Intents.Scan.RESULT_ORIENTATION, orientation.intValue());
}
String ecLevel = (String) metadata.get(ResultMetadataType.ERROR_CORRECTION_LEVEL);
if (ecLevel != null) {
intent.putExtra(Intents.Scan.RESULT_ERROR_CORRECTION_LEVEL, ecLevel);
}
#SuppressWarnings("unchecked")
Iterable<byte[]> byteSegments = (Iterable<byte[]>) metadata.get(ResultMetadataType.BYTE_SEGMENTS);
if (byteSegments != null) {
int i = 0;
for (byte[] byteSegment : byteSegments) {
intent.putExtra(Intents.Scan.RESULT_BYTE_SEGMENTS_PREFIX + i, byteSegment);
i++;
}
}
}
sendReplyMessage(R.id.return_scan_result, intent, resultDurationMS);
} else if (source == IntentSource.PRODUCT_SEARCH_LINK) {
// Reformulate the URL which triggered us into a query, so that the request goes to the same
// TLD as the scan URL.
int end = sourceUrl.lastIndexOf("/scan");
String replyURL = sourceUrl.substring(0, end) + "?q=" + resultHandler.getDisplayContents() + "&source=zxing";
sendReplyMessage(R.id.launch_product_query, replyURL, resultDurationMS);
} else if (source == IntentSource.ZXING_LINK) {
if (scanFromWebPageManager != null && scanFromWebPageManager.isScanFromWebPage()) {
String replyURL = scanFromWebPageManager.buildReplyURL(rawResult, resultHandler);
sendReplyMessage(R.id.launch_product_query, replyURL, resultDurationMS);
}
}
}
private void sendReplyMessage(int id, Object arg, long delayMS) {
if (handler != null) {
Message message = Message.obtain(handler, id, arg);
if (delayMS > 0L) {
handler.sendMessageDelayed(message, delayMS);
} else {
handler.sendMessage(message);
}
}
}
private void initCamera(SurfaceHolder surfaceHolder) {
if (surfaceHolder == null) {
throw new IllegalStateException("No SurfaceHolder provided");
}
if (cameraManager.isOpen()) {
Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?");
return;
}
try {
cameraManager.openDriver(surfaceHolder);
// Creating the handler starts the preview, which can also throw a RuntimeException.
if (handler == null) {
handler = new CaptureActivityHandler(this, decodeFormats, decodeHints, characterSet, cameraManager);
}
decodeOrStoreSavedBitmap(null, null);
} catch (IOException ioe) {
Log.w(TAG, ioe);
displayFrameworkBugMessageAndExit();
} catch (RuntimeException e) {
// Barcode Scanner has seen crashes in the wild of this variety:
// java.?lang.?RuntimeException: Fail to connect to camera service
Log.w(TAG, "Unexpected error initializing camera", e);
displayFrameworkBugMessageAndExit();
}
}
private void displayFrameworkBugMessageAndExit() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.app_name));
builder.setMessage(getString(R.string.msg_camera_framework_bug));
builder.setPositiveButton(R.string.button_ok, new FinishListener(this));
builder.setOnCancelListener(new FinishListener(this));
builder.show();
}
public void restartPreviewAfterDelay(long delayMS) {
if (handler != null) {
handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);
}
resetStatusView();
}
private void resetStatusView() {
resultView.setVisibility(View.GONE);
statusView.setText(R.string.msg_default_status);
statusView.setVisibility(View.VISIBLE);
viewfinderView.setVisibility(View.VISIBLE);
lastResult = null;
}
public void drawViewfinder() {
viewfinderView.drawViewfinder();
}
}
your SplashScreen Java should look like this:
{
Intent mainIntent = new Intent().setClass(SplashScreenActivity.this, com.google.zxing.client.android.CaptureActivity.class);
// use startActivityForResult instead of startActivity
startActivityForResult(mainIntent)
}
but I guess you already solved you problem!