Android app unexpected going back to previous activity - java

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".

Related

my app is crashing when there is no internet and i want my markers or my map to refresh each second

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
}

Check if a property of a custom object ArrayList is an empty string or not?

I want to hide a WebView object (txtCode) if the code property of a custom object Arraylist (arrQues) contains nothing.
if (arrQues.get(count).code.isEmpty())
txtCode.setVisibility(View.GONE);
Its an ArrayList of custom objects fetched from a database table which is shown below
And if the code property does contains code then I have dynamically added rules to layout as shown below:
if (!(arrQues.get(count).code.isEmpty())) {
submit_params.removeRule(RelativeLayout.BELOW);
submit_params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
submit_params.bottomMargin = (int) convertPxToDp(getContext(), convertDpToPx(getContext(), 15));
main_params.addRule(RelativeLayout.ABOVE, submitContainer.getId());
mainContainer.setLayoutParams(main_params);
submitContainer.setLayoutParams(submit_params);
}
The issue is when I load the second question and so on... the layout gets messed up and the current question number does not shows as 2 even if its 2 as shown in below:
Both of these issues only arises whenever I use...
arrQues.get(count).code.isEmpty() in the code
I have also tried using "" instead of isEmpty() and even null, but the result was same.
Also what I have noticed is only those questions are loaded from database which have something in the code column.
Below is the complete code for Java file
public class QuestionsFragment extends Fragment implements View.OnClickListener {
TextView txtTimer, txtStatus;
LinearLayout boxA, boxB, boxC, boxD, mainContainer;
RelativeLayout submitContainer;
RelativeLayout.LayoutParams submit_params;
RelativeLayout.LayoutParams main_params;
ScrollView scrollView;
Button btnSubmit;
DBHelper dbHelper;
SharedPreferences sharedPreferences;
TextView txtQues;
WebView txtCode;
TextView txtOptA, txtOptB, txtOptC, txtOptD;
String ans;
ArrayList<QuestionModal> arrQues = new ArrayList<>();
ArrayList<String> arrAnswers = new ArrayList<>();
CountDownTimer countDownTimer;
boolean timerSwitch;
int selectedVal, id;
int curr_quesNo = 0;
int count = 0;
int right = 0;
int non_attempted = 0;
public QuestionsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_questions, container, false);
txtQues = view.findViewById(R.id.txtQues);
txtOptA = view.findViewById(R.id.txtOptionA);
txtOptB = view.findViewById(R.id.txtOptionB);
txtOptC = view.findViewById(R.id.txtOptionC);
txtOptD = view.findViewById(R.id.txtOptionD);
txtCode = view.findViewById(R.id.txtCode);
txtStatus = view.findViewById(R.id.txtStatus);
boxA = view.findViewById(R.id.boxA);
boxB = view.findViewById(R.id.boxB);
boxC = view.findViewById(R.id.boxC);
boxD = view.findViewById(R.id.boxD);
scrollView = view.findViewById(R.id.scrollView);
btnSubmit = view.findViewById(R.id.btnSubmit);
submitContainer = view.findViewById(R.id.submitContainer);
mainContainer = view.findViewById(R.id.mainContainer);
submit_params = new RelativeLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT);
main_params = new RelativeLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT);
sharedPreferences = getActivity().getSharedPreferences("PrefFile", MODE_PRIVATE);
timerSwitch = sharedPreferences.getBoolean("timer_switch", true);
selectedVal = sharedPreferences.getInt("selectedVal", 10);
dbHelper = DBHelper.getDB(getActivity(), sharedPreferences.getString("db_name", null));
if (!dbHelper.checkDB()) {
dbHelper.createDB(getActivity());
}
dbHelper.openDB();
String levelKey = sharedPreferences.getString("level_key", null);
arrQues = dbHelper.getQues(levelKey, selectedVal);
loadQues(timerSwitch);
txtTimer = view.findViewById(R.id.txtTimer);
switch (sharedPreferences.getString("db_name", null)) {
case "Android":
((MainActivity) getActivity()).setFragTitle("Android Quiz");
// topicLogo.setImageResource(R.drawable.ic_nature_people_black_24dp);
break;
case "Java":
((MainActivity) getActivity()).setFragTitle("Java Quiz");
// topicLogo.setImageResource(R.drawable.ic_nature_people_black_24dp);
break;
case "C":
((MainActivity) getActivity()).setFragTitle("C Quiz");
((MainActivity) getActivity()).setFragLogo(R.drawable.ic_home_black_24dp);
break;
case "C++":
((MainActivity) getActivity()).setFragTitle("C++ Quiz");
break;
case "Python":
((MainActivity) getActivity()).setFragTitle("Python Quiz");
break;
case "Kotlin":
((MainActivity) getActivity()).setFragTitle("Kotlin Quiz");
break;
}
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (timerSwitch)
countDownTimer.cancel();
if (id == 0) {
non_attempted++;
arrAnswers.add("NotAttempted");
Toast.makeText(getActivity(), "Not Attempted!", Toast.LENGTH_SHORT).show();
}
switch (id) {
case R.id.boxA:
arrAnswers.add("A");
break;
case R.id.boxB:
arrAnswers.add("B");
break;
case R.id.boxC:
arrAnswers.add("C");
break;
case R.id.boxD:
arrAnswers.add("D");
break;
}
if ((id == R.id.boxA && ans.equals("A"))
|| (id == R.id.boxB && ans.equals("B"))
|| (id == R.id.boxC && ans.equals("C"))
|| (id == R.id.boxD && ans.equals("D"))) {
right++;
count++;
Toast.makeText(getActivity(), "RIGHT!", Toast.LENGTH_SHORT).show();
if (count < arrQues.size()) {
loadQues(timerSwitch);
} else {
sendResult();
}
} else {
count++;
if (count < arrQues.size()) {
loadQues(timerSwitch);
} else {
sendResult();
}
}
}
});
return view;
}
public void setBtnDefault() {
boxA.setBackgroundColor(getResources().getColor(android.R.color.transparent));
boxB.setBackgroundColor(getResources().getColor(android.R.color.transparent));
boxC.setBackgroundColor(getResources().getColor(android.R.color.transparent));
boxD.setBackgroundColor(getResources().getColor(android.R.color.transparent));
}
public void sendResult() {
int attempted = selectedVal - non_attempted;
Gson gson = new Gson();
String jsonAnswers = gson.toJson(arrAnswers);
String jsonQues = gson.toJson(arrQues);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("right_key", right);
editor.putInt("wrong_key", attempted - right);
editor.putInt("total_key", selectedVal);
editor.putInt("attempted_key", attempted);
editor.putString("arr_answers", jsonAnswers);
editor.putString("arr_ques", jsonQues);
editor.commit();
((MainActivity) getActivity()).AddFrag(new ResultFragment(), 1);
}
public void LoadTimer() {
countDownTimer = new CountDownTimer(60000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
txtTimer.setText("0:" + millisUntilFinished / 1000);
}
#SuppressLint("SetTextI18n")
#Override
public void onFinish() {
txtTimer.setText("Time Over");
}
};
}
#SuppressLint("NewApi")
public void loadQues(boolean timer_switch) {
try {
id = 0;
setBtnDefault();
if (timer_switch) {
LoadTimer();
countDownTimer.start();
}
curr_quesNo++;
txtStatus.setText(curr_quesNo + "/" + selectedVal);
txtOptC.setVisibility(View.VISIBLE);
txtOptD.setVisibility(View.VISIBLE);
txtCode.setVisibility(View.VISIBLE);
main_params.removeRule(RelativeLayout.ABOVE);
submit_params.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
submit_params.addRule(RelativeLayout.BELOW, mainContainer.getId());
submit_params.topMargin = (int) convertPxToDp(getContext(), convertDpToPx(getContext(), 70));
mainContainer.setLayoutParams(main_params);
submitContainer.setLayoutParams(submit_params);
txtQues.setText(arrQues.get(count).ques);
txtOptA.setText(arrQues.get(count).optionA);
txtOptB.setText(arrQues.get(count).optionB);
txtOptC.setText(arrQues.get(count).optionC);
txtOptD.setText(arrQues.get(count).optionD);
txtCode.loadDataWithBaseURL(null, arrQues.get(count).code, "text/html", null, null);
if (txtOptC.getText().toString().isEmpty())
txtOptC.setVisibility(View.GONE);
if (txtOptD.getText().toString().isEmpty())
txtOptD.setVisibility(View.GONE);
if (arrQues.get(count).code.isEmpty())
txtCode.setVisibility(View.GONE);
if (!(arrQues.get(count).code.isEmpty())) {
submit_params.removeRule(RelativeLayout.BELOW);
submit_params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
submit_params.bottomMargin = (int) convertPxToDp(getContext(), convertDpToPx(getContext(), 15));
main_params.addRule(RelativeLayout.ABOVE, submitContainer.getId());
mainContainer.setLayoutParams(main_params);
submitContainer.setLayoutParams(submit_params);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
scrollView.arrowScroll(View.FOCUS_DOWN);
}
}, 1000);
}
ans = arrQues.get(count).answer;
boxA.setOnClickListener(this);
boxB.setOnClickListener(this);
boxC.setOnClickListener(this);
boxD.setOnClickListener(this);
} catch (Exception e) {
((MainActivity) getActivity()).AddFrag(new QuestionsFragment(), 1);
}
}
#Override
public void onClick(View v) {
setBtnDefault();
id = v.getId();
v.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
}
public float convertDpToPx(Context context, float dp) {
return dp * context.getResources().getDisplayMetrics().density;
}
public float convertPxToDp(Context context, float px) {
return px / context.getResources().getDisplayMetrics().density;
}
}
I solved it, all issues were happening because arrQues.get(count).code was fetching null values from the database(The column "Code" had null values). As soon as I replaced null values with empty strings "" isEmpty() worked perfectly. I guess isEmpty() doesn't work with null values and is only intended for empty strings.

duplicate actions in android application when going to home screen

Intro:
My client require some components across the application like navigationDrawer, toolbar. So I have a MainActivity having two toolbar(top/bottom) and two navigation drawer(left/right). All other screens consist of fragments that I change in MainActivity. I have a little problem that is some of the action are being duplicated.
Cases:
In some fragments when user perform an action i.e.
1: User press "Add To Cart" button and press home button that is in toolbar Bottom, the code of "Add To Cart" button run twice (once clicking button, once going to home screen) so my item is being added to cart twice.
2: In another fragment I have "apply coupon" checkbox when user check that checkbox an AlertDialog appear and when user go to home screen the AlertDialog again appear in the home screen.
I'm simply recreating the main activity on home button press with recreate();
I check the code but can't understand why those actions duplicate. If someone faced the same or a bit similar problem please guide me how to tackle that. Any help would be appreciated.
If I need to show code tell me which part?
Edit:
inside onCreateView of fragment Cart Detail
useCoupon.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
createAndShowCustomAlertDialog();
}
}
});
Sequence of this code is Main Activity(Main Fragment)=>Product Frag=>Cart Detail Frag.
Edit 2: MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
this.utils = new Utils(this);
utils.changeLanguage("en");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
this.context = this;
setupToolbar(this);
utils.switchFragment(new MainFrag());
setOnClickListener();
initRightMenuData();
initLeftMenuData();
listAdapter = new ExpandableListAdapter(headerListLeft, hashMapLeft,
false, loggedInIconList);
listViewExpLeft.setAdapter(listAdapter);
if (isLoggedIn()) {
listAdapterRight = new ExpandableListAdapterRight(headerListRight, hashMapRight,
loggedInIconList);
} else {
listAdapterRight = new ExpandableListAdapterRight(headerListRight, hashMapRight,
NotLoggedInIconList);
}
listViewExpRight.setAdapter(listAdapterRight);
enableSingleSelection();
setExpandableListViewClickListener();
setExpandableListViewChildClickListener();
}
private void setOnClickListener() {
myAccountTV.setOnClickListener(this);
checkoutTV.setOnClickListener(this);
discountTV.setOnClickListener(this);
homeTV.setOnClickListener(this);
searchIcon.setOnClickListener(this);
cartLayout.setOnClickListener(this);
}
private void setExpandableListViewClickListener() {
listViewExpRight.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition,
long id) {
utils.printLog("GroupClicked", " Id = " + id);
int childCount = parent.getExpandableListAdapter().getChildrenCount(groupPosition);
if (!isLoggedIn()) {
if (childCount < 1) {
if (groupPosition == 0) {
utils.switchFragment(new FragLogin());
} else if (groupPosition == 1) {
utils.switchFragment(new FragRegister());
} else if (groupPosition == 2) {
utils.switchFragment(new FragContactUs());
} else {
recreate();
}
drawer.closeDrawer(GravityCompat.END);
}
} else {
if (childCount < 1) {
changeFragment(103 + groupPosition);
drawer.closeDrawer(GravityCompat.END);
}
}
return false;
}
});
listViewExpLeft.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
int childCount = parent.getExpandableListAdapter().getChildrenCount(groupPosition);
if (childCount < 1) {
MenuCategory textChild = (MenuCategory) parent.getExpandableListAdapter()
.getGroup(groupPosition);
moveToProductFragment(textChild.getMenuCategoryId());
utils.printLog("InsideChildClick", "" + textChild.getMenuCategoryId());
}
return false;
}
});
}
private void setExpandableListViewChildClickListener() {
listViewExpLeft.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
int childPosition, long id) {
MenuSubCategory subCategory = (MenuSubCategory) parent.getExpandableListAdapter()
.getChild(groupPosition, childPosition);
moveToProductFragment(subCategory.getMenuSubCategoryId());
utils.printLog("InsideChildClick", "" + subCategory.getMenuSubCategoryId());
return true;
}
});
listViewExpRight.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
String str = parent.getExpandableListAdapter().getGroup(groupPosition).toString();
UserSubMenu userSubMenu = (UserSubMenu) parent.getExpandableListAdapter()
.getChild(groupPosition, childPosition);
if (str.contains("Information") || str.contains("معلومات")) {
Bundle bundle = new Bundle();
bundle.putString("id", userSubMenu.getUserSubMenuCode());
utils.switchFragment(new FragShowText(), bundle);
} else if (str.contains("اللغة") || str.contains("Language")) {
recreate();
} else if (str.contains("دقة") || str.contains("Currency")) {
makeDefaultCurrencyCall(userSubMenu.getUserSubMenuCode());
}
utils.printLog("InsideChildClick", "" + userSubMenu.getUserSubMenuCode());
drawer.closeDrawer(GravityCompat.END);
return false;
}
});
}
private void setupToolbar(Context context) {
ViewCompat.setLayoutDirection(appbarBottom, ViewCompat.LAYOUT_DIRECTION_RTL);
ViewCompat.setLayoutDirection(appbarTop, ViewCompat.LAYOUT_DIRECTION_RTL);
String imgPath = Preferences
.getSharedPreferenceString(appContext, LOGO_KEY, DEFAULT_STRING_VAL);
utils.printLog("Product Image = " + imgPath);
if (!imgPath.isEmpty()) {
Picasso.with(getApplicationContext()).load(imgPath)
.into(logoIcon);
}
logoIcon.setOnClickListener(this);
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
actionbarToggle();
drawer.addDrawerListener(mDrawerToggle);
drawerIconLeft.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
drawer.openDrawer(GravityCompat.START);
drawerIconLeft.setScaleX(1);
drawerIconLeft.setImageResource(R.drawable.ic_arrow_back_black);
}
}
});
drawerIconRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawer(GravityCompat.END);
} else {
drawer.openDrawer(GravityCompat.END);
}
}
});
}
private void initViews() {
drawerIconLeft = findViewById(R.id.drawer_icon_left);
drawerIconRight = findViewById(R.id.drawer_icon_right);
logoIcon = findViewById(R.id.logo_icon);
searchIcon = findViewById(R.id.search_icon);
cartLayout = findViewById(R.id.cart_layout);
counterTV = findViewById(R.id.actionbar_notification_tv);
drawer = findViewById(R.id.drawer_layout);
listViewExpLeft = findViewById(R.id.expandable_lv_left);
listViewExpRight = findViewById(R.id.expandable_lv_right);
appbarBottom = findViewById(R.id.appbar_bottom);
appbarTop = findViewById(R.id.appbar_top);
myAccountTV = findViewById(R.id.my_account_tv);
discountTV = findViewById(R.id.disc_tv);
checkoutTV = findViewById(R.id.checkout_tv);
homeTV = findViewById(R.id.home_tv);
searchView = findViewById(R.id.search_view);
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawer(GravityCompat.END);
} else {
super.onBackPressed();
}
}
private void initRightMenuData() {
headerListRight = new ArrayList<>();
hashMapRight = new HashMap<>();
String[] notLoggedInMenu = {findStringByName("login_text"),
findStringByName("action_register_text"),
findStringByName("contact_us_text")};
String[] loggedInMenu = {findStringByName("account"), findStringByName("edit_account_text"),
findStringByName("action_change_pass_text"),
findStringByName("order_history_text"),
findStringByName("logout"), findStringByName("contact_us_text")};
List<UserSubMenu> userSubMenusList = new ArrayList<>();
if (isLoggedIn()) {
for (int i = 0; i < loggedInMenu.length; i++) {
headerListRight.add(loggedInMenu[i]);
hashMapRight.put(headerListRight.get(i), userSubMenusList);
}
} else {
for (int i = 0; i < notLoggedInMenu.length; i++) {
headerListRight.add(notLoggedInMenu[i]);
hashMapRight.put(headerListRight.get(i), userSubMenusList);
}
}
String responseStr = "";
if (getIntent().hasExtra(KEY_EXTRA)) {
responseStr = getIntent().getStringExtra(KEY_EXTRA);
utils.printLog("ResponseInInitData", responseStr);
try {
JSONObject responseObject = new JSONObject(responseStr);
boolean success = responseObject.optBoolean("success");
if (success) {
try {
JSONObject homeObject = responseObject.getJSONObject("home");
JSONArray slideshow = homeObject.optJSONArray("slideshow");
AppConstants.setSlideshowExtra(slideshow.toString());
JSONArray menuRight = homeObject.optJSONArray("usermenu");
for (int z = 0; z < menuRight.length(); z++) {
List<UserSubMenu> userSubMenuList = new ArrayList<>();
JSONObject object = menuRight.getJSONObject(z);
headerListRight.add(object.optString("name"));
JSONArray childArray = object.optJSONArray("children");
for (int y = 0; y < childArray.length(); y++) {
JSONObject obj = childArray.optJSONObject(y);
userSubMenuList.add(new UserSubMenu(obj.optString("code"),
obj.optString("title"), obj.optString("symbol_left"),
obj.optString("symbol_right")));
}
hashMapRight.put(headerListRight.get(headerListRight.size() - 1), userSubMenuList);
utils.printLog("AfterHashMap", "" + hashMapRight.size());
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
utils.showErrorDialog("Error Getting Data From Server");
utils.printLog("SuccessFalse", "Within getCategories");
}
} catch (JSONException e) {
e.printStackTrace();
utils.printLog("JSONObjEx_MainAct", responseStr);
}
} else {
utils.printLog("ResponseExMainActivity", responseStr);
throw new IllegalArgumentException("Activity cannot find extras " + KEY_EXTRA);
}
}
private void initLeftMenuData() {
headerListLeft = new ArrayList<>();
hashMapLeft = new HashMap<>();
String responseStr = "";
if (getIntent().hasExtra(KEY_EXTRA)) {
responseStr = getIntent().getStringExtra(KEY_EXTRA);
utils.printLog("ResponseInMainActivity", responseStr);
try {
JSONObject responseObject = new JSONObject(responseStr);
utils.printLog("JSON_Response", "" + responseObject);
boolean success = responseObject.optBoolean("success");
if (success) {
try {
JSONObject homeObject = responseObject.getJSONObject("home");
JSONArray menuCategories = homeObject.optJSONArray("categoryMenu");
utils.printLog("Categories", menuCategories.toString());
for (int i = 0; i < menuCategories.length(); i++) {
JSONObject menuCategoryObj = menuCategories.getJSONObject(i);
JSONArray menuSubCategoryArray = menuCategoryObj.optJSONArray(
"children");
List<MenuSubCategory> childMenuList = new ArrayList<>();
for (int j = 0; j < menuSubCategoryArray.length(); j++) {
JSONObject menuSubCategoryObj = menuSubCategoryArray.getJSONObject(j);
MenuSubCategory menuSubCategory = new MenuSubCategory(
menuSubCategoryObj.optString("child_id"),
menuSubCategoryObj.optString("name"));
childMenuList.add(menuSubCategory);
}
MenuCategory menuCategory = new MenuCategory(menuCategoryObj.optString(
"category_id"), menuCategoryObj.optString("name"),
menuCategoryObj.optString("icon"), childMenuList);
headerListLeft.add(menuCategory);
hashMapLeft.put(headerListLeft.get(i), menuCategory.getMenuSubCategory());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
utils.printLog("ResponseExMainActivity", responseStr);
throw new IllegalArgumentException("Activity cannot find extras " + KEY_EXTRA);
}
}
private void actionbarToggle() {
mDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawer,
R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
drawerIconLeft.setImageResource(R.drawable.ic_list_black);
drawerIconLeft.setScaleX(-1);
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
}
#Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.logo_icon) {
recreate();
} else if (id == R.id.my_account_tv) {
utils.switchFragment(new Dashboard());
} else if (id == R.id.disc_tv) {
utils.printLog("From = Main Act");
Bundle bundle = new Bundle();
bundle.putString("from", "mainActivity");
utils.switchFragment(new FragProduct(), bundle);
} else if (id == R.id.checkout_tv) {
if (isLoggedIn()) {
utils.switchFragment(new FragCheckout());
} else {
AlertDialog alertDialog = utils.showAlertDialogReturnDialog("Continue As",
"Select the appropriate option");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE,
"As Guest", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
utils.switchFragment(new FragCheckout());
}
});
alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
"Login", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
utils.switchFragment(new FragLogin());
}
});
alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL,
"Register", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
utils.switchFragment(new FragRegister());
}
});
alertDialog.show();
}
} else if (id == R.id.home_tv) {
recreate();
} else if (id == R.id.search_icon) {
startActivityForResult(new Intent(context, SearchActivity.class), SEARCH_REQUEST_CODE);
} else if (id == R.id.cart_layout) {
Bundle bundle = new Bundle();
bundle.putString("midFix", "cartProducts");
utils.switchFragment(new FragCartDetail(), bundle);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SEARCH_REQUEST_CODE || requestCode == CURRENCY_REQUEST_CODE
|| requestCode == LANGUAGE_REQUEST_CODE) {
if (data != null) {
String responseStr = data.getStringExtra("result");
utils.printLog("ResponseIs = " + responseStr);
if (responseStr != null) {
if (resultCode == Activity.RESULT_OK) {
JSONObject response;
if (!isJSONString(responseStr)) {
try {
response = new JSONObject(responseStr);
if (requestCode == CURRENCY_REQUEST_CODE) {
JSONObject object = response.optJSONObject("currency");
Preferences.setSharedPreferenceString(appContext
, CURRENCY_SYMBOL_KEY
, object.optString("symbol_left")
+ object.optString("symbol_right")
);
recreate();
} else if (requestCode == LANGUAGE_REQUEST_CODE) {
JSONObject object = response.optJSONObject("language");
Preferences.setSharedPreferenceString(appContext
, LANGUAGE_KEY
, object.optString("code")
);
recreate();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
if (requestCode == SEARCH_REQUEST_CODE) {
if (responseStr.isEmpty())
return;
Bundle bundle = new Bundle();
bundle.putString("id", responseStr);
bundle.putString("from", "fromSearch");
utils.switchFragment(new FragProduct(), bundle);
} else {
utils.showAlertDialog("Alert", responseStr);
}
}
} else if (resultCode == FORCED_CANCEL) {
utils.printLog("WithinSearchResult", "If Success False" + responseStr);
} else if (resultCode == Activity.RESULT_CANCELED) {
utils.printLog("WithinSearchResult", "Result Cancel" + responseStr);
}
}
}
}
}
}
MainFragment
public class MainFrag extends MyBaseFragment {
public MainFrag() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_main, container, false);
initUtils();
initViews(view);
utils.setupSlider(mPager, indicator, pb, true, true);
RecyclerView.LayoutManager mLayoutManager =
new LinearLayoutManager(getActivity()
, LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(mLayoutManager);
List<String> keysList = prepareData();
if (keysList.size() > 0 && !keysList.isEmpty()) {
mRecyclerView.setAdapter(new MainFragmentAdapter(keysList));
}
return view;
}
private void initViews(View view) {
mRecyclerView = view.findViewById(R.id.parent_recycler_view);
mPager = view.findViewById(R.id.pager);
indicator = view.findViewById(R.id.indicator);
pb = view.findViewById(R.id.loading);
}
private List<String> prepareData() {
String responseStr = getHomeExtra();
List<String> keysStr = new ArrayList<>();
try {
JSONObject responseObject = new JSONObject(responseStr);
utils.printLog("JSON_Response", "" + responseObject);
boolean success = responseObject.optBoolean("success");
if (success) {
JSONObject homeObject = responseObject.optJSONObject("home");
JSONObject modules = homeObject.optJSONObject("modules");
Iterator<?> keys = modules.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
keysStr.add(key);
utils.printLog("KeyStr", key);
}
utils.printLog("ModuleSize", modules.toString());
} else {
utils.printLog("SuccessFalse", "Within getCategories");
}
} catch (JSONException e) {
e.printStackTrace();
utils.printLog("JSONEx_MainFragTest", responseStr);
}
return keysStr;
}
}
I removed global variables and some method because of length.
You should not use recreate() method here, as it forces the activity to reload everything. Just use intent to call your Home activity, that should solve this issue.
From the hint of #Akash Khatri I use to switch to mainFragment and its fine now. Actually #Akash is right recreate(); everything at present But as I was setting main fragment in OnCreate of MainActivity. So, It was hard to notice that Android first recreate everything and in no time It call the main Fragment.
I do not using Intent to start the same activity again Because Switching fragment is more convenient. And also I pass Some extras to it that I will loose With new Intent.

Android setOnDragListener shows error

I am developing an android app of screen lock. I have used broadcast receiver for screen. In my app I want to use drag and drop. So, when I am using setOnDragListener,it shows an error
java.lang.RuntimeException: Error receiving broadcast Intent {
act=init view flg=0x10 } in
com.app.lockscreenlibrary.LockBroadcastReceiver#f22ed7d.
And the library file reference is https://github.com/find-happiness/LockScreen
when i am using drop.setOnDragListener(new View.OnDragListener() { in LockView.java file . Then the error may occur. I want to get the dragged item value. (Here is my item is btn0 and the drag portion is bottomlinear)
My code is LockView.java:
public class LockView extends FrameLayout {
public LinearLayout drop;
TextView text, sucess;
int total, failure = 0;
ImageView viewDrop;
private GestureDetector gestureDetector;
private Context mContext;
Button btnUnlock;
Button btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0, btnH, btnS;
Button buttonB;
private int CLICK_ACTION_THRESHHOLD = 200;
private float startX;
private float startY;
int nums[] = new int[4];
int position = 0;
ImageView imageView1, imageView2, imageView3, imageView4;
public LockView(Context context) {
this(context, null);
}
public LockView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public LockView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(final Context context) {
mContext = context;
View view = inflate(context, R.layout.activity_screen_lock, null);
gestureDetector = new GestureDetector(context, new SingleTapConfirm());
drop = (LinearLayout) findViewById(R.id.bottomlinear);
sucess = (TextView) findViewById(R.id.Sucess);
drop.setOnDragListener(new View.OnDragListener() {
#Override
public boolean onDrag(View v, DragEvent event) {
final int action = event.getAction();
switch(action) {
case DragEvent.ACTION_DRAG_STARTED:
break;
case DragEvent.ACTION_DRAG_EXITED:
break;
case DragEvent.ACTION_DRAG_ENTERED:
break;
case DragEvent.ACTION_DROP:{
failure = failure+1;
return(true);
}
case DragEvent.ACTION_DRAG_ENDED:{
total = total +1;
int suc = total - failure;
sucess.setText("Sucessful Drops :"+suc);
text.setText("Total Drops: "+total);
return(true);
}
default:
break;
}
return true;
}
});
btnUnlock = (Button) view.findViewById(R.id.unlock);
btnUnlock.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LockHelper.getLockLayer().unlock();
}
});
btn0 = (Button) view.findViewById(R.id.btn0);
btn1 = (Button) view.findViewById(R.id.btn1);
btn2 = (Button) view.findViewById(R.id.btn2);
btn3 = (Button) view.findViewById(R.id.btn3);
btn4 = (Button) view.findViewById(R.id.btn4);
btn5 = (Button) view.findViewById(R.id.btn5);
btn6 = (Button) view.findViewById(R.id.btn6);
btn7 = (Button) view.findViewById(R.id.btn7);
btn8 = (Button) view.findViewById(R.id.btn8);
btn9 = (Button) view.findViewById(R.id.btn9);
btnH = (Button) view.findViewById(R.id.btnH);
btnS = (Button) view.findViewById(R.id.btnS);
imageView1 = (ImageView) view.findViewById(R.id.imageView);
imageView2 = (ImageView) view.findViewById(R.id.imageView2);
imageView3 = (ImageView) view.findViewById(R.id.imageView3);
imageView4 = (ImageView) view.findViewById(R.id.imageView4);
buttonB = (Button) view.findViewById(R.id.buttonB);
btn0.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (position > -1 && position < 4) {
nums[position] = 0;
}
setPosition(position);
}
});
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (position > -1 && position < 4) {
nums[position] = 2;
}
setPosition(position);
}
});
btn3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (position > -1 && position < 4) {
nums[position] = 3;
}
setPosition(position);
}
});
btn4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (position > -1 && position < 4) {
nums[position] = 4;
}
setPosition(position);
}
});
btn5.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (position > -1 && position < 4) {
nums[position] = 5;
}
setPosition(position);
}
});
btn6.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (position > -1 && position < 4) {
nums[position] = 6;
}
setPosition(position);
}
});
btn7.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (position > -1 && position < 4) {
nums[position] = 7;
}
setPosition(position);
}
});
btn8.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (position > -1 && position < 4) {
nums[position] = 8;
}
setPosition(position);
}
});
btn9.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (position > -1 && position < 4) {
nums[position] = 9;
}
setPosition(position);
}
});
btn1.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent arg1) {
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder shadow = new View.DragShadowBuilder(btn1);
v.startDrag(data, shadow, v, 0);
Log.d("LOGTAG", "onTouch");
return true;
}
});
if (position == 3) {
checkSpeedDial();
} else if (position == 2) {
checkSpeedDial();
} else if (position == 1) {
checkSpeedDial();
} else if (position == 0) {
checkSpeedDial();
} else if (position == -1) {
checkSpeedDial();
}
buttonB.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (position == 1) {
imageView1.setImageResource(0);
position--;
Log.d("LOGTAG", "clicked1 : position =" + position);
} else if (position == 2) {
imageView2.setImageResource(0);
position--;
Log.d("LOGTAG", "clicked2 : position =" + position);
} else if (position == 3) {
imageView3.setImageResource(0);
position--;
Log.d("LOGTAG", "clicked3 : position =" + position);
} else if (position == 4) {
imageView4.setImageResource(0);
position--;
Log.d("LOGTAG", "clicked4 : position =" + position);
} else {
}
}
});
if (position > 3) {
checkPassword();
}
addView(view);
}
private void setPosition(int pos) {
if (pos == 0) {
imageView1.setImageResource(R.drawable.lock_circle);
position++;
} else if (pos == 1) {
imageView2.setImageResource(R.drawable.lock_circle);
position++;
} else if (pos == 2) {
imageView3.setImageResource(R.drawable.lock_circle);
position++;
} else if (pos == 3) {
imageView4.setImageResource(R.drawable.lock_circle);
position++;
checkPassword();
} else {
}
}
public void showLockHome() {
}
private void checkSpeedDial() {
Log.d("LOGTAG", position + " ::" + nums[0] + " 2: " + nums[1] + " 3: " + nums[2] + " 4: " + nums[3]);
}
public void checkPassword() {
Log.d("LOGTAG", "1 :" + nums[0] + " 2: " + nums[1] + " 3: " + nums[2] + " 4: " + nums[3]);
int pas[] = new int[4];
pas[0] = 1;
pas[1] = 1;
pas[2] = 1;
pas[3] = 1;
if (Arrays.equals(nums, pas)) {
LockHelper.getLockLayer().unlock();
} else {
Log.d("LOGTAG", "Wrong Password");
}
}
private class SingleTapConfirm extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onSingleTapUp(MotionEvent event) {
Log.d("LockView", "clicked1");
return true;
}
}
private boolean isAClick(float startX, float endX, float startY, float endY) {
float differenceX = Math.abs(startX - endX);
float differenceY = Math.abs(startY - endY);
if (differenceX > CLICK_ACTION_THRESHHOLD/* =5 */ || differenceY > CLICK_ACTION_THRESHHOLD) {
return false;
}
return true;
}
}
LockHelper.java
public enum LockHelper implements SwipeEvent {
INSTANCE;
private static Context mContext;
private final int UNLOCK = 830;
private final int UNLOCK_WITH_PASSWORD = 831;
private final int SWITCH_TO_GUEST = 345;
public static final String INIT_VIEW_FILTER = "init view";
public static final String START_SUPERVISE = "start supervise";
public static final String STOP_SUPERVISE = "stop supervise";
public static final String SHOW_SCREEN_LOCKER = "show screen locker";
private static LockView mLockView;
private static LockLayer mLockLayer;
public void initialize(Context context) {
initContextViewAndLayer(context);
loadLockView(context);
}
public static LockView getLockView() {
if (mLockView == null)
throw new NullPointerException("init first");
return mLockView;
}
public static LockLayer getLockLayer() {
if (mLockLayer == null)
throw new NullPointerException("init first");
return mLockLayer;
}
public void initLockViewInBackground(final Context context) {
if (context == null)
throw new NullPointerException("context == null, assign first");
if (mLockView == null || mLockLayer == null)
initContextViewAndLayer(context);
}
public void initContextViewAndLayer(Context context) {
if (mContext == null)
synchronized (this) {
if (mContext == null)
mContext = context;
}
//init layout view
if (mLockView == null)
synchronized (this) {
if (mLockView == null)
mLockView = new LockView(context);
}
if (mLockLayer == null)
synchronized (this) {
if (mLockLayer == null)
mLockLayer = LockLayer.getInstance(context, mLockView);
}
}
private volatile boolean mIsInitialized = false;
public void loadLockView(Context context) {
mLockView.showLockHome();
if( !mIsInitialized){
mIsInitialized = true;
}
mLockLayer.lock();
showLockLayer();
}
private Handler mHandler = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UNLOCK:
unlock();
break;
case UNLOCK_WITH_PASSWORD:
if (!(msg.obj instanceof String)) break;
String password = (String) msg.obj;
switchUserIfExistOrAlertUser(password);
break;
default:
break;
}
}
};
private void unlock() {
mLockLayer.unlock();
mContext.sendBroadcast(new Intent(LockHelper.STOP_SUPERVISE));
mContext.sendBroadcast(new Intent(CoreIntent.ACTION_SCREEN_LOCKER_UNLOCK));
}
private void switchUserIfExistOrAlertUser(String password) {
if (TextUtils.isEmpty(password)) {
wrong();
return;
}
if (!password.equals("1234")) {
wrong();
return;
}
unlockScreenAndResetPinCode();
}
private void unlockScreenAndResetPinCode() {
unlock();
}
private void wrong() { }
public static final String INTENT_KEY_WITH_SECURE = "with_secure";
#Override
public <S, T> void onSwipe(S s, T t) {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
LockHelper.INSTANCE.getLockLayer().removeLockView();
}
}, 1000);
}
private void triggerCameraWithSecure(Context context, boolean withSecure) { }
private void showLockLayer() {
mLockView.showLockHome();
mLockLayer.bringBackLockView();
}
public void vibrate(long milliseconds) {
if (mContext == null) return;
Vibrator v = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(milliseconds == 0 ? 500 : milliseconds);
}
}
LockBroadcastReceiver.java
final public class LockBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = LockBroadcastReceiver.class.getSimpleName();
private volatile boolean bInterruptSupervisor = false;
private ScheduledThreadPoolExecutor mExecutor;
private FutureRunnable mSupervisorRunnable;
private static final int SCHEDULE_TASK_NUMBER = 3;
private PhoneStateChange mPhoneStateChangeCallback;
public void assignPhoneStateChangeCallback(PhoneStateChange phoneStateChangeCallback) {
mPhoneStateChangeCallback = phoneStateChangeCallback;
}
#Override
public void onReceive(Context context, Intent intent) {
String mAction = intent.getAction();
switch (mAction) {
case LockHelper.INIT_VIEW_FILTER:
LockHelper.INSTANCE.initLockViewInBackground(context);
break;
case Intent.ACTION_SCREEN_ON:
refreshBatteryInfo();
bringLockViewBackTopIfNot();
break;
case CoreIntent.ACTION_SCREEN_LOCKER_UNLOCK:
shutdownScheduleExecutor();
break;
case LockHelper.START_SUPERVISE:
bInterruptSupervisor = false;
supervise(context.getApplicationContext());
break;
case LockHelper.STOP_SUPERVISE:
bInterruptSupervisor = true;
break;
case LockHelper.SHOW_SCREEN_LOCKER:
//DU.sd("broadcast", "locker received");
case Intent.ACTION_SCREEN_OFF:
LockHelper.INSTANCE.initialize(context);
LockHelper.INSTANCE.getLockLayer().lock();
bInterruptSupervisor = true;
break;
case Intent.ACTION_POWER_CONNECTED:
//LockHelper.INSTANCE.getLockView().batteryChargingAnim();
break;
case Intent.ACTION_POWER_DISCONNECTED:
//LockHelper.INSTANCE.getLockView().batteryChargingAnim();
break;
case Intent.ACTION_SHUTDOWN:
break;
case "android.intent.action.PHONE_STATE":
TelephonyManager tm =
(TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
switch (tm.getCallState()) {
case TelephonyManager.CALL_STATE_RINGING:
mPhoneStateChangeCallback.ringing();
Log.i(TAG, "RINGING :" + intent.getStringExtra("incoming_number"));
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
mPhoneStateChangeCallback.offHook();
//DU.sd(TAG, "off hook");
break;
case TelephonyManager.CALL_STATE_IDLE:
mPhoneStateChangeCallback.idle();
Log.i(TAG, "incoming IDLE");
break;
}
break;
default:
break;
}
}
abstract class FutureRunnable implements Runnable {
private Future<?> future;
public Future<?> getFuture() {
return future;
}
public void setFuture(Future<?> future) {
this.future = future;
}
}
public void supervise(final Context context) {
initScheduleExecutor();
if (mSupervisorRunnable == null) {
mSupervisorRunnable = new FutureRunnable() {
public void run() {
if (bInterruptSupervisor) getFuture().cancel(true);
boolean cameraRunning = false;
Camera _camera = null;
try {
_camera = Camera.open();
cameraRunning = _camera == null;
} catch (Exception e) {
cameraRunning = true;
} finally {
if (_camera != null) {
_camera.release();
getFuture().cancel(true);
context.sendBroadcast(new Intent(LockHelper.SHOW_SCREEN_LOCKER));
}
}
if (!cameraRunning)
context.sendBroadcast(new Intent(LockHelper.SHOW_SCREEN_LOCKER));
}
};
}
Future<?> future = mExecutor.scheduleAtFixedRate(mSupervisorRunnable, 2000, 500, TimeUnit.MILLISECONDS);
mSupervisorRunnable.setFuture(future);
}
private void bringLockViewBackTopIfNot() {
initScheduleExecutor();
mExecutor.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
LockHelper.INSTANCE.getLockLayer().requestFullScreen();
}
}, 1000, 1000, TimeUnit.MILLISECONDS);
}
private void refreshBatteryInfo() {
initScheduleExecutor();
mExecutor.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
//LockHelper.INSTANCE.getLockView().refreshBattery();
}
}, 2, 2, TimeUnit.MINUTES);
}
private void initScheduleExecutor() {
if (mExecutor == null) {
synchronized (this) {
if (mExecutor == null)
mExecutor = new ScheduledThreadPoolExecutor(SCHEDULE_TASK_NUMBER);
}
}
}
public synchronized void shutdownScheduleExecutor() {
if (mExecutor == null) return;
mExecutor.shutdown();
mExecutor = null;
}
}
activity_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:patternview="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_screen_lock"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="1"
android:layout_height="wrap_content"
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:minWidth="10dp"/>
<LinearLayout
android:id="#+id/bottomlinear"
android:gravity="center"
android:background="#00ffff"
android:orientation="vertical"
android:layout_marginTop="50dp"
android:layout_height="75dp"
android:layout_width="75dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Sucess"
android:textSize="20sp" />
</LinearLayout>
</RelativeLayout>
The error shows :
E/AndroidRuntime: FATAL EXCEPTION: main Process:
com.yudong.fitnewdome, PID: 8020 java.lang.RuntimeException: Error
receiving broadcast Intent { act=init view flg=0x10 } in
com.happiness.lockscreenlibrary.LockBroadcastReceiver#f22ed7d at
android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:880)
at android.os.Handler.handleCallback(Handler.java:739) at
android.os.Handler.dispatchMessage(Handler.java:95) at
android.os.Looper.loop(Looper.java:135) at
android.app.ActivityThread.main(ActivityThread.java:5312) at
java.lang.reflect.Method.invoke(Native Method) at
java.lang.reflect.Method.invoke(Method.java:372) at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:90
1) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Caused by: java.lang.ClassCastException:
com.happiness.lockscreenlibrary.LockScreenService cannot be cast to
android.view.View$OnDragListener at
com.happiness.lockscreenlibrary.view.LockView.init(LockView.java:89)
at com.happiness.lockscreenlibrary.view.LockView.(LockView.java:73)
at com.happiness.lockscreenlibrary.view.LockView.(LockView.java:0) at
com.happiness.lockscreenlibrary.view.LockView.(LockView.java:0) at
com.happiness.lockscreenlibrary.util.LockHelper.initContextViewAndLayer(LockH
elper.java:82) at
com.happiness.lockscreenlibrary.util.LockHelper.initLockViewInBackground(Lock
Helper.java:68) at
com.happiness.lockscreenlibrary.LockBroadcastReceiver.onReceive(LockBroadcast
Receiver.java:55) at
android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:870)
at android.os.Handler.handleCallback(Handler.java:739) at
android.os.Handler.dispatchMessage(Handler.java:95) at
android.os.Looper.loop(Looper.java:135) at
android.app.ActivityThread.main(ActivityThread.java:5312) at
java.lang.reflect.Method.invoke(Native Method) at
java.lang.reflect.Method.invoke(Method.java:372)
How to solve the issue please help me.
The fix is to use:
drop = (LinearLayout) view.findViewById(R.id.bottomlinear);
instead of:
drop = (LinearLayout) findViewById(R.id.bottomlinear);

Fatal runtime error at android.media.audiofx.Equalizer.<init>

I am working on equalier app and no errors in code at all. when I run app on phone it force closes, I logcat and this is result
03-22 02:49:17.945: E/AndroidRuntime(4318): at android.media.audiofx.Equalizer.<init>(Equalizer.java:149)
03-22 02:50:34.796: E/AndroidRuntime(4423): at android.media.audiofx.Equalizer.<init>(Equalizer.java:149)
I tried on android gingerbread kitkat and jellybean
this is the main activity code:
public class MainActivity extends Activity
implements SeekBar.OnSeekBarChangeListener,
CompoundButton.OnCheckedChangeListener,
View.OnClickListener
{
//as usual "define variables"
TextView bass_boost_label = null;
SeekBar bass_boost = null;
CheckBox enabled = null;
Button flat = null;
Button Button1;
Equalizer eq = null;
BassBoost bb = null;
int min_level = 0;
int max_level = 100;
static final int MAX_SLIDERS = 8; // Must match the XML layout
SeekBar sliders[] = new SeekBar[MAX_SLIDERS];
TextView slider_labels[] = new TextView[MAX_SLIDERS];
int num_sliders = 0;
/*=============================================================================
onCreate
=============================================================================*/
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
/*=============================================================================
onCreate
=============================================================================*/
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//initalize layout
setContentView(R.layout.activity_main);
//initialize the checkbox
enabled = (CheckBox)findViewById(R.id.enabled);
enabled.setOnCheckedChangeListener (this);
//initialize flat button
flat = (Button)findViewById(R.id.flat);
flat.setOnClickListener(this);
Button1 = (Button)findViewById(R.id.button1);
Button1.setOnClickListener(this);
//the seekbars
bass_boost = (SeekBar)findViewById(R.id.bass_boost);
bass_boost.setOnSeekBarChangeListener(this);
bass_boost_label = (TextView) findViewById (R.id.bass_boost_label);
sliders[0] = (SeekBar)findViewById(R.id.slider_1);
slider_labels[0] = (TextView)findViewById(R.id.slider_label_1);
sliders[1] = (SeekBar)findViewById(R.id.slider_2);
slider_labels[1] = (TextView)findViewById(R.id.slider_label_2);
sliders[2] = (SeekBar)findViewById(R.id.slider_3);
slider_labels[2] = (TextView)findViewById(R.id.slider_label_3);
sliders[3] = (SeekBar)findViewById(R.id.slider_4);
slider_labels[3] = (TextView)findViewById(R.id.slider_label_4);
sliders[4] = (SeekBar)findViewById(R.id.slider_5);
slider_labels[4] = (TextView)findViewById(R.id.slider_label_5);
sliders[5] = (SeekBar)findViewById(R.id.slider_6);
slider_labels[5] = (TextView)findViewById(R.id.slider_label_6);
sliders[6] = (SeekBar)findViewById(R.id.slider_7);
slider_labels[6] = (TextView)findViewById(R.id.slider_label_7);
sliders[7] = (SeekBar)findViewById(R.id.slider_8);
slider_labels[7] = (TextView)findViewById(R.id.slider_label_8);
//define equilizer
eq = new Equalizer (0, 0);
if (eq != null)
{
eq.setEnabled (true);
int num_bands = eq.getNumberOfBands();
num_sliders = num_bands;
short r[] = eq.getBandLevelRange();
min_level = r[0];
max_level = r[1];
for (int i = 0; i < num_sliders && i < MAX_SLIDERS; i++)
{
int[] freq_range = eq.getBandFreqRange((short)i);
sliders[i].setOnSeekBarChangeListener(this);
slider_labels[i].setText (formatBandLabel (freq_range));
}
}
for (int i = num_sliders ; i < MAX_SLIDERS; i++)
{
sliders[i].setVisibility(View.GONE);
slider_labels[i].setVisibility(View.GONE);
}
bb = new BassBoost (0, 0);
if (bb != null)
{
}
else
{
bass_boost.setVisibility(View.GONE);
bass_boost_label.setVisibility(View.GONE);
}
updateUI();
}
/*=============================================================================
onProgressChanged
=============================================================================*/
#Override
public void onProgressChanged (SeekBar seekBar, int level,
boolean fromTouch)
{
if (seekBar == bass_boost)
{
bb.setEnabled (level > 0 ? true : false);
bb.setStrength ((short)level); // Already in the right range 0-1000
}
else if (eq != null)
{
int new_level = min_level + (max_level - min_level) * level / 100;
for (int i = 0; i < num_sliders; i++)
{
if (sliders[i] == seekBar)
{
eq.setBandLevel ((short)i, (short)new_level);
break;
}
}
}
}
/*=============================================================================
onStartTrackingTouch
=============================================================================*/
#Override
public void onStartTrackingTouch(SeekBar seekBar)
{
}
/*=============================================================================
onStopTrackingTouch
=============================================================================*/
#Override
public void onStopTrackingTouch(SeekBar seekBar)
{
}
/*=============================================================================
formatBandLabel
=============================================================================*/
public String formatBandLabel (int[] band)
{
return milliHzToString(band[0]) + "-" + milliHzToString(band[1]);
}
/*=============================================================================
milliHzToString
=============================================================================*/
public String milliHzToString (int milliHz)
{
if (milliHz < 1000) return "";
if (milliHz < 1000000)
return "" + (milliHz / 1000) + "Hz";
else
return "" + (milliHz / 1000000) + "kHz";
}
/*=============================================================================
updateSliders
=============================================================================*/
public void updateSliders ()
{
for (int i = 0; i < num_sliders; i++)
{
int level;
if (eq != null)
level = eq.getBandLevel ((short)i);
else
level = 0;
int pos = 100 * level / (max_level - min_level) + 50;
sliders[i].setProgress (pos);
}
}
/*=============================================================================
updateBassBoost
=============================================================================*/
public void updateBassBoost ()
{
if (bb != null)
bass_boost.setProgress (bb.getRoundedStrength());
else
bass_boost.setProgress (0);
}
/*=============================================================================
onCheckedChange
=============================================================================*/
#Override
public void onCheckedChanged (CompoundButton view, boolean isChecked)
{
if (view == (View) enabled)
{
eq.setEnabled (isChecked);
}
}
/*=============================================================================
onClick
=============================================================================*/
#Override
public void onClick (View view)
{
if (view == (View) flat)
{
setFlat();
}
if (view == (View) Button1)
{
Intent myIntent = new Intent(MainActivity.this, Guide.class);
MainActivity.this.startActivity(myIntent);
}
}
/*=============================================================================
updateUI
=============================================================================*/
public void updateUI ()
{
updateSliders();
updateBassBoost();
enabled.setChecked (eq.getEnabled());
}
/*=============================================================================
setFlat
=============================================================================*/
public void setFlat ()
{
if (eq != null)
{
for (int i = 0; i < num_sliders; i++)
{
eq.setBandLevel ((short)i, (short)0);
}
}
if (bb != null)
{
bb.setEnabled (false);
bb.setStrength ((short)0);
}
updateUI();
}
/*=============================================================================
showAbout
=============================================================================*/
public void showAbout ()
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("About Simple EQ");
alertDialogBuilder.setMessage(R.string.copyright_message);
alertDialogBuilder.setCancelable(true);
alertDialogBuilder.setPositiveButton (R.string.ok,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
}
});
AlertDialog ad = alertDialogBuilder.create();
ad.show();
}
/*=============================================================================
onOptionsItemSelected
=============================================================================*/
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.about:
showAbout();
return true;
}
return super.onOptionsItemSelected(item);
}
}

Categories