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);
}
Related
Im new to android and they(some people :) ) gave me an half developed app and im still confused about some things.
Im getting an error which i can't understand what it means. So the error is what i wrote in the title : java.lang.IllegalStateException: FragmentManager has not been attached to a host, and is hapening when this activity runs:
package com.example.loginregistodb;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
public class ClienteActivity extends AppCompatActivity {
Spinner tipo_intervencao;
Button bt_cliente_seguinte;
EditText et_inserir_cliente;
ImageView icon1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cliente);
bt_cliente_seguinte = (Button) findViewById(R.id.bt_cliente_seguinte);
et_inserir_cliente = findViewById(R.id.et_inserir_cliente);
tipo_intervencao = findViewById(R.id.tipo_intervencao);
icon1 = findViewById(R.id.icon2);
bt_cliente_seguinte.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String cliente = et_inserir_cliente.getText().toString();
String tipoIntervencao = "" + tipo_intervencao.getSelectedItem().toString();
preencherExcel Excel = new preencherExcel();
Excel.entradaWhatsapp(cliente, tipoIntervencao);
if (cliente.equalsIgnoreCase("")) {
Toast.makeText(ClienteActivity.this, "Preencha o campo Cliente!", Toast.LENGTH_SHORT).show();
} else {
Intent i = new Intent(ClienteActivity.this, EmpresaActivity.class);
startActivity(i);
}
}
});
}
}
EDIT :
the error message i get is this :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.loginregistodb, PID: 15275
java.lang.IllegalStateException: FragmentManager has not been attached to a host.
at androidx.fragment.app.FragmentManager.ensureExecReady(FragmentManager.java:1938)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1996)
at androidx.fragment.app.FragmentManager.executePendingTransactions(FragmentManager.java:600)
at com.google.firebase.firestore.core.ActivityScope.lambda$onFragmentActivityStopCallOnce$1(ActivityScope.java:180)
at com.google.firebase.firestore.core.ActivityScope$$ExternalSyntheticLambda1.run(Unknown Source:4)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
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());*/
}
}
When i am trying to add two string variable msg and phoneNo in the TextView through setter method present in MainActivity.java (which is called by dow() method which is present in MyReceiver.java) a Runtime Exception (shown below)
occurs When onReceive method in MyReceiver.java file is called by broadcastReceiver. I am unable to understand the Exceptio
MainActivity.java
package com.example.smsreceiver;
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.pm.PackageManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final int MY_PERMISSION_REQUEST_RECEIVE_SMS = 0;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView2);
//check if the permission is not granted
if(ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED) {
if(!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECEIVE_SMS)) {
//a pop up will appear asking for required permission i.e. Allow or Deny
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECEIVE_SMS}, MY_PERMISSION_REQUEST_RECEIVE_SMS);
}
}
//this.setter();
}//onCreate
//after getting the result of permission request the result will be passed through this method
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
//will check the requestCode
if (requestCode == MY_PERMISSION_REQUEST_RECEIVE_SMS) {//check whether the length of grantResults is greater than 0 and is equal to PERMISSION_GRANTED
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Now broadcast receiver work in background
Toast.makeText(this, "Thank you for permitting!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Well I can't do anything until you permit me", Toast.LENGTH_LONG).show();
}
}
}
public void setter(String msg, String phoneNo){
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView2);
String hi = msg + phoneNo;
textView.setText(hi);
Toast.makeText(this, "message: " + msg + "\n Number: " + phoneNo, Toast.LENGTH_LONG).show();
}
}
MyReceiver.java
package com.example.smsreceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
import java.util.Objects;
public class MyReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
private static final String TAG = "SmsBroadcastReceiver";
public static String msg, phoneNo = "";
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Intent Received: " + intent.getAction());
if(Objects.equals(intent.getAction(), SMS_RECEIVED)) {
//retrieves a map of extended data from the intent
Bundle dataBundle = intent.getExtras();
if (dataBundle != null) {
//create an PDU(Protocol Data Unit) object which is a protocol for transferring message
Object[] mypdu = (Object[])dataBundle.get("pdus");
final SmsMessage[] message = new SmsMessage[mypdu.length];
for (int i = 0; i < mypdu.length; i++) {
//for build version >= API Level 23 (Build.VERSION_CODES.M)
String format = dataBundle.getString("format");
//from PDU we get all abject and SmsMessage Object using following line of code
message[i] = SmsMessage.createFromPdu((byte[]) mypdu[i], format);
msg = message[i].getMessageBody();
phoneNo = message[i].getOriginatingAddress();
}
Toast.makeText( context, "message: " + msg + "\n NUmber: " + phoneNo, Toast.LENGTH_LONG).show();
dow(msg, phoneNo);
}
}
}
public void dow(String msg, String phoneNo){
MainActivity mainActivity = new MainActivity();
mainActivity.setter(msg, phoneNo);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="24sp"
/>
</LinearLayout>
Exception shown by Logcat
Process: com.example.smsreceiver, PID: 18414
java.lang.RuntimeException: Unable to start receiver com.example.smsreceiver.MyReceiver: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3665)
at android.app.ActivityThread.access$1500(ActivityThread.java:219)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1850)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:227)
at android.app.ActivityThread.main(ActivityThread.java:7200)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:575)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:903)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:91)
at android.view.ContextThemeWrapper.getResourcesInternal(ContextThemeWrapper.java:127)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:121)
at androidx.appcompat.app.AppCompatActivity.getResources(AppCompatActivity.java:543)
at android.widget.Toast.<init>(Toast.java:139)
at android.widget.Toast.makeText(Toast.java:306)
at android.widget.Toast.makeText(Toast.java:296)
at com.example.smsreceiver.MainActivity.setter(MainActivity.java:60)
at com.example.smsreceiver.MyReceiver.dow(MyReceiver.java:51)
at com.example.smsreceiver.MyReceiver.onReceive(MyReceiver.java:45)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3649)
at android.app.ActivityThread.access$1500(ActivityThread.java:219)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1850)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:227)
at android.app.ActivityThread.main(ActivityThread.java:7200)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:575)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:903)
You are trying to instantiate MainActivity on your own. Instead, do the following :
1)Create MyReceiver as an inner class inside MainActivity and register it as usual.
2)Receive the broadcast and update the UI from within onReceive().
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.
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?