I have this array class that is not removing items after re-running my recyclerview - android-studio

The below class is used in an array.
package com.example.ShivitoMGO;
public class RoomTable {
public String RoomName,UpDown,minmaxint;
}
Main Activity
static ArrayList <RoomTable> CountCheck = new ArrayList<>();
public void playerup(View vvv){
st_spinner = v1.findViewById(R.id.spinner);
st_reportLayout = v1.findViewById(R.id.reportlayout);
st_Leanervidimg = v1.findViewById(R.id.Linearvidcopy);
TextView roomname = v1.findViewById(R.id.action_Players1);
RoomTable roomtb = new RoomTable();
if (CountCheck.size() == 0){
//playerupdown = "up";
Toast.makeText(this, "Will notify when " + mRooms.get(position1) + " players increase #" + mRoomSize.get(position1), Toast.LENGTH_LONG).show();
String[] minmaxval = mRoomSize.get(position1).split("/");
CountCheckint = Integer.parseInt(minmaxval[0].trim());
//CountCheck = (String) mRooms.get(position1);
roomtb.RoomName = (String) mRooms.get(position1);
roomtb.minmaxint = minmaxval[0].trim();
roomtb.UpDown = "up";
Log.d("added: ", "it was added");
CountCheck.add(roomtb);
Log.d("RoomTableadd: ",roomtb.RoomName+ " " + roomtb.minmaxint +" " +roomtb.UpDown);
st_reportLayout.setVisibility(View.GONE);
Log.d("Longclickhere: ", mRoomSize.get(position1));
Log.d("RoomNameCount ", String.valueOf(CountCheck.get(0).RoomName));
}else {
int exist1 = 0;
int poss;
for (int i = 0; i < CountCheck.size(); i++) {
if (roomname.getText() == CountCheck.get(i).RoomName) {
Log.d("RoomNametxt: " , CountCheck.get(i).RoomName);
Log.d("RoomNametxt: ", (String) roomname.getText());
Toast.makeText(this, "Notification " + CountCheck.get(i).RoomName + " OFF!", Toast.LENGTH_LONG).show();
Log.d("Removed item: ", String.valueOf(CountCheck.size()));
CountCheck.remove(i);
Log.d("Removed item: ", String.valueOf(CountCheck.size()));
st_reportLayout.setVisibility(View.GONE);
exist1 = 1;
poss = i;
} else {
exist1 = 0;
}
}
if (exist1 == 0) {
Toast.makeText(this, "Will notify when " + mRooms.get(position1) + " players increase #" + mRoomSize.get(position1), Toast.LENGTH_LONG).show();
String[] minmaxval = mRoomSize.get(position1).split("/");
CountCheckint = Integer.parseInt(minmaxval[0].trim());
//CountCheck = (String) mRooms.get(position1);
roomtb.RoomName = (String) mRooms.get(position1);
roomtb.minmaxint = minmaxval[0].trim();
roomtb.UpDown = "up";
Log.d("added: ", "it was added");
CountCheck.add(roomtb);
Log.d("RoomTableadd: ", roomtb.RoomName + " " + roomtb.minmaxint + " " + roomtb.UpDown);
st_reportLayout.setVisibility(View.GONE);
}
Log.d("CountSize: ", String.valueOf(CountCheck.size()));
for (int xb = 0;xb<CountCheck.size();xb++) {
try {
Log.d("RoomNameCount ", String.valueOf(CountCheck.get(xb).RoomName));
} catch (Exception e) {
Log.d("Out of range ", String.valueOf(e));
}
}
}
}
Recycler-View
#Override
public boolean onLongClick(View v) {
// Launch your web intent
if (CountCheck.size() != 0){
Log.d("Longclickhere: ",mRoomSize.get(position));
Toast.makeText(mContext, mRoomSize.get(position), Toast.LENGTH_SHORT).show();
Toast.makeText(mContext, "Will notify when "+mRooms.get(position)+" players decrease", Toast.LENGTH_SHORT).show();
String[] minmaxval = mRoomSize.get(position).split("/");
MainActivity.CountCheckint = Integer.parseInt(minmaxval[0].trim());
} else{
//MainActivity.CountCheck = "";
Toast.makeText(mContext, "Player Decrease notification OFF", Toast.LENGTH_SHORT).show();
}
return true;
In this app the recycler view creates the "rooms" and if the room is selected the textview and 2 other values are put in to the RoomTable. these are stored and used in a service to check if ether of the other to values change. Everything works as intended unless i use the swip-to-refresh witch runs the recycler-view again. If i do not refresh and i select the same item in the recycler-view it will remove it from CountCheck . However if i run the refresh and select the same recycler-view item that i selected previously it will add it instead of removing it. This Makes no since to me because i use a for loop to Check the CountCheck.get(i).RoomName aka the textview and if the names are the same then my if statement will remove instead of add. is it somehow possible i'm ending up with 2 CountCheck Objects????? with the same name???? Please I'm out of ideas on this one. Thanks.

I dont remember why. Maybe someone can explain but i changed this line
if (roomname.getText() == CountCheck.get(i).RoomName)
To this
if (roomname.getText().equals(CountCheck.get(i).RoomName));
and that fixed the issue. please let me know the difference if you are reading this.

Related

Workflow C# string function error in Docusign

I have an code issue in docusign.
In my calculation step I have created and input and output code.
When I run the template and checking the "incoming data" xml in the workflow I have an error message displayed:
<In_80_stackTrace>Exception: at ADEXS.DynamicCode.DynamicClassD_3447d8ccd49f4631b91c31df53e249e7.DynamicMethodD_dcb572b7876d400683579290c5918f06(DynamicContext _context)</In_80_stackTrace>
I don't know how to fix this that it will show only the
logError("In_80_error", "Data node //CategoryName is missing");
when no data is in the node.
Below are the details - my input code:
//In_80 - ESP_CategoryName_Description
string In_80 = "";
{
try
{
if (incomingDataRoot.SelectSingleNode("//CategoryName[node()]").InnerText == null)
{
logError("In_80_error", "Data node //CategoryName is missing");
}
else if (incomingDataRoot.SelectSingleNode("//CategoryName[node()]").InnerText != null)
{
In_80 = incomingDataRoot.SelectSingleNode("//CategoryName[node()]").InnerText;
}
}
catch (Exception e)
{
//logError("In_80_error", "Exception: Message:" + e.Message +" Inner Exception: "+ e.InnerException +" StackTrace: "+ e.StackTrace +" Source: "+ e.Source +" Data: "+ e.Data);
logError("In_80_stackTrace", "Exception: " + e.StackTrace);
}
}
Here is the output code:
//OUT_92 - ESP_CategoryName_Description
var OUT_92 = In_80;
if (In_80 == "")
{
logError("OUT_92_error", "Error reading In_80");
} else {
XmlElement elem = incomingDataRoot.OwnerDocument.CreateElement("OUT_92");
string p_category = "";
int i = 1;
foreach (char item in In_80)
{
if (Char.IsLetter(item))
{
if (i == 1)
{
p_category += item.ToString().ToUpper();
}
else
{
p_category += item.ToString().ToLower();
}
i++;
}
else
{
if (item == ' ')
{
i = 1;
}
p_category += item.ToString();
}
}
OUT_92 = p_category;
elem.InnerText = OUT_92.ToString();
elem.SetAttribute("Name", "ESP_CategoryName_Description");
incomingDataRoot.SelectSingleNode("/Root/Params/TemplateFieldData/Calculation_Results").AppendChild(elem);
}
In incoming data OUT part I'm getting
<OUT_92_error>Error reading In_80</OUT_92_error>
where I assume that its because something is wrong with the input code part?
Thank you for your help!

Accessing Current SharedPreferences Data from Background Services

My app uses a countdown timer in the background in a class that extends Services. The background running service is designed to access the Sharedpreferences data of the app. During the countdown, a particular integer in the Sharedpreferences changes value and the updated value is expected to be accessed in the onFinish() call of the countdown timer. The problem now is that the Service don't read the updated valued from the Sharedpreferences but rather returns the initial value at the point the background service started.
I saw somewhere that the solution to the problem is to use
PreferenceManager.getDefaultSharedPreferences()
instead of getSharedPrefences to be able access the current SharedPreferences value. I implemented this recommendation but the problem persist.
Please somebody should help me out because trying to figure out this is taking too much of my time.
My code is here:
public class BroadcastService extends Service {
DatabaseHelperClass myDatabase = new DatabaseHelperClass(this);
private SharedPreferences defaultSharedPreferences, sharedPreferences, staffSignedIn;
private SharedPreferences.Editor staffEditor, defaultSharedPreferencesEditor;
int countSignIn;
private SimpleDateFormat simpleDateFormatII;
Long timeLeftInMiliseconds;
private final static String TAG = "BroadcastService";
public static final String COUNTDOWN_BR = "com.cenitscitech.www.etimebook.countdown_br";
Intent bi = new Intent(COUNTDOWN_BR);
CountDownTimer cdt = null;
#Override
public void onCreate() {
super.onCreate();
defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
defaultSharedPreferencesEditor = defaultSharedPreferences.edit();
sharedPreferences = getSharedPreferences("setTime", MODE_PRIVATE);
//staffSignedIn = getSharedPreferences("present", MODE_PRIVATE);
//countSignIn = staffSignedIn.getInt("max", 0);
//staffEditor = staffSignedIn.edit();
simpleDateFormatII = new SimpleDateFormat("MMM EEE dd, yyyy HH:mm");
Log.i(TAG, "Starting timer in broadcast receiver...");
Log.i(TAG, "max Count Obtained onBroadcastCreate: "+defaultSharedPreferences.getInt("max", 0));
}
#Override
public void onDestroy() {
//cdt.cancel();
Log.i(TAG, "Timer in broadcast receiver cancelled");
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
timeLeftInMiliseconds = intent.getLongExtra("timeLeft", 0L);
cdt = new CountDownTimer(timeLeftInMiliseconds, 1000) {
#Override
public void onTick(long millisUntilFinished) {
SharedPreferences defaultShared = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);
/*bi.putExtra("countdown", millisUntilFinished);
sendBroadcast(bi);*/
}
#Override
public void onFinish() {
SharedPreferences defaultSharedPreferences2 = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
countSignIn = defaultSharedPreferences2.getInt("max", 0);
Log.i(TAG, "Timer finished");
bi.putExtra("countdown", "Timer finished");
sendBroadcast(bi);
StringBuilder phoneBuilder = new StringBuilder();
Calendar cStart = Calendar.getInstance();
cStart.set(Calendar.HOUR_OF_DAY, 0);
cStart.set(Calendar.MINUTE, 0);
cStart.set(Calendar.SECOND, 0);
Long cStartLong = cStart.getTimeInMillis();
Calendar cEnd = Calendar.getInstance();
cEnd.set(Calendar.HOUR_OF_DAY, 23);
cEnd.set(Calendar.MINUTE, 59);
cEnd.set(Calendar.SECOND, 59);
Long cEndLong = cEnd.getTimeInMillis();
String[] conditionsElements;
Log.i(TAG + " onFinish", "MAXIMUM COUNT OBTAINED: " + defaultSharedPreferences2.getInt("max", 0));
Log.i(TAG + " onFinish", "MAXIMUM COUNT OBTAINED: " + countSignIn);
if (defaultSharedPreferences2.getInt("max", 0) > 0) {
Log.i(TAG + " onFinish", "CURRENT countSignIn Value: "+countSignIn+"\n"+" max Value: "+defaultSharedPreferences2.getInt("max", 0));
conditionsElements = new String[defaultSharedPreferences2.getInt("max", 0)];
for (int i = 1; i <= defaultSharedPreferences2.getInt("max", 0); i++) {
conditionsElements[i - 1] = defaultSharedPreferences2.getString(Integer.toString(i), "NoElement");
Log.i(TAG + " onFinish", "conditionsElement[" + (i - 1) + "] = " + defaultSharedPreferences2.getString(Integer.toString(i), "NoElement"));
if (i < defaultSharedPreferences2.getInt("max", 0)) {
phoneBuilder.append("MOBILE_NUMBER = ? OR ");
Log.i(TAG + " onFinish", "phoneBuilder[" + (i - 1) + "]: " + phoneBuilder);
//phoneBuilder.append(staffSignedIn.getString(Integer.toString(i), "NoStaff")+"_");
} else if (i == defaultSharedPreferences2.getInt("max", 0)) {
//phoneBuilder.append(staffSignedIn.getString(Integer.toString(i), "NoStaff"));
phoneBuilder.append("MOBILE_NUMBER = ?");
Log.i(TAG + " onFinish", "phoneBuilder[final]: " + phoneBuilder);
}
}
} else {
Log.i(TAG + " onFinishInsideElse", "CURRENT countSignIn Value: "+countSignIn+"\n"+" max Value: "+defaultSharedPreferences2.getInt("max", 0));
conditionsElements = new String[1];
conditionsElements[0] = "NoElement";
phoneBuilder.append("MOBILE_NUMBER = ?");
}
Cursor cursor = myDatabase.queryAbsentStaff(SURNAME_COLUMN + ", " + FIRST_NAME_COLUMN + ", " + MIDDLE_NAME_COLUMN + ", " + MOBILE_NUMBER_COLUMN + ", " + DATE_COLUMN,
SURNAME_COLUMN + ", " + FIRST_NAME_COLUMN + ", " + MIDDLE_NAME_COLUMN + ", " + MOBILE_NUMBER_COLUMN + ", " + DATE_COLUMN,
phoneBuilder.toString(),
conditionsElements);
Log.i(TAG + " onFinish", "\n" + "SET TIMES:" + "\n" + cStartLong + "\n" + cEndLong + "\n" + "RETURNED ROWS:" + "\n" + cursor.getCount());
/*staffEditor.putInt("max", 0);
staffEditor.apply();
for(int i=0; i<staffSignedIn.getInt("totalStaff", 100); i++){
staffEditor.putString(Integer.toString((i+1)), "empty").apply();
}*/
if(cursor.moveToFirst()){
for (int i = 0; i < cursor.getCount(); i++) {
if(myDatabase.insertTimeBookRecord(cursor.getString(cursor.getColumnIndex(SURNAME_COLUMN)), cursor.getString(cursor.getColumnIndex(FIRST_NAME_COLUMN)),
cursor.getString(cursor.getColumnIndex(MIDDLE_NAME_COLUMN)), cursor.getString(cursor.getColumnIndex(MOBILE_NUMBER_COLUMN)),
"ABSENT", Long.toString(System.currentTimeMillis()), 1000000L, "NO", "0000", System.currentTimeMillis(), "notSynced", "notSynced")){
cursor.moveToNext();
if(cursor.isAfterLast()){
cursor.close();
}
}else{
cursor.moveToNext();
if(cursor.isAfterLast()){
cursor.close();
}
}
}
}
Log.i(TAG +" onFinish: ", "max val reset: "+defaultSharedPreferences2.getInt("max", 0));

Changing the constraints in a Container object

In Java 8, the Container class has an void add(Component comp, Object constraints) method that adds the component with a constraints information. I want to build a GUI with three panels, where pressing a button would result in switching the constraint information of the components that do not include the button object. How is it possible to switch the constraint information?
EDIT:
I tried the following:
private Map<SpecUITitlePanel, GridBagConstraints> constraints = new Hashtable<SpecUITitlePanel, GridBagConstraints>();
[…]
switchPanelsButton.setText( "Switch panels");
switchPanelsButton.addActionListener( new java.awt.event.ActionListener() {
public void actionPerformed( final java.awt.event.ActionEvent event) {
switchPanelsActionPerformed( event);
}
[…]
private void switchPanelsActionPerformed( final java.awt.event.ActionEvent event) {
boolean swapped = false;
final GridBagLayout layout = (GridBagLayout) getLayout();
final Iterator<SpecUITitlePanel> keysIter = constraints.keySet().iterator();
// summaryPanel, testPanel
while (keysIter.hasNext() && layout != null) {
final SpecUITitlePanel key = keysIter.next();
final String title = key.getTitle();
final Iterator<SpecUITitlePanel> keysIter2 = constraints.keySet().iterator();
while (keysIter2.hasNext()) {
final SpecUITitlePanel key2 = keysIter2.next();
final String title2 = key2.getTitle();
if (!title.equals( title2)) {
if (!title.contains( BUTTON_PANEL_TITLE) && !title2.contains( BUTTON_PANEL_TITLE)) {
// swap components
String message = "component = " + title + ", "
+ constraints.get( key) + "; component2 = " + title2
+ ", " + constraints.get( key2);
System.out.println( message);
final GridBagConstraints value = constraints.get( key);
final GridBagConstraints value2 = constraints.get( key2);
constraints.put(key, value2);
layout.setConstraints( key, value2);
constraints.put(key2, value);
layout.setConstraints( key2, value);
swapped = true;
message = "component = " + title + ", "
+ constraints.get( key) + "; component2 = " + title2
+ ", " + constraints.get( key2);
System.out.println( message);
}
}
}
}
if (swapped) {
repaint();
}
}
The relevant part of the output is
component = Test, java.awt.GridBagConstraints#5179288b; component2 = tna.rads.main_panel.violation_summary_panel, java.awt.GridBagConstraints#f1a7ed2
component = Test, java.awt.GridBagConstraints#f1a7ed2; component2 = tna.rads.main_panel.violation_summary_panel, java.awt.GridBagConstraints#5179288b

How to get an existing MediaContainerModel in hybris?

I tried to get MediaFormatModel, MediaModel, MediaFolderModel etc with the help of MediaService but only the MediaContainer is not possible to get from MediaService and I tried with ModelService. Only one possibility I found that by getting MediaModel we can get the MediaContainerModel but I need to get specific MediaContainerModel by passing qualifier. Like for example:
final MediaModel mm1 = mediaService.getMedia(catalogVersion, "picture515x515");
final MediaFormatModel mf1200 = mediaService.getFormat("1200x1200");
final MediaFolderModel mfm = mediaService.getFolder("convertedimages");
any help?
You can always retrieve models using the flexiblesearh getModelByExample
CatalogVersionModel catalogVersion = catalogVersionService.getCatalogVersion("yourCatalogName", "version");
MediaContainerModel container = new MediaContainerModel();
container.setCatalogVersion(catalogVersion);
container.setQualifier("yourQualifier");
try
{
container = flexibleSearchService.getModelByExample(container);
}//no container found
catch (final ModelNotFoundException ex)
{
...
}
private MediaContainerModel getExistingMediaContainer(CatalogVersionModel catalogVersion, String qualifier) {
final String query = "SELECT {" + MediaContainerModel.PK + "} FROM {" + MediaContainerModel._TYPECODE + "} "
+ "WHERE {" + MediaContainerModel.QUALIFIER + "} = ?qualifier AND " + "{" + MediaContainerModel.CATALOGVERSION + "} = ?catalogVersion";
final FlexibleSearchQuery fQuery = new FlexibleSearchQuery(query);
fQuery.addQueryParameter("qualifier", qualifier);
fQuery.addQueryParameter("catalogVersion", catalogVersion);
final SearchResult<MediaContainerModel> searchResult = flexibleSearchService.search(fQuery);
if (searchResult.getTotalCount() > 0) {
return searchResult.getResult().get(0);
} else {
return null;
}
}
I got the solution we can get as follows
#Autowired
MediaContainerService mediaContainerService;......
MediaContainerModel mediaContainer = null;
try
{
mediaContainer = mediaContainerService.getMediaContainerForQualifier("testContainer");
}
catch (final Exception e)
{
mediaContainer = createMediaContainer("testContainer");
}
mediaContainer.setCatalogVersion(catalogVersion);

How do I make so that when I input a value into a scanner if it is not an integer it won't give me an error?

I am writing a program that does simple math problems. What I am trying to do is to make it so that even if I input a string into the the scanner level it will not give me an error. The level is to choose the difficulty of the math problems. I have tried parseInt, but am at a loss of what to do now.
import java.util.Random;
import java.util.Scanner;
public class Test {
static Scanner keyboard = new Scanner(System.in);
static Random generator = new Random();
public static void main(String[] args) {
String level = intro();//This method intorduces the program,
questions(level);//This does the actual computation.
}
public static String intro() {
System.out.println("HI - I am your friendly arithmetic tutor.");
System.out.print("What is your name? ");
String name = keyboard.nextLine();
System.out.print("What level do you choose? ");
String level = keyboard.nextLine();
System.out.println("OK " + name + ", here are ten exercises for you at the level " + level + ".");
System.out.println("Good luck.");
return level;
}
public static void questions(String level) {
int value = 0, random1 = 0, random2 = 0;
int r = 0, score = 0;
int x = Integer.parseInt("level");
if (x==1) {
r = 4;
}
else if(x==2) {
r = 9;
}
else if(x==3) {
r = 50;
}
for (int i = 0; i<10; i++) {
random1 = generator.nextInt(r);//first random number.
random2 = generator.nextInt(r);//second random number.
System.out.print(random1 + " + " + random2 + " = ");
int ans = keyboard.nextInt();
if((random1 + random2)== ans) {
System.out.println("Your answer is correct!");
score+=1;
}
else if ((random1 + random2)!= ans) {
System.out.println("Your answer is wrong!");
}
}
if (score==10 || score==9) {
if (score==10 && x == 3) {
System.out.println("This system is of no further use.");
}
else {
System.out.println("Choose a higher difficulty");
}
System.out.println("You got " + score + " out or 10");
}
else if (score<=8 && score>=6) {
System.out.println("You got " + score + " out or 10");
System.out.println("Do the test again");
}
else if (score>6) {
System.out.println("You got " + score + " out or 10");
System.out.println("Come back for extra lessons");
}
}
}
The first error I see is that you tried to Integer.parseInt() a String "level" instead of the String variable named level
int x = Integer.parseInt("level");
should be
int x = Integer.parseInt(level);
Also, when defining level you can use keyboard.nextInt instead of keyboard.nextLine
String level = keyboard.nextInt();
Then, you wouldn't have to do an Integer.parseInt() operation later on

Resources