How to reset AtomicInteger unique Id in Android?
Asked Answered
G

1

4

I want to create a unique Id with reset button. I have a class ViewId.ViewId class contain AtomicInteger. AtomicInteger create unique Id successfully.But I want to reset unique Id using a button.So please help me to reset and create unique id again.

ViewId Class :

import java.util.concurrent.atomic.AtomicInteger;

public class ViewId {

private static ViewId INSTANCE = new ViewId();

private AtomicInteger seq;

private ViewId() {
    seq = new AtomicInteger(0);
}

public int getUniqueId() {
    return seq.incrementAndGet();
}

public static ViewId getInstance() {
    return INSTANCE;
}
}

MainActivity Class :

public class MainActivity extends AppCompatActivity {

EditText editValue;
ViewId viewId = ViewId.getInstance();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    editValue = (EditText)findViewById(R.id.editText);

}

// Increment Button
public void floatIncrement(View view) {
    Log.e("Incremented value is : ", String.valueOf(viewId.getUniqueId()));
}

// Reset Button
public void resetBtn(View view) {
    // reset here
}
}
Gravely answered 3/9, 2015 at 17:9 Comment(3)
where do you want to use this id. I do not see it is used?Ambrosial
@Diyoda I have two buttons 1. floatIncrement, 2. resetBtn. I want to store the id in database when I click the increment button. I show the result in log ..the floatIncrement btn increment the value(ex : 1,2,3,..).When I click resetBtn I want again (1,2,3,...) order ..Gravely
I am glad somebody helped you. I havent had time to look on SO yesterday. Sorry about thatAmbrosial
R
10

Just call seq.set(0), which should just bring your AtomicInteger back to 0.

Raffarty answered 4/9, 2015 at 7:39 Comment(1)
@hipokito I don't know if it would still be helpful, but I would assume that a static code analyzer is flagging it, correct? If so, you can just declare the '0' as a constant, eg. private static final int INITIAL_VAL = 0;Raffarty

© 2022 - 2024 — McMap. All rights reserved.