so i have a button that when i click on, it add a new object to my ArrayList.
private List<Object> addObject = new ArrayList<>();
when i click, it does this
Object object = new object;
object.setTitle("stuff");
object.isLast = false;
addObject.add(object);
This works as it should and then my ArrayList and attached to the adapter...Yada yada yada
At some point in my code, object is going to be true. How i prevent adding to the ArrayList since its the last one.
i tried running a loop
for (int i = 1; i < addObject.size(); i++ {
Object newboject = addObject.get(i);
if(newobject.getIsLast)){
//Then i kinda need to stop adding to the list on further clicks.
}
}
I think the problem may be with how my code is structed, any assistance is appreciated...
it would be better to see your whole code to show you the right places, but the flag-solution by Kevin could look like this:
private boolean isAtEnd = false;
if (object.getIsLast()) {
isAtEnd = true;
}
if (!isAtEnd) {
addobject.add(object);
}
public class TestRing extends Activity
{
boolean isLastObj = false;
Button add;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.testring);
add = (Button) findViewById(R.id.btnAdd);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
if(!isLastObj)
{
for (int i = 1; i < addObject.size(); i++ )
{
Object newboject = addObject.get(i);
newboject.setTitle("stuff");
newboject.isLast = false;
newboject.add(object);
if(newboject.getIsLast)
{
isLastObj = true; // this will prevent furtheradding of objects
}
}
}
}
});
}
}
You can create a fixed-size list from your list that already contains all the items (and the last one) and pass it to the adapter as:
List<Object> finalObjectList = Arrays.asList(addObject);
Please be advised that adding an element to this list will throw an java.lang.UnsupportedOperationException
Logic(Works with Ordered collections only): Check 'isLast' field of the last element in your list.
if(addObject.size() > 0 && !addObject.get(addObject.size()).getIsLast()){
Object object = new object;
object.setTitle("stuff");
object.isLast = false;
addObject.add(object);
}
Though the solution is bit clumsy, but it is a contained logic and won't depend on external flag.
Related
How do I get the first element of an ArrayList from another class and assign it to another ArrayList?
public class PaymentScreenController {
public ListView<Customer> lvCustomer1;
public ArrayList<Customer> allcustomers;
public ArrayList<Customer> cusarray;
private Table tbl = new Table();
#FXML
public void initialize() {
allcustomers = tbl.getCustomers();
// Getting first element from 'allcustomers and assigning it to cusarray?
// I have tried cusarray = allcustomers.get(0) but that doesn't work?
}
}
And then assign cus array to a listview?
Any help would be appreciated thanks
try:
cusarray.add(allcustomers.get(0));
You can initialize the cusarray and add the item to the list:
cusarray = new ArrayList<>();
cusarray.add(allcustomers.get(0);
That should work for you.
Then for the ListView, I guess you'd want something like this:
lvCustomer1 = new ListView(FXCollections.observableArrayList(cusarray));
lvCustomer1.setCellFactory(param -> new ListCell<Customer>() {
#Override
protected void updateItem(Customer item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null || item.<function to get name>() == null) {
setText(null);
} else {
setText(item.<function to get name>());
}
}
});
Though I haven't tested the ListView bit.
EDIT: Now tested the code for the ListView and it works as intended.
I am working on android app and need to define custom buttons.
Initially, I am setting the button to Invisible.
I want to execute a particular method, and check for a String value. If it returns null value, then the button should be still invisible. If it returns some string value, I want to invoke the button and perform some task then.
This is what I tried, but failing.
My app is crashing when the code value returns Null, with error : "attempt to invoke virtual method"
public String code = "";
Button startbtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrieve_visits);
startbtn = findViewById(R.id.videobutton);
startbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//code
}
});
//more code here
}
public void parseData(String response)
{
try {
JSONObject json = new JSONObject(response);
JSONArray data = json.getJSONArray("data");
for (int i = 0; i < data.length(); i++)
{
JSONObject child = data.getJSONObject(i);
code = child.getString("code");
}
if(data.length()==0) ////check for empty array
startbtn.setVisibility(View.INVISIBLE);
else
startbtn.setVisibility(View.VISIBLE);
}
catch (Exception e) {
e.printStackTrace();
}
}
try the code below
if (code != null && !code.equels("")
{
startbtn.setVisibility(View.VISIBLE);
}
else
{
startbtn.setVisibility(View.GONE);
}
startbtn.setOnClickListener(new View.OnClickListener() {
//Required action
}
You can set a button in three ways in android:
1. VISIBLE
2. INVISIBLE
3. GONE
Use button.INVISIBLE to hide button instead of button.GONE as latter one removes button from view instead of hiding. This is the reason you are getting null pointer exception.
You may try the below code:
if (code == null || code.equals("")
{
startbtn.setVisibility(View.INVISIBLE);
}
else
{
startbtn.setVisibility(View.VISIBLE);
}
If the value in code is null or is empty, we set the button to invisible else it will be visible.
I have situation where I have Arraylist, which has name items in it. I need to loop through that namelist which check if the new name that user gave, is already on a list or not. If it is, just give toast to notify user that name is already there, or if it isn't, then add name to the list.
This is what I have:
public class ActivityPlayers extends AppCompatActivity {
public static ArrayList<NameItem> mNameList;
private Button buttonAdd;
private EditText textAdd;
private int checkNumber;
/** When "add" button been clicked... **/
textAdd = findViewById(R.id.name_input);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/** Loop the list **/
for (int i = 0; i < mNameList.size(); i++) {
/** Check if user input match to any name in list
and if it does...**/
if (mNameList.get(i).getText1().equals(textAdd.toString().trim())) {
checkNumber = 1;
break;
} else {
/** If it doesn't **/
checkNumber = 0;
}
}
/** if checkNumber is still 0 **/
if (checkNumber == 0) {
/** Close soft keyboard **/
InputMethodManager input = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
input.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
/** ...add a name to the namelist **/
addItem(0);
} else {
/** if name in a list == name from input, give toast **/
Toast toast = Toast.makeText(getApplicationContext(),
"Name is already on a list", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}
});
Any ideas why this won't work? It only adds the names to the list, even tho it already exists... but it never detects duplicates...
if (mNameList.get(i).getText1().equals(textAdd.toString().trim()))
In the above line of code you compare the ith list element to the string representation of the EditText itself, not to its Text field. Instead of textAdd.toString(), you should use textAdd.getText().
Unrelated to the problem, but I suggest using boolean variables to represent logical flags in your code instead of integer counting.
In the above example, it would go like this:
private boolean nameInList = false;
//...
if (...) {
nameInList = true;
break;
}
//...
if (nameInList) {
//...
} else {
//...
}
Try this:
if (mNameList.get(i).getText1().equalsIgnoreCase(textAdd.getText().toString().trim())) {
checkNumber = 1;
break;
} else {
/** If it doesn't **/
checkNumber = 0;
}
I would advise you to use a suitable data structure Set which disallows duplicate values. You will also have saved your self from loops.
create a set object for example
Set<String> names = new TreeSet(); call the add() which returns true if name doesn't exist in set, else false meaning name exists.
Set<String> names = TreeSet();
boolean isExists = names.add("my name");
if(isExists){ // make you toast here}
I´m trying to use setText method to show all the elements from an ArrayList of Objects into a TextView.
I have 6 buttons in 6 different shelves (A,B,C,D,E,F) with a popup menu each one, where the user chose a cardinal point (N,S,E,W) and after that show the shelve letter and the item clicked in a text view. This is the map:
Here is the code I´m using:
Button buttonA, buttonB, buttonC, buttonD, buttonE, buttonF;
private TextView coordenada_view;
ArrayList<PickUpPoint> pickuppoint_array = new ArrayList<PickUpPoint>();
#Override
protected void onCreate{......
buttonA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final PopupMenu popupMenu = new PopupMenu(Mapa.this, buttonA);
popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
String mShelving = buttonA.getText().toString();
String mCardinalPoint = item.getTitle().toString();
pickuppoint_array.add(new PickUpPoint(mShelving,mCardinalPoint));
PickUpPoint pickUpPoint = new PickUpPoint(mShelving,mCardinalPoint);
//Here I´m trying to show all the elements of the ArrayList into the TextView
for (int i = 0; i < pickuppoint_array.size(); i++){
coordenada_view.setText( pickuppoint_array.get(i).toString());
}
return true;
}
});
popupMenu.show();
buttonB.setOnClickListener....
buttonC.setOnClickListener....
}
This is the class PickUpPoint:
class PickUpPoint {
public String shelving;
public String cardinalPoint;
public String getShelving() {
return shelving;
}
public String getCardinalPoint() {
return cardinalPoint;
}
PickUpPoint(String shelving, String cardinalPoint) {
this.shelving = shelving;
this.cardinalPoint = cardinalPoint;
}
}
But I got this from the array list:
So, my question is...How to get all the elements from the array list like this?
Use this method to set text from Arraylist
Also check if Arraylist is not null and empty
public void setTextViewFromList(ArrayList<PickUpPoint> arraylist, TextView textview) {
//Variable to hold all the values
String output = "";
for (int i = 0; i < arraylist.size(); i++) {
//Append all the values to a string
output += arraylist.get(i).getShelving();//whatever you want to show here like shelving or cordinalpoint use getCordinalPoint()
output += "\n";
}
//Set the textview to the output string
textview.setText(output);
}
USAGE
Call this method like this
setTextViewFromList(pickuppoint_array,coordenada_view)
I assume that the coordenada_view#setTextcan only be called once.
So you need to convert the Elements in pickuppoint_array into a String first
and then supply this to the setText method.
StringBuilder content = new StringBuilder();
for (int i = 0; i < pickuppoint_array.size(); i++) {
content.append(pickuppoint_array.get(i).toString());
content.append('\n');
}
coordenada_view.setText(content.toString());
You also want to implement the toString() method in your PickUpPoint class to return the desired representation of each object, for example:
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("SHELVING ");
builder.append(shelving);
builder.append(" - ");
builder.append(cardinalPoint);
return builder.toString();
}
Ps.:
If you know the expected length of these strings you should supply this as parameter to the StringBuilder constructor, so the jvm does not need to waste time with resizing it.
new StringBuilder(18) might work for the toString method,
and new StringBuilder(19 * pickuppoint_array.size()) might work for the other one.
I know this has got to be simple. But for the life of me i don't know why i can't get this right.
Ok so I want to go from a listview page (got that) then click a switch to make it go to the next page (also got that.) Then I want a int to tell me which position I am on form the last page (might be working?) now i can't get the If Else statement to work in the page.
public class NightmareParts extends Activity
{
public int current_AN_Number = NightmareList.AN_position_num;
private TextView edit_title;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.part_layout);
// isn't working here. Why?
// test_edit = (TextView)findViewById(R.id.directions_tv);
// test_edit.setText(R.string.directions_text_two);
// works without this being in here.
setDoneButtonListener();
}
//Set up the Done button to initialize intent and finish
private void setDoneButtonListener()
{
Button doneButton = (Button) findViewById(R.id.back_button);
doneButton.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick(View v)
{
finish();
}
});
}
private void editTitle()
{
if (current_AN_Number = 1)
{
edit_title = (TextView)findViewById(R.id.part_title);
edit_title.setText(R.string.AN_title_1);
}
}
}
The current_AN_number is coming from the last page.
Your if statement is incorrect:
if (current_AN_Number = 1)
You've used the assignment operator, when you wanted to compare it with the == operator:
if (current_AN_Number == 1)
if (current_AN_Number = 1)
Should be
if (current_AN_Number == 1)
You're not setting current_AN_Number to be 1, you are comparing if it is equal to 1. So use ==.
test_edit = (TextView)findViewById(R.id.directions_tv);
is not working because test_edit is never declared.