Application Stop when input editText more than 10 digit - java

i am trying to show calculation textView(txtHasil) it is running but when input more than 10 application suddenly force close. this is my code:
btnHitung.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//String plafond = NumberTextWatcherForThousand.trimCommaOfString(edtPlafond.getText().toString());
String plafond = edtPlafond.getText().toString().trim();
String jasa = edtJasa.getText().toString().trim();
int edtPlafond = Integer.parseInt(plafond);
float edtJasa = Float.parseFloat(jasa);
double hasil = (edtPlafond * edtJasa )/100;
txtHasil.setText(""+hasil+"\nplafond: "+edtPlafond+"\nJasa: "+edtJasa);
//txtHasil.addTextChangedListener(new NumberTextWatcherForThousand((EditText) txtHasil));
}
}
i have been try change int,float, and double. i have been read this link: This program doesn't work properly for decimals more than 10 digits? but didn't help. any suggest will be help. thanks

Integer.parseInt(plafond);
This is the problem.It can not parse anythong larger than Integer.MAX_VALUE
int edtPlafond;
try {
edtPlafond = Integer.parseInt(plafond);
} catch (NumberFormatException e ) {
e.printStackTrace();
// add proper error handling
}
The best would be to have a longer value - long...
long edtPlafond;
try {
edtPlafond = Long.parseLong(plafond);
} catch (NumberFormatException e ) {
e.printStackTrace();
// add proper error handling
}
And an example of handling the error in a better way, by displaying the error in a dialog:
} catch (NumberFormatException e ) {
new AlertDialog.Builder(getActivity())
.setTitle("Error: incorrect number entered!")
.setMessage("The exact error is: " + e.getMessage())
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int b) {
dialog.cancel();
}
});
.create()
.show();
}
Note: all conversions need such a treatment...

Related

The program closes after executing the loop on Thread [duplicate]

This question already has answers here:
Android update TextView in Thread and Runnable
(4 answers)
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 11 months ago.
Error only when i use editText.setText(sbz); What to do? Without Thread, setText works good
public void onstart(View view) {
setContentView(R.layout.activity_main);
EditText editText = (EditText)findViewById(R.id.result);
Toast.makeText(this, "LOG FINISH!", Toast.LENGTH_SHORT).show();
String str = new String((String) textView1.getText());
StringBuilder sbz = new StringBuilder();
new Thread(() -> {
int x = 0;
while(x<100) {
x++;
sbz.append(str);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
editText.setText(sbz);
}).start();
Try stringBuffer instead of stringbuilder. Stringbuilder is not syncronized.
editText.setText from your Thread is trying to modify an android view from a background thread, this is a forbidden action. You should only modify android views from the UI/Main thread. In your example, you can try posting it to the UI thread
public void onstart(View view) {
setContentView(R.layout.activity_main);
EditText editText = (EditText)findViewById(R.id.result);
Toast.makeText(this, "LOG FINISH!", Toast.LENGTH_SHORT).show();
String str = new String((String) textView1.getText());
StringBuilder sbz = new StringBuilder();
new Thread(() -> {
int x = 0;
while(x<100) {
x++;
sbz.append(str);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
editText.post(() -> {
editText.setText(sbz)
});
}).start();

NumberFormatException For Input String "4018.B"

The following code comes from a Android App for Handheld Scanner Device; the Device should scan different Barcodes and QR codes, different digit ranges, numbers and digits;
that´s why I decided to go with .matcher instead of Regular Expressions; The following code works fine when it comes to parse combinations like "1367+700" etc.:
editBarcode.setOnClickListener(new View.OnClickListener() { //tv is the TextView.
public void onClick(View v) {
code = editBarcode.getText().toString();
XXXStorageApp.getInstance().setScannedCode(code);
editBarcode.setText("");
if (ScanService.checkEnteredCode(code, basic, content, MainDetailActivity.this) == true) {
return;
}
else {
Pattern p = Pattern.compile(code);
Matcher matcher = p.matcher(Pattern.quote("\\+"));
if (matcher.find()){
retrievedItemNo = String.valueOf(matcher);
}
String intermediateItemNo = code;
String[] splitString = intermediateItemNo.split(Pattern.quote("+"));
retrievedItemNo = splitString [0];
String intermediateString = code.substring(code.indexOf("+") + 1);
retrievedQuantity = intermediateString.split("\\+")[0];
if(XXXStorageApp.getInstance().NoList.contains(retrievedItemNo) || XXXStorageApp.getInstance().EanList.contains(scannedCode)){
Log.d(String.valueOf(XXXStorageApp.getInstance().NoList),"NoList");
Log.d(String.valueOf(XXXStorageApp.getInstance().EanList),"EanList");
}
else {
Log.d(String.valueOf(XXXStorageApp.getInstance().NoList),"NoList");
Log.d(String.valueOf(XXXStorageApp.getInstance().EanList),"EanList");
Vibrator vibrator;
vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(3000);
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
Toast.makeText(getApplicationContext(), R.string.not_in_database, Toast.LENGTH_LONG).show();
return;
}
if (!addBooking.isEnabled() == true && removeBooking.isEnabled())
{
AddBookingMessage message = new AddBookingMessage();
message.setType("add-item-to-pallet");
message.setPalNo(receivedPalNo);
message.setItem(retrievedItemNo);
if (String.valueOf(retrievedQuantity).matches("") ||
retrievedQuantity == null ||
retrievedQuantity.trim().isEmpty()) {
final Dialog dialog = new Dialog(MainDetailActivity.this, 0);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setContentView(R.layout.sortiment_layout);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
TextView textView = dialog.findViewById(R.id.textView4);
Button okButton = dialog.findViewById(R.id.ok);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
retrievedQuantity = textView.getText().toString();
message.setQuantity(Integer.valueOf(retrievedQuantity));
message.setSource(source);
message.setTime(time);
RestClient.putBookingOnPallet(basic, message, MainDetailActivity.this);
dialog.dismiss();
}
});
Button cancelButton = dialog.findViewById(R.id.cancel);
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
else
{
message.setQuantity(Integer.valueOf(retrievedQuantity));
message.setSource(source);
message.setTime(time);
RestClient.putBookingOnPallet(basic, message, MainDetailActivity.this);
}
}
if (addBooking.isEnabled() && !removeBooking.isEnabled() == true)
{
AddBookingMessage message = new AddBookingMessage();
message.setType("remove-item-from-pallet");
message.setPalNo(receivedPalNo);
message.setItem(retrievedItemNo);
message.setEan(scannedCode);
if (spinner != null && spinner.getSelectedItem() != null) {
source = spinner.getSelectedItem().toString();
}
if (String.valueOf(retrievedQuantity).matches("") || retrievedQuantity == null
|| retrievedQuantity.trim().isEmpty())
{
final Dialog enterDialog = new Dialog(MainDetailActivity.this, 0);
enterDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
enterDialog.setCancelable(true);
enterDialog.setContentView(R.layout.sortiment_layout);
enterDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
TextView enterQuantityView = enterDialog.findViewById(R.id.textView4);
Button okQuantityButton = enterDialog.findViewById(R.id.ok);
okQuantityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
retrievedQuantity = enterQuantityView.getText().toString();
message.setQuantity(Integer.valueOf(retrievedQuantity));
message.setSource(source);
message.setTime(time);
RestClient.removeItemFromPallet(basic, message, MainDetailActivity.this);
enterDialog.dismiss();
}
});
Button cancelQuantityButton = enterDialog.findViewById(R.id.cancel);
cancelQuantityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
enterDialog.dismiss();
}
});
enterDialog.show();
}
else {
message.setQuantity(Integer.valueOf(retrievedQuantity));
message.setSource(source);
message.setTime(time);
RestClient.removeItemFromPallet(basic, message, MainDetailActivity.this);
}
}
editBarcode.setText("");
}}
however the App crashes with a
java.lang.NumberFormatException: For input string: "4018.B"
So, the problem here is to parse a string like "4018.B+95".
I don´t know how to handle this mixed input String with .matcher and definitely don´t want to use a Regular Expression; so basically, all of the following Input Strings - including Type conversion - should be handled correctly:
1256+70
1235.B+70
1256+70+DB
1235.B+70+DB
1256+70+DB2020-123
1235.B+70+DB2020-123
1256+0+DB2020-123
1235.B+0+DB2020-123
So, basically I need a condition for .matcher() that handles input like
"1235.B"
a mixed Integer and String; I need to store it in one variable which is of type String;
the problem here is that the "." in "1235.B" is not recognized and the App crashes hence, because the Number contains a string (".B")
So, two questions here:
How can I use .matcher() to recognize if a String contains ".B" or ".C" or anything similar?
How do I handle the different Types correctly in one Variable type?
As I am stuck with this, I would appreciate any hints or help.

Send string from thread bluetooth service to textView in main activity

I want to send value from string (distance to obstacle) to my TextView in main activity.
I tried to use Handler, but still not working (crash) or receive nothing.
A part code which receive data from HC-05 (screen where you see in debug value assignet to variable)
enter image description here
#Override
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while(true){
try {
bytes = inputStream.read(buffer);
final String comingMsg = new String(buffer,0,bytes);
Log.d(TAG,"InputStream: " + comingMsg);
/*mHandler2.post(new Runnable() {
#Override
public void run() {
Message message = new Message();
message.obj = comingMsg;
mHandler2.sendMessage(message);
}
});*/
}catch (IOException e){
Log.e(TAG,"Write: Error reading input." + e.getMessage());
active=false;
break;
}
}
}
Here It's parts of code from MainActivity where I tried put something to get values from service.
[I add, that for this moment i want to see something values from bluetooth in textView. Later I want to create parse string and send custom text to custom TextView - example: FL: (Front Left)- to one textView, FR: (Front Right) - to second textView]
There is method implementThreads(), because I wanted to do 6 Threads to 6 TextView which every time is refreshing value from string in Services (there I tried get value from Bluetooth Service)
Log.d(TAG,"Check intent - result");
if(getIntent().getIntExtra("result",0)==RESULT_OK){
mDevice = getIntent().getExtras().getParcelable("bonded device");
myBluetoothService = new MyBluetoothService(getApplicationContext());
startConnection(mDevice,MY_UUID);
Log.d(TAG,"Check is active service");
checkIfActive();
}
Log.d(TAG,"Check intent - connect_to_paired");
if(getIntent().getIntExtra("connect_to_paired",0)==RESULT_OK){
mDevice = getIntent().getExtras().getParcelable("bonded_paired_device");
myBluetoothService = new MyBluetoothService(getApplicationContext());
startConnection(mDevice,MY_UUID);
Log.d(TAG,"Check is active service");
checkIfActive();
}
}
#Override
public void onStart(){
super.onStart();
myBluetoothService = new MyBluetoothService(getApplicationContext());
}
public void checkIfActive(){
Log.d(TAG,"CheckIfActive: Started");
if(myBluetoothService.active){
Log.d(TAG,"CheckIfActive: Running method implementThreads()");
implementThreads();
}
}
public void implementThreads(){
Log.d(TAG,"ImplementThreads: Started");
Thread thread = new Thread(){
#Override
public void run() {
try{
sleep(100);
}catch (InterruptedException e){
e.printStackTrace();
}
}
};
thread.start();
}
public void startConnection(BluetoothDevice device,UUID uuid){
Log.d(TAG,"StartConnection: Initializing connection");
myBluetoothService.startClient(device,uuid);
}
Thanks all for help, because It's very important for me !
Use this to interect with UI Thread for operations like updating textviews etc.
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
//YOUR CODE HERE
Message message = new Message();
message.obj = comingMsg;
mHandler2.sendMessage(message);
}
});

Cancel an operation on Toast

I wrote a JSoup HTML scraping class for my Android project. This custom class puts the user-inputted zip code into the constructor, and would parse that HTML. It works in an asynchronous thread from my main thread. Since there is no right way to deal with incorrect zip codes, I had check for null in a particular element, specifically:
if(doc.select("div.columns").first().text() == null)
{
((Activity) context).runOnUiThread(new Runnable() {
public void run()
{
Toast toast = Toast.makeText(context, R.string.toast_parse_fail, Toast.LENGTH_LONG);
toast.show();
return;
}
});
}
If that particular element is null (meaning that no such data exists for this zip code), it would create a toast to the user. As to why try wouldn't work in this case, it is because JSoup and Java doesn't know whether the parse failed or not, since the web page still loads fine; only, there is no data, which would crash the app from a NullPointerException from the code following it.
Despite my Toast exception handling using .runOnUiThread, my app would still crash. Is there any particular methods that would cancel the operations that follow my null-checking method? I know I am crashing because Toast is not cancelling my operations, and is preceding to execute the following code which causes my NullPointerExceptions.
Posted is my full Pollen constructor.
public Pollen(int zipcode, final Context context)
{
this.context = context;
this.zipcode = zipcode;
Document doc;
try
{
// pass address to Wunderground's website using our inputted zipcode
doc = Jsoup.connect("http://www.wunderground.com/DisplayPollen.asp?Zipcode=" + this.zipcode).get();
if(doc.select("div.columns").first().text() == null)
{
((Activity) context).runOnUiThread(new Runnable() {
public void run()
{
Toast toast = Toast.makeText(context, R.string.toast_parse_fail, Toast.LENGTH_LONG);
toast.show();
return;
}
});
}
// get "location" from XML
Element location = doc.select("div.columns").first();
this.location = location.text();
// get "pollen type" from XML
Element pollenType = doc.select("div.panel h3").first();
this.pollenType = pollenType.text();
SimpleDateFormat format = new SimpleDateFormat("EEE MMMM dd, yyyy");
// add the four items of pollen and dates
// to its respective list
for(int i = 0; i < 4; i++)
{
Element dates = doc.select("td.text-center.even-four").get(i);
Element levels = doc.select("td.levels").get(i);
try
{
pollenMap.put(format.parse(dates.text()), levels.text());
}
catch (ParseException e)
{
((Activity) context).runOnUiThread(new Runnable() {
public void run()
{
Toast toast = Toast.makeText(context, R.string.toast_parse_fail, Toast.LENGTH_LONG);
toast.show();
return;
}
});
}
}
}
catch (IOException e)
{
((Activity) context).runOnUiThread(new Runnable() {
public void run()
{
Toast toast = Toast.makeText(context, R.string.toast_parse_fail, Toast.LENGTH_LONG);
toast.show();
return;
}
});
}
}
tl;dr I still want the Toast to show - but I want on-Toast, to cancel all operations that follow it, since I know that if this particular Toast shows, if the code following it executes, it would crash the app.
Since you already in a try-catch-block, can't you just throw an exception?
public Pollen(int zipcode, final Context context) {
this.context = context;
this.zipcode = zipcode;
Document doc;
try {
// pass address to Wunderground's website using our inputted zipcode
doc = Jsoup.connect("http://www.wunderground.com/DisplayPollen.asp?Zipcode=" + this.zipcode).get();
if(doc.select("div.columns").first().text() == null) {
// Oh no! div.colums is empty. Lets throw an exception, which
// will prevent the code below from executing.
throw new IllegalStateException("div.columns is NULL");
}
// get "location" from XML
Element location = doc.select("div.columns").first();
this.location = location.text();
// get "pollen type" from XML
Element pollenType = doc.select("div.panel h3").first();
this.pollenType = pollenType.text();
SimpleDateFormat format = new SimpleDateFormat("EEE MMMM dd, yyyy");
// add the four items of pollen and dates
// to its respective list
for(int i = 0; i < 4; i++) {
Element dates = doc.select("td.text-center.even-four").get(i);
Element levels = doc.select("td.levels").get(i);
// Removed nested try-catch block
pollenMap.put(format.parse(dates.text()), levels.text());
}
} catch (IOException e) {
displayToast(context);
} catch (ParseException e) {
// We catch the ParseException here instead of nesting try-catch blocks.
displayToast(context);
} catch (IllegalStateException e) {
// Catch the IllegalStateException thrown when div.columns was null,
// and let the user know what went wrong.
displayToast(context);
}
}
private void displayToast(Context context) {
((Activity) context).runOnUiThread(new Runnable() {
public void run() {
Toast toast = Toast.makeText(context, R.string.toast_parse_fail, Toast.LENGTH_LONG);
toast.show();
}
});
}

how can i add multithreading or other similar function to android application?

my android application freezes for a few seconds when i try to send my database file to my remote server, is there anyway i can set this as a background thread using multithreading or another such feature?
this is the code for the dialog box that appears to ask me if i want to send
public void showYesNoBox(){
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
SendData();
finish();//go back to the previous Activity
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
finish();//go back to the previous Activity
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_DARK);
builder.setMessage("Do you want to send the data now?");
builder.setPositiveButton("Yes", dialogClickListener);
builder.setNegativeButton("No", dialogClickListener);
builder.show();
}
and here is the code it executes when i click the "Yes" button
public void SendData() {
File path = getDatabasePath(DataBaseHelper.DATABASE_NAME);
if (path.exists())
copyDatabase(path);
}
/**
* Copy the database to the sdcard
* #param file
*/
private void copyDatabase(File file) {
SimpleDateFormat dateFormat1 = new SimpleDateFormat("ddMMyy-HHmmss");
String dateString = dateFormat1.format(new Date());
String pathdest = getDir().getAbsolutePath() + Configuration.LOST_FOLDER + "/Database/";
String pathdir = pathdest;
File dir = new File(pathdir);
if (!dir.exists())
dir.mkdirs();
String namefile = file.getName();
int pos = namefile.lastIndexOf('.');
if (pos != -1) {
String ext = namefile.substring(pos + 1);
String name = namefile.substring(0, pos - 1);
pathdest += name;
pathdest += "_" + dateString;
pathdest += ext;
} else {
pathdest += namefile;
pathdest += "_" + dateString;
}
File filedest = new File(pathdest);
try {
if (filedest.createNewFile())
copyFile(file.getAbsolutePath(), pathdest);
} catch (IOException e) {
e.printStackTrace();
}
}
any help with this problem would be greatly appreciated as while the problem doesn't prevent the user from being able to send the data it is anoying to be stuck on one screen for a few seconds while it attempts to execute the action.
while the problem doesn't prevent the user from being able to send the data it is anoying to be stuck on one screen for a few seconds while it attempts to execute the action.
You can see AsyncTask. Its for the same purposes. User need not be stuck on UI when you want to do long running processes including taking to server, doing database stuff etc. This can be done in the background using AsyncTask. There are many good tutorials out there. Just Google it. Checkout Android Background Processing with Threads, Handlers and AsyncTask - Tutorial and What arguments are passed into AsyncTask<arg1, arg2, arg3>? . Hope this helps.
I've been using asynctask for handling all the processes I want to do in the background.
AsyncTask
Use all network operations in AsyncTask
like the below example
private class UploadTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
// upload task
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
Once created, a task is executed very simply:
new UploadTask().execute(url1, url2, url3);

Categories

Resources