so I have an EditText field,and when the user tap a number,its start counting down.
The problem starts when the are not entering a number the app crash.
this is what I tried to do:
Thanks for the help.
public class MainActivity extends AppCompatActivity {
EditText mEnterNumber;
TextView mTest;
int timerIsRunning = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void StartRemainder(View view){
mTest = findViewById(R.id.mTest);
mEnterNumber = findViewById(R.id.mEnterNumber);
int userNumb = Integer.parseInt(mEnterNumber.getText().toString()) * 60000;
if(userNumb < 0 || mEnterNumber.toString().isEmpty()){
Toast.makeText(MainActivity.this, "Please enter correct number", Toast.LENGTH_SHORT).show();
}
else{
CountDownTimer userTimer = new CountDownTimer(userNumb,1000) {
#Override
public void onTick(long millisUntilFinished) {
long millis = millisUntilFinished;
//Convert milliseconds into hour,minute and seconds
String hms = String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
mTest.setVisibility(View.VISIBLE);
mTest.setText(hms);
timerIsRunning = 1;
}
#Override
public void onFinish() {
}
}.start();
}
}
----------------------This is the error I get when the app crash:--------------------------------
2020-09-04 04:09:15.024 27096-27096/com.example.drinkme E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.drinkme, PID: 27096
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:414)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NumberFormatException: For input string: ""
at java.lang.Integer.parseInt(Integer.java:620)
at java.lang.Integer.parseInt(Integer.java:643)
at com.example.drinkme.MainActivity.StartRemainder(MainActivity.java:40)
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
line of error:
int userNumb = Integer.parseInt(mEnterNumber.getText().toString()) * 60000;
I'm guessing the issue is with this line:
int userNumb = Integer.parseInt(mEnterNumber.getText().toString()) * 60000;
And it is because, an empty string("") cannot be converted to a number unlike strings like "1" or "2"
To fix this:
We Provide a try-catch block for the NumberFormatException
int userNumb = 0;
try {
if (mEnterNumber != null && !TextUtils.isEmpty(mEnterNumber.getText().toString())) {
userNumb = Integer.parseInt(mEnterNumber.getText().toString()) * 60000;
}
}
catch (NumberFormatException ex) {}
You're not getting the text from the edittext before checking weather it's empty or not. Try this :
if(userNumb < 0 && mEnterNumber.`getText()`.toString().isEmpty()){
Toast.makeText(MainActivity.this, "Please enter correct number",
Toast.LENGTH_SHORT).show();
int userNumb = Integer.parseInt(mEnterNumber.getText().toString()) * 60000;
}
As you can see I've put the integer conversion in the if block as it might also be the reason for it.
Like Felix Favour said it's because you're trying to parse a non-numeric item into a string. This line:
mEnterNumber = findViewById(R.id.mEnterNumber);
Will most likely resolve to Null if nothing is entered. You can try setting it to a numeric value:
mEnterNumber = findViewById(R.id.mEnterNumber);
if mEnterNumber.getText().toString().equals("")
{
int userNumb = 0; // or whatever value you want to set as a starting default
}
else
{
int userNumb = Integer.parseInt(mEnterNumber.getText().toString()) * 60000;
}
This invariably could need more improvement for checking or preventing other non-numeric entries ofcourse.
Alternatively, you can also set it in the XML like this:
<EditText
android:id="#+id/mEnterNumber"
...
android:text="0" />
I use something like this -
if (mEnterNumber.getText().toString().matches("")){
Toast.makeText(this, "Please Enter any number", Toast.LENGTH_SHORT).show();
return;
}
I hope this will prevent the crash.
Related
Kind of a newbie here, but I am trying to create a music app for my project in Android Studio and I keep running into an error every time I try to play a song from my playlist.
Here's the error on Logcat
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:414)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25885)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25885)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.spectrumv1.Song.getId()' on a null object reference
at com.example.spectrumv1.SongCollection.searchSongById(SongCollection.java:30)
at com.example.spectrumv1.PlaySongActivity.handleSelection(PlaySongActivity.java:40)
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25885)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
And here are the two classes mentioned by Logcat with errors
SongCollection.java
public class SongCollection {
public Song[] songs = new Song[2];
public SongCollection() {
Song godSpeed = new Song(
"S1001",
"(1) Godspeed",
"Frank Ocean",
"https://p.scdn.co/mp3-preview/6548bf4d7ad5b17d7602528182e586b86db8e23b?cid=2afe87a64b0042dabf51f37318616965",
2.97,
"https://i.scdn.co/image/ab67616d0000b273c5649add07ed3720be9d5526");
songs[0] = godSpeed;
}
public Song getCurrentSong(int currentSongId) {
return songs[currentSongId];
}
public int searchSongById(String Id) {
for (int index = 0; index < songs.length; index++) {
Song tempSong = songs[index];
if (tempSong.getId().equals(Id)) {
return index;
}
}
return -1;
}
public int getNextSong(int currentSongIndex) {
if (currentSongIndex >= songs.length - 1) {
return currentSongIndex;
} else {
return currentSongIndex + 1;
}
}
public int getPrevSong(int currentSongIndex) {
if (currentSongIndex <= 0) {
return currentSongIndex;
} else {
return currentSongIndex - 1;
}
}
}
And PlaySongActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import androidx.appcompat.app.AppCompatActivity;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class PlaySongActivity extends AppCompatActivity {
SongCollection songCollection = new SongCollection();
static ArrayList<Song> playList = new ArrayList<Song>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_song);
ImageButton S1001 = findViewById(R.id.songBG);
Picasso.with(this).load(songCollection.songs[0].getCoverArt()).into(S1001);
}
public void sendDataToActivity(int index)
{
Intent intent = new Intent(this, SongPlayer.class );
intent.putExtra("index", index);
startActivity(intent);
}
public void handleSelection(View view)
{
String resourceId = getResources().getResourceEntryName(view.getId());
int currentArrayIndex = songCollection.searchSongById(resourceId);
Log.d("temasek", "the current array position is: " + currentArrayIndex);
sendDataToActivity(currentArrayIndex);
}
}
any help would be appreciated
I think there's two issues causing your error. I think the first problem is that you created an array and didn't fill it with values
public Song[] songs = new Song[2];
...
Song godSpeed = new Song( ... )
songs[0] = godSpeed; // !! songs[1] isn't defined
And I think that if (tempSong.getId().equals(Id)) must not be working as intended, which is causing it to miss the correct song (godSpeed in songs[0]) and check the undefined element ( songs[1] )
I would recommend some sort of logging to check if it's working correctly.
Hi I am trying to parse JSON using Retrofit, save it on Sqlite and display on RecyclerView. However my app crashes when I try to open the activity.
Below is my full codes of related activity. Could you please help me with resolving the issue?
Thank you
public class InventoryProductActivity extends AppCompatActivity implements InventoryProductListAdapter.CustomClickListener {
private static final String TAG = InventoryProductActivity.class.getSimpleName();
private InventoryProductListAdapter mInventoryProductListAdapter;
private RecyclerView mRecyclerView;
private RetrofitClient mRetrofitClient;
LinearLayoutManager mLinearLayoutManager;
private WarehouseDatabase mDatabase;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inventory_product);
configViews();
mRetrofitClient = new RetrofitClient();
mDatabase = new WarehouseDatabase(this);
loadInventoryProductFeed();
}
private void configViews() {
mRecyclerView = findViewById(R.id.recycler_view_inventory_product);
mRecyclerView.setHasFixedSize(true);
mLinearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
mInventoryProductListAdapter = new InventoryProductListAdapter(this);
mRecyclerView.setAdapter(mInventoryProductListAdapter);
}
private void loadInventoryProductFeed() {
mProgressDialog = new ProgressDialog(InventoryProductActivity.this);
mProgressDialog.setMessage("Loading Inventory Data...");
mProgressDialog.setCancelable(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setIndeterminate(true);
mProgressDialog.show();
mInventoryProductListAdapter.reset();
if (getNetworkAvailability()) {
getFeed();
} else {
getFeedFromDatabase();
}
}
private void getFeed() {
Call<List<InventoryProductModel>> listCall = mRetrofitClient.getWarehouseServiceInventoryProduct().getAllInventoryProducts();
listCall.enqueue(new Callback<List<InventoryProductModel>>() {
#Override
public void onResponse(Call<List<InventoryProductModel>> call, Response<List<InventoryProductModel>> response) {
if (response.isSuccessful()) {
List<InventoryProductModel> inventoryProductModelList = response.body();
for (int i = 0; i < inventoryProductModelList.size(); i++) {
InventoryProductModel inventoryProductModel = inventoryProductModelList.get(i);
mInventoryProductListAdapter.notifyDataSetChanged();
}
} else {
int sc = response.code();
switch (sc) {
}
}
mProgressDialog.dismiss();
}
#Override
public void onFailure(Call<List<InventoryProductModel>> call, Throwable t) {
mProgressDialog.dismiss();
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void getFeedFromDatabase() {
List<InventoryProductModel> inventoryProductModelList = mDatabase.getInventoryProducts();
for (int i = 0; i < inventoryProductModelList.size(); i++) {
InventoryProductModel inventoryProductModel = inventoryProductModelList.get(i);
Log.d(TAG, inventoryProductModel.getName() + "||" + inventoryProductModel.getCountryId());
}
mProgressDialog.dismiss();
}
private boolean getNetworkAvailability() {
return Utils.isNetworkAvailable(getApplicationContext());
}
#Override
public void onClick(int position) {
}
}
E/WindowManager: android.view.WindowLeaked: Activity
codes.bala.bmsfinal1.activity.MainActivity has leaked window
DecorView#52c3fcd[] that was originally added here
at android.view.ViewRootImpl.(ViewRootImpl.java:418)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:331)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
at android.app.Dialog.show(Dialog.java:322)
at android.app.ProgressDialog.show(ProgressDialog.java:116)
at android.app.ProgressDialog.show(ProgressDialog.java:104)
at codes.bala.bmsfinal1.activity.MainActivity.login(MainActivity.java:61)
at codes.bala.bmsfinal1.activity.MainActivity$1.onClick(MainActivity.java:41)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
I/ViewConfigCompat: Could not find method getScaledScrollFactor() on
ViewConfiguration D/AndroidRuntime: Shutting down VM
--------- beginning of crash E/AndroidRuntime: FATAL EXCEPTION: main
Process: codes.bala.bmsfinal1, PID: 12077
java.lang.RuntimeException: Unable to start activity ComponentInfo{codes.bala.bmsfinal1/codes.bala.bmsfinal1.activity.InventoryProductActivity}:
java.lang.NullPointerException: Attempt to invoke interface method
'retrofit2.Call
codes.bala.bmsfinal1.iinterface.WarehouseService.getAllInventoryProducts()'
on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke interface
method 'retrofit2.Call
codes.bala.bmsfinal1.iinterface.WarehouseService.getAllInventoryProducts()'
on a null object reference
at codes.bala.bmsfinal1.activity.InventoryProductActivity.getFeed(InventoryProductActivity.java:88)
at codes.bala.bmsfinal1.activity.InventoryProductActivity.loadInventoryProductFeed(InventoryProductActivity.java:70)
at codes.bala.bmsfinal1.activity.InventoryProductActivity.onCreate(InventoryProductActivity.java:46)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Application terminated.
getWarehouseServiceInventoryProduct()
method return null.
You should set breakpoint inside this method and check what happening (or add some logs to this method).
I'm a novice coder and I've been trying to learn how to code for school in a few days and one thing I like to do is try and deconstruct other code to learn it better. So I was looking at trying to make a contact picker and I found a tutorial online, however, the code does not work, and I don't really understand what the error message means.
My code:
public class ContactActivity extends AppCompatActivity {
private static final int RESULT_PICK_CONTACT = 85500;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact);
}
public void pickContact(View v)
{
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// check whether the result is ok
if (resultCode == RESULT_OK) {
// Check for the request code, we might be usign multiple startActivityForReslut
switch (requestCode) {
case RESULT_PICK_CONTACT:
contactPicked(data);
break;
}
} else {
Log.e("MainActivity", "Failed to pick contact");
}
}
/**
* Query the Uri and read contact details. Handle the picked contact data.
* #param data
*/
private void contactPicked(Intent data) {
Button b1 = findViewById(R.id.button);
Button b2 = findViewById(R.id.button2);
Cursor cursor = null;
try {
String phoneNo = null ;
String name = null;
// getData() method will have the Content Uri of the selected contact
Uri uri = data.getData();
//Query the content uri
cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
// column index of the phone number
int phoneIndex =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
// column index of the contact name
int nameIndex =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
phoneNo = cursor.getString(phoneIndex);
name = cursor.getString(nameIndex);
// Set the value to the textviews
b1.setText(name);
b2.setText(phoneNo);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Error Message:
08-14 16:25:16.437 3923-3923/com.example.jackson.safetynet E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.jackson.safetynet, PID: 3923
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:389)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
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)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
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)
Caused by: java.lang.IllegalArgumentException: Can only use lower 16 bits for requestCode
at android.support.v4.app.BaseFragmentActivityApi14.checkForValidRequestCode(BaseFragmentActivityApi14.java:79)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:748)
at com.example.jackson.safetynet.ContactActivity.pickContact(ContactActivity.java:29)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
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)
So I see the line " Caused by: java.lang.IllegalArgumentException: Can only use lower 16 bits for requestCode " and I think that this is the problem. Is there something with the Result_Pick_Contact or what?
Layout Visual
Try using a smaller positive RESULT_PICK_CONTACT value
private static final int RESULT_PICK_CONTACT = 24;
As specified by this answer
You need to pass a positive number to startActivityForResult.
I would like to make it so that when the editText fields are empty, no result is shown instead of the app crashing.
I read over this result here: How to break out or exit a method in Java?
as well as some other results based on whether the number was negative or positive. I've been working in this for about an hour and I'm throwing in the towel. I'm new to this, and I think I must just not be putting the if statement in the correct location?
Here's the code. Any pointers in the right direction would be helpful. Thanks.
public class incomePage extends AppCompatActivity {
EditText perYearAmount;
EditText perMonthAmount;
EditText perWeekAmount;
Button totalButton;
TextView addResult;
double year, month, week, sum;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_income_page);
perYearAmount = (EditText) findViewById(R.id.perYearAmount);
perMonthAmount = (EditText) findViewById(R.id.perMonthAmount);
perWeekAmount = (EditText) findViewById(R.id.perWeekAmount);
totalButton = (Button) findViewById(R.id.totalButton);
addResult = (TextView) findViewById(R.id.totalMonthlyIncome);
totalButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
year = Double.parseDouble(perYearAmount.getText().toString());
month = Double.parseDouble(perMonthAmount.getText().toString());
week = Double.parseDouble(perWeekAmount.getText().toString());
sum = year + month + week;
addResult.setText(Double.toString(sum));
if (perYearAmount.getText().toString().equals("")) {
return;
}
if (perMonthAmount.getText().toString().equals("")) {
return;
}
if (perWeekAmount.getText().toString().equals("")) {
return;
}
if (totalButton.getText().toString().equals("")) {
return;
}
if (addResult.getText().toString().equals("")) {
return;
}
}
});
}
}
Here's the logCat error. You guys are fast!!
08-24 15:49:31.799 15154-16038/com.example.android.budgeit10 D/OpenGLRenderer: Enabling debug mode 0
08-24 15:49:35.123 15154-16038/com.example.android.budgeit10 D/OpenGLRenderer: endAllStagingAnimators on 0xb8937048 (RippleDrawable) with handle 0xb897a910
08-24 15:49:36.645 15154-16038/com.example.android.budgeit10 D/OpenGLRenderer: endAllStagingAnimators on 0xb89e95a0 (RippleDrawable) with handle 0xb89ebac8
08-24 15:49:50.694 15154-15154/com.example.android.budgeit10 D/AndroidRuntime: Shutting down VM
08-24 15:49:50.695 15154-15154/com.example.android.budgeit10 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.budgeit10, PID: 15154
java.lang.NumberFormatException: Invalid double: ""
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseDouble(StringToReal.java:267)
at java.lang.Double.parseDouble(Double.java:301)
at com.example.android.budgeit10.incomePage$1.onClick(incomePage.java:34)
at android.view.View.performClick(View.java:4785)
at android.view.View$PerformClick.run(View.java:19884)
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:5343)
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:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
You need to check if the EditText has text in it before trying to parse the (possibly) non-existing text as a numeric value. For example
String yearString = perYearAmount.getText().toString();
if (!"".equals(yearString)) {
year = Double.parseDouble(yearString);
}
Note that I create a temporary variable yearString in order to avoid typing and executing perYearAmount.getText().toString() twice.
Use TextUtils.
totalButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TextUtils.isEmpty(perYearAmount.getText().toString())||
TextUtils.isEmpty(perMonthAmount.getText().toString())||
TextUtils.isEmpty(perWeekAmount.getText().toString())) {
addResult.setText(""); // if any of the fields is empty, add nothing to textview
} else {
year = Double.parseDouble(perYearAmount.getText().toString());
month = Double.parseDouble(perMonthAmount.getText().toString());
week = Double.parseDouble(perWeekAmount.getText().toString());
sum = year + month + week;
addResult.setText(Double.toString(sum));
}
}
});
The crash is caused by a NumberFormatException, which is thrown by the Double.parseDouble() method when the argument is not a parsable double. In your error log, this appears as an empty String:
java.lang.NumberFormatException: Invalid double: ""
To get around this, you could surround any Double.parseDouble() calls in a try/catch block:
try {
Double.parseDouble(anEditText.getText().toString());
} catch (NumberFormatException nfe) {
//anEditText does not contain a parsable Double
}
Edit:
To create an example using your code:
double year = 0;
double month = 0;
try {
year = Double.parseDouble(perYearAmount.getText().toString());
month = Double.parseDouble(perMonthAmount.getText().toString());
} catch (NumberFormatException nfe) {
Toast.makeText(this, "Please enter a valid number and try again", Toast.LENGTH_SHORT).show();
return;
}
double sum = year + month;
//etc...
I am new to android programming and I am trying to make an app that splits a bill between people. But something about my integers are wrong. I know this because in my logcat it says "Caused by: java.lang.NumberFormatException: Invalid int: ""
Here is my MainActivity.java
public class MainActivity extends Activity {
public double x;
public double y;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Button
Button btn = (Button) findViewById(R.id.button);
//EditText
EditText nop = (EditText) findViewById(R.id.editText);
EditText cob = (EditText) findViewById(R.id.editText2);
//Getting the strings
try{
x = Double.valueOf(nop.getText().toString());
} catch (NumberFormatException) {
x = 0;
}
try{
y = Double.valueOf(cob.getText().toString());
} catch (NumberFormatException) {
y = 0;
}
String textX = nop.getText().toString();
// if variable contains valid number:
if (textX != null && textX.length() > 0)
x = Double.valueOf(); // exception thrown by method
else
x = 0;
//TextView
final TextView tv = (TextView) findViewById(R.id.textView);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double z = x / y;
tv.setText((int) z);
}
});
}
}
Here is the logcat:
08-19 07:30:28.452 16070-16070/com.elie.billsplitter E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.elie.billsplitter, PID: 16070
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.elie.billsplitter/com.elie.billsplitter.MainActivity}: java.lang.NumberFormatException: Invalid int: ""
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
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)
Caused by: java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at com.elie.billsplitter.MainActivity.onCreate(MainActivity.java:25)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
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)
Looking to your exception:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.elie.billsplitter/com.elie.billsplitter.MainActivity}: java.lang.NumberFormatException: Invalid int: ""
The error is in this piece of code
//Getting the strings
x = Integer.parseInt(nop.getText().toString());
y = Integer.parseInt(cob.getText().toString());
Why? nop.getText().toString().equals("") or cob.getText().toString().equals("").
How to avoid? You must be sure you get a valid String from this EditText because if them are empty or does not contain an equivaloent double String you will have a NumberFormatException.
Solution?Best ways will be:
adding a validation to EditText to get only valid Strings.
Convert the value if NumberFormatException is thrown.
try{
x = Double.valueOf(nop.getText().toString());
} catch (NumberFormatException e) {
x = 0;
}
try{
y = Double.valueOf(cop.getText().toString());
} catch (NumberFormatException e) {
y = 1; // division / 0 will throw NaN
}
ADD-ON:
Why I dont use Integer.parseInt()??
If you create doubles you cannot parse ints because you will lose accuracy, and, for example in java (int) 1 / (int) 3 = 0 or (int) 10 / (int) 3 = 3 so use Double::valueOf()
x = Double.valueOf(nop.getText().toString());
y = Double.valueOf(cob.getText().toString());