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?
Related
To this day I'm facing a slight problem, I've been working on the subject for several weeks and I still can't find out why it doesn't work, I can explain.
For a personal project I need to create EditText dynamically, more precisely an array of EditText, so I managed to do that but I can't get the text from them and display it.
At first I asked
P1.setText(playerName[id].getText().toString());
except I forgot that my id variable had a ++ which was in place so the id I was asking for in the list didn't exist yet so the error Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.jenaijamais, PID: 6450
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
at android.view.View.performClick(View.java:7161)
at android.view.View.performClickInternal(View.java:7138)
at android.view.View.access$3500(View.java:811)
at android.view.View$PerformClick.run(View.java:27419)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7520)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:7161)
at android.view.View.performClickInternal(View.java:7138)
at android.view.View.access$3500(View.java:811)
at android.view.View$PerformClick.run(View.java:27419)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7520)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.jenaijamais.NumberOfPlayers.play(NumberOfPlayers.java:98)
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:7161)
at android.view.View.performClickInternal(View.java:7138)
at android.view.View.access$3500(View.java:811)
at android.view.View$PerformClick.run(View.java:27419)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7520)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
so to make a test I asked for 0 in the list and there always the same error even when filling the EditText (I specify that I fill the fields each time so they are not null in theory), then I tried with 1 the same same error it doesn't want to get the text back.
I specify that the final goal is to loop all the text of the fields and insert them in a SQLite database but for the moment I just want to do some tests without a database to make sure it works but I can't get the text from ONE EditText so many at the moment it's not even worth thinking about it.
package com.example.jenaijamais;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.Console;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
public class NumberOfPlayers extends AppCompatActivity {
public Button btnAdd;
public DatabasePlayers databasePlayers;
public ViewGroup layoutAddPlayer;
public ViewGroup main;
public int id = 1;
public int id2 = 1;
public EditText[] playerName;
public TextView P1;
#SuppressLint("ResourceType")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_number_of_players);
databasePlayers = new DatabasePlayers(this);
layoutAddPlayer = findViewById(R.id.addPlayerLayout);
main = findViewById(R.id.addPlayerLayout2);
btnAdd = findViewById(R.id.btnAdd);
P1 = (TextView) findViewById(R.id.P1);
for (int i = 1; i < 5; i++){
playerName = new EditText[100];
playerName[i] = new EditText(this);
playerName[i].setId(id);
playerName[i].setHint("Joueur n°"+playerName[i].getId());
RelativeLayout.LayoutParams config = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
config.setMargins(0,8,0,8);
config.addRule(RelativeLayout.BELOW, playerName[i].getId());
layoutAddPlayer.addView(playerName[i],config);
playerName[i] = (EditText) findViewById(i);
id++;
}
//playerName[0] = (EditText) findViewById(1);
}
public void addPlayer(View view) {
/*id++;
playerName = new EditText[id--];
playerName[id] = new EditText(this);
playerName[id].setId(id);
playerName[id].setHint("Joueur n°"+this.playerName[id].getId());
RelativeLayout.LayoutParams config = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
config.setMargins(0,8,0,8);
config.addRule(RelativeLayout.BELOW, playerName[id].getId());
layoutAddPlayer.addView(playerName[id],config);
id++;
nameView = new TextView[id--];
nameView[id] = new TextView(this);
nameView[id].setId(id);
nameView[id].setText("Player"+id);
RelativeLayout.LayoutParams config2 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
config2.setMargins(0, 8, 0, 8);
config2.addRule(RelativeLayout.BELOW, nameView[id].getId());
main.addView(nameView[id],config2);
id++;
//nameView[0].setText(String.valueOf(id));*/
}
public void play(View view) {
P1.setText(playerName[0].getText().toString());
}
private void viewAll(){
/*Cursor data = databasePlayers.getAllData();
if (data.getCount() == 0){
P1.setText("ERROR, NO DATA");
return;
}
StringBuffer buffer = new StringBuffer();
while (data.moveToNext()){
buffer.append("playerID :" +data.getString(0)+"\n");
buffer.append("playerName : "+data.getString(1)+"\n");
buffer.append("playerScore : "+data.getString(2)+"\n");
}
P1.setText(buffer.toString());*/
}
}
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
package com.example.smsread;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ListView listView;
private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
ArrayList<String> smsList;
//private static final String TAG == MainActivity.class.getSimpleName()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.idList);
int permissionCheck = ContextCompat.checkSelfPermission( this,
Manifest.permission.READ_SMS);
if(permissionCheck == PackageManager.PERMISSION_GRANTED) {
showContacts();
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_SMS},
PERMISSIONS_REQUEST_READ_CONTACTS);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResult){
if(requestCode == PERMISSIONS_REQUEST_READ_CONTACTS){
if(grantResult[0] == PackageManager.PERMISSION_GRANTED) {
showContacts();
}else {
Toast.makeText(this,
"Until you grant the permission, we cannot display the names",
Toast.LENGTH_SHORT).show();
}
}
}
private void showContacts(){
Uri inboxUri = Uri.parse("content://sms/inbox");
smsList = new ArrayList<>();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(inboxUri, null, null, null, null);
while (cursor.moveToNext()){
String number = cursor.getString(cursor.getColumnIndexOrThrow("address")).toString();
String body = cursor.getString(cursor.getColumnIndexOrThrow("body")).toString();
//String number = "098765432";
//String body = "lat: 33.584317N long: 73.045458";
String data = body;
String[] args = data.split(" ");
// String a = body.trim();
// String latitude = args[1];
// String longitude = args[1];
// Log.d("Args",a);
Log.d("Args",args[1]);
Log.d("Args",args[3]);
smsList.add("Number:" + number + "\n" + "Body:" + body + "\n"+"latitude:" +args[1]+ "\n" + "longitude:" +args[3] );
//+ "\n" + "latitude:" +args[1]+ "\n" + "longitude:" +args[3]
}
cursor.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
smsList);
listView.setAdapter(adapter);
}
}
error: E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.smsread, PID: 28273
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.smsread/com.example.smsread.MainActivity}:
java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3430)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3614)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:86)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199)
at android.os.Handler.dispatchMessage(Handler.java:112)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
at com.example.smsread.MainActivity.showContacts(MainActivity.java:83)
at com.example.smsread.MainActivity.onCreate(MainActivity.java:44)
at android.app.Activity.performCreate(Activity.java:7458)
at android.app.Activity.performCreate(Activity.java:7448)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1286)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3409)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3614)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:86)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199)
at android.os.Handler.dispatchMessage(Handler.java:112)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
I/Process: Sending signal. PID: 28273 SIG: 9 Process 28273 terminated.
Why am I getting this error?
Because of ArrayIndexOutOfBoundsException. When you're splitting data to args[] and trying to log args[1] and args[3] make sure it has enough elements. Better to use more safety constructions like:
for(String s : args){
Log.d("Args", s);
}
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);
}
}
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.
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.