I'm new to android coding practice
ABB20180001
Suppose this as my first id, and i wish to auto-increment this by 1 using shared preferences and use as employee id.
like ABB20180002, ABB20180003, ABB20180004 etc.
I'm new to android coding practice
ABB20180001
Suppose this as my first id, and i wish to auto-increment this by 1 using shared preferences and use as employee id.
like ABB20180002, ABB20180003, ABB20180004 etc.
You can use a specific radix
to parse the number into a long, increment it, and then convert it back to String.
If you're using all letters, then you can use 36
as the radix:
long number = Long.parseLong("ABB20180001", 36);
String incremented = Long.toString(number + 1, 36).toUpperCase();//"ABB20180002"
It's possible that your number is just a hexadecimal number. In that case, you can use 16
as the radix instead of 36
as shown above.
Note that if ABB
is just a prefix, then the above won't work (incrementing by 20 will return ABB2018000L
).
If "ABB"
is just a static prefix, then you can use
//if the prefix changes, a regex will be needed
String incremented = "ABB" + (Long.parseLong(string.replace("ABB", "")) + 1)
And finally, if "ABB"
can change, you can use a regex like this (the example below assumes that prefix is of length 3, change accordingly):
String s = "ABB20180001";
String[] parts = s.split("(?<=[A-Z]{3})"); //split after a sequence of 3 letters
String res = parts[0] + (Long.parseLong(parts[1]) + 1);
You can't increment alphanumeric values directly. if want to do so you need to write some lines of code for it
here is activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:id="@+id/txt_autoincreament"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="click"
android:onClick="Click"/>
</LinearLayout>
here is MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView autoTextIncreament;
String stringValue="ABB";
long intValue=20180001;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
autoTextIncreament = findViewById(R.id.txt_autoincreament);
}
public void Click(View view){
autoTextIncreament.setText(getValue());
}
private String getValue() {
return stringValue+String.valueOf(intValue++);
}
}
hope this will help you.