I want my textfield become like this “99999”
this is my code
while (rs.next()){
int s=rs.getInt("Number");
String num1 = String.valueOf(s);
String n = String.format("%05d",num1);
view.txtcustomernumber.setText(n);
}
why my txtcustomernumber(JTextField) always blank
Try this.
while (rs.next()){
int s=rs.getInt("Number");
String n = String.format("%05d",s);
view.txtcustomernumber.setText(n);
}
It might solve your problem.
Related
I am loading a string which contains some number (all in Persian) into an android TextView. Everything was fine until I changed my custom font, numbers of text shown as English number.
Expected : ۱۲۳۴
Received : 1234
I know that my new font support Persian number. When I change the number locale using code below the number shown correctly.
NumberFormat numberFormat = NumberFormat.getInstance(new Locale("fa", "IR"));
String newNumber = numberFormat.format(number);
The problem is I have a string and it's hard to find the numeric part and change it. also my previous font works fine and I can't understand what's the problem with this font.
Any Idea how to globally solve this problem for all textview, or at least for a string?
Try to use this method:
private String setPersianNumbers(String str) {
return str
.replace("0", "۰")
.replace("1", "۱")
.replace("2", "۲")
.replace("3", "۳")
.replace("4", "۴")
.replace("5", "۵")
.replace("6", "۶")
.replace("7", "۷")
.replace("8", "۸")
.replace("9", "۹");
}
You can use this
String NumberString = String.format("%d", NumberInteger);
123 will become ١٢٣
Use this code for show Hegira date in Persian number:
String farsiDate = "1398/11/3";
farsiDate = farsiDate
.replace('0', '٠')
.replace('1', '١')
.replace('2', '٢')
.replace('3', '٣')
.replace('4', '٤')
.replace('5', '٥')
.replace('6', '٦')
.replace('7', '٧')
.replace('8', '٨')
.replace('9', '٩');
dateText.setText(farsiDate);
You'll have to translate it yourself. TextFormat does not automatically translate from arabic digits to any other language's, because that's actually not what people usually want. Each of those digits have their own character codes, a simple walk of the string and replacing them with the appropriate persian code would be sufficient.
private static String[] persianNumbers = new String[]{ "۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹" };
public static String PerisanNumber(String text) {
if (text.length() == 0) {
return "";
}
String out = "";
int length = text.length();
for (int i = 0; i < length; i++) {
char c = text.charAt(i);
if ('0' <= c && c <= '9') {
int number = Integer.parseInt(String.valueOf(c));
out += persianNumbers[number];
} else if (c == '٫') {
out += '،';
} else {
out += c;
}
}
return out;
}}
and after that u can use it like below vlock
TextView textView = findViewById(R.id.text_view);
textView.setText(PersianDigitConverter.PerisanNumber("این یک نمونه است ۱۲ "));
In JS, you can use the function below:
function toPersianDigits(inputValue: any) {
let value = `${inputValue}`;
const charCodeZero = '۰'.charCodeAt(0);
return String(value).replace(/[0-9]/g, w =>
String.fromCharCode(w.charCodeAt(0) + charCodeZero - 48),
);
}
export {toPersianDigits};
I'm creating program like parcel machine. I'm connected to mysql db.
As you can see I have field "final int orderPassword". I would like to generate it automatically by method which I put at the end of this topic.
public static void post() throws Exception{
final int parcelID = 2;
final int clientMPNumber = 777777777;
final int orderPassword = 1234;
try{
Connection con = getConnection();
PreparedStatement posted = con.prepareStatement("INSERT INTO Parcels.Orders (parcelID, clientMPNumber, orderPassword) VALUES ('"+parcelID+"', '"+clientMPNumber+"', '"+orderPassword+"')");
posted.executeUpdate();
}catch(Exception e){System.out.println(e);}
finally{
System.out.println("Insert completed");
}
}
Below is method which I want to put instead of "final int orderPassword".
public static int generatePass(){
Random generator = new Random();
int orderPassword = generator.nextInt(9000)+1000;
return orderPassword;
}
How can I do it?
Given that your method is in the same class oder package, simply change
final int orderPassword = 1234;
to
final int orderPassword = generatePass();
Remark: for better random passwords, you could use some library like https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/RandomStringUtils.html
I suggest to have a more secure password, a String password in particular.
Create an array of char to contain numbers and letters (and special chars optional).
Randomly get -for example- 6 chars from 6 random indices. (Note, it can be any length, not necessarily 6, according to the field size in your DB).
public static String generatePassword(int length){
char source[] = "A0b1C2d3E4f5G6h7I8j9K0l1M2n3O4p5Q6r7S8t9U0v1W2x3Y4z5".toCharArray();
Random generator = new Random();
String password ="";
for(int i=0; i<length; i++){
password += source[generator.nextInt(source.length)];
}
return password;
}
And to use it, you just do:
String orderPassword = generatePassword(6); // of length 6 for example
Output Samples:
36Ynv3
13Kvp5
4A4117
0zlSS3
vr5625
I am working on a school assignment that required us to use SQL statements in Java code as well as use the LIKE operator for a search. In order to properly search I have to get a string from the user, and split the string by any delimiter, and then run the query like so:
SELECT * FROM movies WHERE (movies.title LIKE '%userInput%');
I then return this query in the form of an ArrayList.
Now, when I was testing it out. I originally tested it with no user input, and my query became: SELECT * FROM movies WHERE (movies.title LIKE '%%');. This gave me the correct results.
However when I put a title in there, all of the sudden I get a NullPointerException on this line:
if(title.equals("")) { return "(movies.title LIKE '%%') "; from this section of my code:
public String getSearchString(String title) {
if(title.equals("")) { return "(movies.title LIKE '%%') "; }
String ret = "(";
ArrayList<String> titleArray = Util.splitSearch(title);
for(int i = 0; i < titleArray.size() - 1; ++i) {
String temp = titleArray.get(i);
String stmt = "movies.title LIKE '%" + temp + "%' OR ";
ret += stmt;
}
String temp = "movies.title LIKE '%" + titleArray.get(titleArray.size() - 1) + "%')";
ret += temp;
return ret;
}
This is then called like so:
public List<Movie> listMovies(String title) throws SQLException {
List<Movie> search = new ArrayList<Movie>();
if(null != title && title.isEmpty()) { title = ""; }
ResultSet res = queryMovies(getSearchString(title));
while(res.next()) {
Movie mov = new Movie();
mov.setTitle(res.getString("title"));
search.add(mov);
}
return search;
}
private static queryMovies(String st) throws SQLException {
ResultSet res = null;
try {
PreparedStatement ps = dbcon.prepareStatement(st);
res = ps.executeQuery();
} catch(SQLException e) {
e.printStackTrace();
}
return res;
}
I unfortunately have to do this since I won't know how much a user will enter. And I am also not allowed to use external libraries that make the formatting easier. For reference my Util.splitSearch(...) method looks like this. It should be retrieving anything that is a alphanumeric character and should be splitting on anything that is not alphanumeric:
public static ArrayList<String> splitSearch(String str) {
String[] strArray = str.split("[^a-zA-Z0-9']");
return new ArrayList(Arrays.asList(strArray));
}
What is interesting is when I pass in getSearchString(""); explicitly, I do not get a NullPointerException. It is only when I allows the variable title to be used do I get one. And I still get one when no string is entered.
Am I splitting the String wrong? Am I somehow giving SQL the wrong statement? Any help would be appreciated, as I am very new to this.
the "title" which is passed from input is null, hence you're getting nullpointerexception when you do title.equals("").
Best practices suggest you do a null check like (null != title && title.equals("")).
You can also do "".equals(title)
I have a sqlite databse, with alot of tables. Each table has many rows. In one column I have something like this:
[58458, 65856, 75658, 98456, 98578, ... N]
I made a mistake when created the databse (I don't have acces to the initial data anymore ), what I need is to make these numbers with a punct after the second digit and have something like this:
[58.458, 65.856, 75.658, 98.456, 98.578, ... N]
Is there any way I can do this? I prefer Java. Or is it already any tools that can do this?
Use this function to parse the information from each column.
public static String convertColumn(String textF)
{
String textAux = "";
String newText = "[";
int i = 0;
textF = textF.substring(1, textF.length() - 1);
while(i < textF.length())
{
textAux = textF.substring(i, i + 5);
int nrAux = Integer.parseInt(textAux);
i+=7;
int a;
int b;
a = nrAux / 1000;
b = nrAux - a * 1000;
double newNr;
newNr = a + b * 0.001;
newText = newText + newNr + ", ";
}
newText = newText.substring(0, newText.length() - 2);
newText += "]";
return newText;
}
The function will have as parameter a string like [58458, 65856, 75658, 98456, 98578], which you will get from
the SQL table, and the return value will be [58.458, 65.856, 75.658, 98.456, 98.578] which is the value that you need to update the column with.
For SQL the base idea is this:
UPDATE table
SET column = convertColumn(column);
You can use CAST as REAL on the column, and then update as advised in the other answer.
select CAST(YOUR_COL AS REAL) from YOUR_TABLE
Search for CAST in this doc for more info on it: SQLite language guide
This should work if it's a NUMERIC column:
UPDATE <TABLE NAME> SET <COLUMN> = <COLUMN>/1000;
If it is NOT a NUMERIC or REAL column then this should work:
UPDATE <TABLE NAME> SET <COLUMN> = CAST(<COLUMN> AS REAL)/1000;
(Thanks to Goibniu for the pointer)
So I am trying to get the result as count from a sql query as follows
ResultSet rs = st.executeQuery("SELECT count(employeeID) FROM employee WHERE " +
"employeeID='"+_empID+"' AND password = '"+_password + "'");
so i am also trying to convert that value to int and I tried the follwing
for (; rs.next();) {
val = (Integer) rs.getObject(1);
}
I have also try
val = Integer.parseInt(rs.getObject(1));
but nothing I get the following errors
java.lang.Long cannot be cast to java.lang.Integer
How can I do this.. so if that returns a 0,3 or 4 that it becomes an integer?
Thank you
EDITED TO: (STILL GETTING ERROR)
long countLong = 0;
for (; rs.next();) {
countLong = rs.getLong(1);
}
if(countLong < 1)
{
isAuthentic = false;
}
else
{
isAuthentic = true;
}
A good trick to use when you are not sure about the exact number type is to cast it to the parent class of all numeric type, Number:
val = ((Number) rs.getObject(1)).intValue();
This will work for all numeric types, eg float, long, int etc.
Use ResultSet.getLong method:
long countLong = resultSet.getLong(1);
//if you really want and you are sure that it fits you can now cast
int count = (int)countLong;
Try a getString() and then Long.parseLong().
Cast it to a string and then to an int or long or whatever you want:
Integer.parseInt(rs.getObject(1).toString());