Android: whenever a edittext field is left empty, program closes giving exception - java

program sudenly close when any edittext is left empty when ever i pressed a button to move to next to activity. here is the code.
package cme.ws.com.ws.cme;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
* Created by Waqas Aamer on 5/27/2015.
*/
public class areaActivity extends Activity {
int plotarea, coveredarea;
int brickprice, blockprice, cementprice, sandprice, crushprice, ironprice;
int brickprice1, blockprice1, cementprice1, sandprice1, crushprice1, ironprice1;
int plotarea1, coveredarea1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_area);
{
final Context context = getApplicationContext();
final int duration = Toast.LENGTH_SHORT;
Button movenextarea=(Button) findViewById(R.id.buttonnextexteriorwall);
movenextarea.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = getIntent();
if (null != intent)
{
// test = intent.getStringExtra("NameOfVariable");
brickprice1 = intent.getIntExtra("anything00", brickprice);
blockprice1 = intent.getIntExtra("anything11", blockprice);
sandprice1 = intent.getIntExtra("anything22", sandprice);
ironprice1 = intent.getIntExtra("anything33", ironprice);
cementprice1 = intent.getIntExtra("anything44", cementprice);
crushprice1 = intent.getIntExtra("anything55", crushprice);
}
EditText areanumber1 = (EditText) findViewById(R.id.editTextplotarea);
if(areanumber1 == null)
{
Toast toast = Toast.makeText(context, "Please fill the plot area field ", duration);
toast.show();
}
else
{
plotarea1 = Integer.parseInt(areanumber1.getText().toString());
}
EditText areanumber2 = (EditText) findViewById(R.id.editTextcoveredarea);
if(areanumber2 == null)
{
Toast toast1 = Toast.makeText(context, "Please fill the covered area field ", duration);
toast1.show();
}
else
{
coveredarea1 = Integer.parseInt(areanumber2.getText().toString());
}
int sqrt = (int) Math.sqrt(plotarea1);
int oneside = sqrt;
Intent secondActivity = new Intent (getApplicationContext(), exteriorwallActivity.class);
secondActivity.putExtra("anything000", brickprice1);
secondActivity.putExtra("anything111", blockprice1);
secondActivity.putExtra("anything222", cementprice1);
secondActivity.putExtra("anything333", sandprice1);
secondActivity.putExtra("anything444", ironprice1);
secondActivity.putExtra("anything555", crushprice1);
secondActivity.putExtra("anything", oneside);
secondActivity.putExtra("anything1", coveredarea1);
startActivity(secondActivity);
}
});
}
}
}
i want this that whenver a edittext box is left empty .the variable in whcih it is storing that value automatically stores 0.
eroor log is
07-05 23:20:42.206 14348-14348/cme.ws.com.ws.cme E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NumberFormatException: unable to parse '' as integer
at java.lang.Integer.parseInt(Integer.java:412)
at java.lang.Integer.parseInt(Integer.java:382)
at cme.ws.com.ws.cme.areaActivity$1.onClick(areaActivity.java:52)
at android.view.View.performClick(View.java:2408)
at android.view.View$PerformClick.run(View.java:8816)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)

Your EditText fields cannot be equals null because in previous line of your verification you have initialized them. Instead of using if (areanumber1 == null) and if (areanumber2 == null), check your EditText like this:
boolean isEmpty(EditText textField) {
return textField.getText().toString().trim().length() == 0;
}
If function return false means that EditText is not empty and return true means that EditText is empty.

This test...
if(areanumber1 == null)
does not check if the EditText called areanumber1 has no text. This checks if the variable named areanumber1 is a null reference. Hopefully it's not since you know what IDs your layout XML is using. What's happening is your code is trying to use parseInt() on an empty string.
You should instead do something like this:
String area1text = areanumber1.getText().toString(); // works even if empty
if (TextUtils.isEmpty(area1Text)) { // text is empty
plotarea1 = 0;
} else {
plotarea1 = Integer.parseInt(area1text);
}
TextUtils is an Android class with some useful static methods like the one I used above. Also, make sure your EditTexts are using the proper android:inputType to restrict the text to numbers only, or else the parseInt() will throw an exception.

Related

error with running the android app after adding the settext to the textview

the java file that it's probably the problem from and it's not realted to xml at all:
package com.example.android.randomnumber;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
EditText from = (findViewById(R.id.editTextFrom));
EditText to = (findViewById(R.id.editTextTo));
TextView output =(findViewById(R.id.textViewOutput));
String wfrom = from.getText().toString();
int numberfrom=Integer.parseInt(wfrom);
String wto = to.getText().toString();
int numberto=Integer.parseInt(wto);
Random randomNumberGenerator =new Random();
int number = randomNumberGenerator.nextInt(numberto-numberfrom)+numberfrom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
output.setText(number);
}
public void generate(View view){
if (from.getText() == null || "".equals(from.getText().toString())){
Toast.makeText(MainActivity.this, "the -From- value is empty!",
Toast.LENGTH_SHORT).show();
return;
}else if (to.getText() == null || "".equals(to.getText().toString())){
Toast.makeText(MainActivity.this, "the -To- value is empty!",
Toast.LENGTH_SHORT).show();
return;
}else if(numberfrom >= numberto){
Toast.makeText(MainActivity.this, "the -To- value must be greater than the -From- value",
Toast.LENGTH_SHORT).show();
return;
}
Log.d("test", "it's from:"+numberfrom+" to this:"+numberto+"generatednumber"+number);
}
}
the error in Logcat thank you in advance:
02-24 14:16:33.865 23117-23117/com.example.android.randomnumber E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.randomnumber, PID: 23117
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.android.randomnumber/com.example.android.randomnumber.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2989)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3260)
at android.app.ActivityThread.access$1000(ActivityThread.java:218)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1734)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6934)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImpl.<init>(AppCompatDelegateImpl.java:249)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:182)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:520)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:191)
at com.example.android.randomnumber.MainActivity.<init>(MainActivity.java:15)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1690)
at android.app.Instrumentation.newActivity(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2979)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3260) 
at android.app.ActivityThread.access$1000(ActivityThread.java:218) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1734) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:6934) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 
i tried to run it through my phone the problem is stil and the problem start toshow when i added the output.setText and thank you again...........................................................................
Your logic code is not correct, please change it to
public class MainActivity extends AppCompatActivity {
EditText from;
EditText to;
TextView output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
from = (findViewById(R.id.editTextFrom));
to = (findViewById(R.id.editTextTo));
output = (findViewById(R.id.textViewOutput));
}
public void generate(View view) {
// Get values of from and to edit text
String wfrom = from.getText().toString();
String wto = to.getText().toString();
// Validate from value
if (TextUtils.isEmpty(wfrom)) {
Toast.makeText(MainActivity.this, "the -From- value is empty!",
Toast.LENGTH_SHORT).show();
return;
}
// Validate to value
if (TextUtils.isEmpty(wto)) {
Toast.makeText(MainActivity.this, "the -To- value is empty!",
Toast.LENGTH_SHORT).show();
return;
}
int numberfrom = Integer.parseInt(wfrom);
int numberto = Integer.parseInt(wto);
// Check whether from larger or equal than to
if (numberfrom >= numberto) {
Toast.makeText(MainActivity.this, "the -To- value must be greater than the -From- value",
Toast.LENGTH_SHORT).show();
return;
}
// Generate a random number in range [from - to]
Random randomNumberGenerator = new Random();
int number = randomNumberGenerator.nextInt(numberto - numberfrom) + numberfrom;
// Display the random number on output text view
output.setText(number + "");
// Log for debug
Log.d("test", "it's from:" + numberfrom + " to this:" + numberto + "generatednumber" + number);
}
}

App Crashed while passing data using Intent on Pressing Next Button (getStringExtra) [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I want to move all data 5 (EditText) from activity 1 to 2
public class MainActivity extends Activity
private EditText fName_ET;
private EditText lName_ET;
private EditText phoneNum_ET;
private EditText eMail_ET;
private EditText deviceModel_ET;
private EditText nameDevice_ET;
private Button nextPage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
fName_ET = (EditText)findViewById(R.id.fName_ET);
lName_ET = (EditText)findViewById(R.id.lName_ET);
phoneNum_ET = (EditText)findViewById(R.id.phone_ET);
eMail_ET = (EditText)findViewById(R.id.mail_ET);
nameDevice_ET = (EditText)findViewById(R.id.name_device);
deviceModel_ET = (EditText)findViewById(R.id.model_device);
nextPage = (Button)findViewById(R.id.next_btn);
nextPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
String fName = fName_ET.getText().toString().trim();
String lName = lName_ET.getText().toString().trim();
String email = eMail_ET.getText().toString().trim();
String phone = phoneNum_ET.getText().toString().trim();
String nameDevice = nameDevice_ET.getText().toString().trim();
String modelDevice =deviceModel_ET.getText().toString().trim();
intent.putExtra("modelDevice",modelDevice);
intent.putExtra("fName", fName);
intent.putExtra("lName", lName);
intent.putExtra("phone", phone);
intent.putExtra("email", email);
intent.putExtra("nameDevice", nameDevice);
startActivity(intent);
}
});
public class Main2Activity extends Activity
{
package com.example.eranp.cp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Main2Activity extends Activity {
private EditText pro_device_det;
private Button saveDataBase;
private DatabaseReference databaseCustomer, databaseDevice, databaseProblem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main3);
databaseCustomer = FirebaseDatabase.getInstance().getReference("customers");
databaseDevice = FirebaseDatabase.getInstance().getReference("device");
databaseProblem = FirebaseDatabase.getInstance().getReference("problem");
saveDataBase = (Button) findViewById(R.id.save_btn);
pro_device_det = (EditText) findViewById(R.id.pro_device_det);
Intent intent = getIntent();
final String fName = intent.getStringExtra("fName");
final String lName = intent.getStringExtra("lName");
final String phone = intent.getStringExtra("phone");
final String email = intent.getStringExtra("email");
final String modelDevice = intent.getStringExtra("modelDevice");
final String nameDevice = intent.getStringExtra("nameDevice");
saveDataBase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String proDeviceDet = pro_device_det.getText().toString().trim();
String shortProDeviceDet = string3Words(proDeviceDet);
DateFormat df = new SimpleDateFormat("d MMM yyyy, HH:mm");
String date = df.format(Calendar.getInstance().getTime());
if (!TextUtils.isEmpty(proDeviceDet)) {
String id = databaseCustomer.push().getKey();
Customer customer = new Customer(id, fName, lName, email, phone);
databaseCustomer.child(id).setValue(customer);
Device device = new Device(id, nameDevice, modelDevice);
databaseDevice.child(id).setValue(device);
Problem problem = new Problem(id, date, proDeviceDet, 0, shortProDeviceDet);
// Toast.makeText(this , "Customer added", Toast.LENGTH_LONG).show();
} else {
// Toast.makeText(this, "Please write on an empty cell", Toast.LENGTH_LONG).show();
}
}
});
}
private String string3Words(String s) {
String[] splitted = s.split("\\s+");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < splitted.length; i++) {
sb.append(splitted[i]);
if (i == 3) {
break;
}
}
String newS = sb.toString();
return newS;
}
}
log when I press:
down VM 03-09 14:47:16.903 3476-3476/com.example.eranp.clientpage
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.eranp.clientpage, PID: 3476
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.eranp.clientpage/com.example.eranp.clientpage.Main2Activity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2924)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2985)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1635)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6692)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'void
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
at
com.example.eranp.clientpage.Main2Activity.onCreate(Main2Activity.java:50)
at android.app.Activity.performCreate(Activity.java:6912)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2877)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2985) 
at android.app.ActivityThread.-wrap14(ActivityThread.java) 
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1635) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6692) 
at java.lang.reflect.Method.invoke(Native Method) 
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
Why when I press the next button the app crashing?
Thank you for helping!
You are trying to set a click listener on a button in Main2Activity. Most likely the button can't be inflated from the second activity's layout because it doesn't exist.
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference at
com.example.eranp.clientpage.Main2Activity.onCreate(Main2Activity.java:50)
at
As per your error log you are getting error because of this
Attempt to invoke virtual method 'void
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference at com.example.eranp.clientpage.Main2Activity.onCreate(Main2Activity.java:50)
saveDataBase = (Button) findViewById(R.id.save_btn);
saveDataBase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// code...
}
});
Check weather button id is correct and is in same layout of the activity or not.

Illegal destination address sms manager shared preferences

I am using numbers stored in shared preferences to send text messages but when i run the app it crashes and the logcat says there is an illegal destination address how?
here is my logcat
12-30 21:01:30.758 12239-12239/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.beez.help2, PID: 12239
java.lang.IllegalArgumentException: Invalid destinationAddress
at android.telephony.SmsManager.sendTextMessage(SmsManager.java:127)
at com.android.beez.help2.MainActivity.sendSms(MainActivity.java:63)
at com.android.beez.help2.MainActivity$2.onClick(MainActivity.java:41)
at android.view.View.performClick(View.java:4475)
at android.view.View$PerformClick.run(View.java:18790)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5328)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
at dalvik.system.NativeStart.main(Native Method)
and here is my
MainActivity.java
package com.android.beez.help2;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button button;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonInit();
Button setupMa = (Button) findViewById(R.id.setupMA);
setupMa.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent a = new Intent(MainActivity.this,Setup.class);
startActivity(a);
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadCredit();
sendSms();
}
});
}
protected void sendSms() {
spInit();
String number1 = sharedPreferences.getString("first", "");
String number2 = sharedPreferences.getString("second", "");
String number3 = sharedPreferences.getString("third", "");
String name = sharedPreferences.getString("name", "");
String text = "Help, this is " + name + ", if you are reading this I am in trouble please help me" +
" Iam located at " + "http://www.google.com/maps/place/"+GPSTracker.latitude+","+GPSTracker.longitude+ " " +
"" +
"" +
"-Sent via the Emergency App";
SmsManager manager = SmsManager.getDefault();
manager.sendTextMessage(number1, null, text, null, null);
manager.sendTextMessage(number2, null, text, null, null);
manager.sendTextMessage(number3, null, text, null, null);
boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (isFirstRun) {
Intent launchSetups = new Intent(MainActivity.this, Setup.class);
startActivity(launchSetups);
}
}
protected void loadCredit() {
spInit();
String creditLine = sharedPreferences.getString("dialLoadSp","");
Uri number = Uri.parse("tel:"+creditLine);
Intent callIntent = new Intent(Intent.ACTION_DIAL, number);
startActivity(callIntent);
}
public void buttonInit() {
button = (Button) findViewById(R.id.button_main);
}
public void spInit() {
sharedPreferences = MainActivity.this.getSharedPreferences("com.android.beez.help2",MODE_PRIVATE);
}
}
The numbers the messages are being sent to are from editTexts and are the stored in sharedPreferences. could the problem be from shared preferences or is it and issue of the text manager
I think you should specify the destination address add an if... if(num1!="" || num2!="" || num3...)
manager.sendText...
Oh, I know this one :) Hope I'm not to late.
IllegalArgumentException is thrown if destinationAddress or text are empty.
In your case, you have this String number1 = sharedPreferences.getString("first", ""); which means that your number1 is empty at first run of the app, and therefore you get that exception.
Also you didn't provide full code here, where you said that numbers would be fill from edit text.

Why do I get "java.lang.IllegalArgumentException" error? [duplicate]

This question already has answers here:
Illegal argument exception: n must be positive
(3 answers)
Closed 5 years ago.
I have this code, I took it from stackoverflow and a bit changed it. The code retrieve the gallery`s content and put every image path inside an array list. Then it choose randomly one of the path inside the ArrayList and put as resources for an ImageView. Thank you for attention.
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
Handler handler = new Handler();
private ImageView randomPicture;
private Bitmap currentBitmap = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
randomPicture = (ImageView)findViewById(R.id.random_picture);
final ArrayList<String> imagesPath = new ArrayList<>();
String[] projection = new String[]{
MediaStore.Images.Media.DATA,
};
Uri images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
Cursor cur = getContentResolver().query(images, projection, null, null, null)
if(cur == null) {
randomPicture.setImageResource(R.drawable.picture);
}
else {
if (cur.moveToFirst()) {
int dataColumn = cur.getColumnIndex(
MediaStore.Images.Media.DATA);
do {
imagesPath.add(cur.getString(dataColumn));
} while (cur.moveToNext());
}
cur.close();
final Random random = new Random();
final int count = imagesPath.size();
handler.post(new Runnable() {
#Override
public void run() {
int number = random.nextInt(count);
String path = imagesPath.get(number);
if (currentBitmap != null)
currentBitmap.recycle();
currentBitmap = BitmapFactory.decodeFile(path);
randomPicture.setImageBitmap(currentBitmap);
handler.postDelayed(this, 1000);
}
});
}
}
}
It crashes on the line with Cursor with the error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.postcards, PID: 2424
java.lang.IllegalArgumentException: n <= 0: 0
at java.util.Random.nextInt(Random.java:182)
at com.example.postcards.MainActivity$1.run(MainActivity.java:53)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Random#nextInt(int) expects the argument to be positive. This is not the case here.
Source
This line:
int number = random.nextInt(count);
gives you the error because you pass 0 as the count. Using nextInt(int) requires input that is greater than 0. The input cannot be negative or 0
The error clearly states that you cannot pass to Random.nextInt() method a value less or equal to 0.
java.lang.IllegalArgumentException: n <= 0: 0
The problem is the nextInt from random. It is possible that your count is zero?

My app crashes when my phone's language is set to Persian or Arabic because of Double.parseDouble

below is the java code for one of my activities, it works fine when the phone's language is English but when the phone's language is set to Persian or Arabic it crashes. the logcat says that it is something wrong with the Double.parseDouble. it seems when the user enters the numbers it changes them into Persian or Arabic digits and thats why it crashes. Any ideas how to fix?
The java code:
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class stressesoninclinedsections extends AppCompatActivity {
private EditText input1;
private EditText input2;
private EditText input3;
private TextView sh_resultt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stressesoninclinedsections);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
input1 = (EditText) findViewById(R.id.editText);
input2 = (EditText) findViewById(R.id.editText2);
input3 = (EditText) findViewById(R.id.editText3);
Button bt_calculate1 = (Button) findViewById(R.id.button4);
sh_resultt = (TextView) findViewById(R.id.textView8);
bt_calculate1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
makeCalculationss();
}
});
}
private void makeCalculationss() {
if ( input1.getText().toString().trim().equals("") || input1.getText().toString().trim().equals("-") || input1.getText().toString().trim().equals(".") || input1.getText().toString().trim().equals("-.")
|| input2.getText().toString().trim().equals("") || input2.getText().toString().trim().equals(".")
|| input3.getText().toString().trim().equals("") || input3.getText().toString().trim().equals("-") || input3.getText().toString().trim().equals(".") || input3.getText().toString().trim().equals("-.")) {
sh_resultt.setText("");
Snackbar.make(findViewById(android.R.id.content), "لطفا مقادیر تمامی متغیرها را وارد کنید ", Snackbar.LENGTH_LONG)
.show();
}
else {
Double n1 = Double.valueOf(input1.getText().toString());
Double n2 = Double.valueOf(input2.getText().toString());
Double n3 = Double.valueOf(input3.getText().toString());
Double n3pi2 = n3+90;
Double n3pi2rad = (n3pi2*Math.PI)/180;
Double n3radians = (n3*Math.PI)/180;
Double result1 = ((n1 / n2) *Math.cos(n3radians)*Math.cos(n3radians))/1000;
Double result2 = ((n1 / n2) *Math.cos(n3pi2rad)*Math.cos(n3pi2rad))/1000;
Double result3 = -((n1 / n2) *Math.sin(n3radians)*Math.cos(n3radians))/1000;
result1 =Double.parseDouble(new DecimalFormat("##.######").format(result1));
result2 =Double.parseDouble(new DecimalFormat("##.######").format(result2));
result3 =Double.parseDouble(new DecimalFormat("##.######").format(result3));
sh_resultt.setText( "σx' (MPa)=\n" + result1 + "\n" + "\nσy' (MPa)=\n" + result2 + "\n" + "\nTx'y' (MPa)=\n" + result3 );
}
}
#Override
public void onBackPressed() {
Intent intent = new Intent(stressesoninclinedsections.this, solidmechanics.class);
startActivity(intent);
finish();
}
}
Here is the Logcat:
03-08 19:16:32.457 3035-3035/com.wima.civilengineeringcalculator E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NumberFormatException: Invalid long: "٠٫٠١١٧٥٢"
at java.lang.Long.invalidLong(Long.java:125)
at java.lang.Long.parse(Long.java:362)
at java.lang.Long.parseLong(Long.java:353)
at java.lang.Long.parseLong(Long.java:319)
at java.math.BigDecimal.<init>(BigDecimal.java:350)
at java.math.BigDecimal.<init>(BigDecimal.java:438)
at com.wima.civilengineeringcalculator.stressesoninclinedsections.makeCalculationss(stressesoninclinedsections.java:65)
at com.wima.civilengineeringcalculator.stressesoninclinedsections.access$000(stressesoninclinedsections.java:16)
at com.wima.civilengineeringcalculator.stressesoninclinedsections$1.onClick(stressesoninclinedsections.java:42)
at android.view.View.performClick(View.java:3549)
at android.view.View$PerformClick.run(View.java:14393)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:4945)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
03-08 19:16:32.467 1595-2005/? E/EmbeddedLogger: App crashed! Process: com.wima.civilengineeringcalculator
03-08 19:16:32.467 1595-2005/? E/EmbeddedLogger: App crashed! Package: com.wima.civilengineeringcalculator v1 (1.0)
You need to convert your numbers from string to double with a latin locale (English-US for example) locale:
Try parsing this way:
try {
Double d=(Double)NumberFormat.getInstance(new Locale("en","US")).parse("123");
} catch (ParseException e) {
e.printStackTrace();
}
Thanks to all who answered specially Alaa M., because I somehow found the answer through his comment. The "," in Persian or Arabic digits that we use to write the decimals with it made the problem.
I managed to fix it by adding
Locale.setDefault(new Locale("en", "US"));
to my code.

Categories