NPE if no radio button checked in RadioGroup - android

This code
val vehicleTypeRadioButtonID = binding.rgVehicle.getCheckedRadioButtonId()
val vehicleTypeSelectedRadioButton: View = binding.rgVehicle.findViewById(vehicleTypeRadioButtonID)
will return a NullPointerException error at the second line:
java.lang.NullPointerException: binding.rgVehicle.findViewById(vehicleTypeRadioButtonID) must not be null
if no radio button under it is selected. The problem is, when I tried to put the code inside
if (vehicleTypeRadioButtonID != null){}
Android Studio will warn that Condition 'vehicleTypeRadioButtonID != null' is always 'true'. Trying to do something like
if (binding.rgVehicle.findViewById(vehicleTypeRadioButtonID) != null){}
is also not possible since Android Studio will complain a syntax error with Not enough information to infer type variable T.
So how do I avoid NPE if nothing is selected? Without resorting to put the codes inside try catch of course

Related

How to get Sharedprfs String value to spinner..? ANDROID

I have given this to save data with sharedpreference
so I want to get value to a spinner, here I have given this
SharedPreferences spf = getSharedPreferences("myprfs", Context.MODE_PRIVATE);
String ret = spf.getString("ctyp","");
Here am getting the value to a String, I want to assign a same value to a spinner.
for(int i=0;i<2;i++)
if(ret.equals(spinner.getItemAtPosition(i).toString())){
spinner.setSelection(i);
break;
}
I am getting this error
'java.lang.Object android.widget.Spinner.getItemAtPosition(int)' on a null object reference
Can any one suggest me correct ans..
Your spinner should be null. Set a breakpoint to confirm that. Remember to run in debug mode to make the breakpoint to "break"
Most probably:
not done a findViewById
using ButterKnife and forgot to bind it
If you've done the above, but spinner is still null, in which lifecycle method are you running above code? Maybe you're trying to touch the UI before it's loaded

empty EditText caused by wrong view?

I'm new to android studio and programming. I create second table to my database and have almost identical onClickListener class first one work perfect but second give me error. EditText .getText().toString() is empty so I can't convert it to dobule. I think this problem may be caused by View but I dont know java that well and I cant find solution.
EDIT: I manage to solve this problem by adding AlertDialog to my second OnClick listener. This is not exactly what I want but it works.
Could you try setting the input type on the edittext as numberDecimal
android:inputType="numberDecimal"
That way, the user will have to input decimal number always if thats what you are expecting the user to enter.
Also, you could do a null check
if(stringWzrost != null && !stringWzrost.trim().equals("")) {
bmiWzrost = Double.valueOf(stringWzrost);
}
Right now I see that its commented out.

Android Exception: UnknownFormatConversionException

Hi I am setting some text inside a RobotoText that is positioned inside of a ViewHolder I am calling it like this:
viewHolder.txtSimilarAds.setText((((Property) ads.get(position)).getSimilar_items_count() == 1 ? context.getString(R.string.ad_data_similar) : context.getString(R.string.ad_data_similar_plural, ads.get(position).getImagesCount())));
However (sometimes NOT always)for some reason I keep getting this error exception UnknownFormatConversionException and it points to this line inside of the class. What could be the problem? Am I doing anything wrong?
Check that the string in R.string.ad_data_similar_plural contains a valid placeholder for an integer. It should be something like "Here is my number: %d".
String format specification
As an aside, one-liner like these are harder to understand, and make debugging more difficult. A more readable approach would have given the erroneous line more easily:
String similarAdsText;
Property adsProperty = ads.get(position);
if (adsProperty.getSimilar_items_count() == 1) {
similarAdsText = context.getString(R.string.ad_data_similar);
}
else {
similarAdsText = context.getString(R.string.ad_data_similar_plural, adsProperty.getImagesCount());
}
viewHolder.txtSimilarAds.setText(similarAdsText);
You are trying too many methods in single line try splitting it. The problem looks like you are comparing Property object with 1 which is wrong.
(Property)ads.get(position)).getSimilar_items_count() == 1
change this to
Property property = (Property) ads.get(position));
property.getSimilar_items_count() == 1

Checking if part of a bundle exists in Android

I am working on an application, and from a list view I create a bundle that includes the item selected and the previous item. What I need to determine is if the previous item actually gets bundled through. If it exists, I want the information, but if it doesn't exist, then I need to set my text views to reflect that. But I get a null pointer exception if it doesn't exist when trying to load the receiving activity (the bundling activity does not cause the crash as I found during debugging - I get to the point where I'm testing for the data in the bundle before it crashes). So I've included the code from the receiving activity.
Bundle evmBundle = this.getIntent().getExtras();
final EVMData evm = (EVMData) evmBundle.getSerializable("evm");
final Project project = (Project) evmBundle.getSerializable("project");
if (!evmBundle.getSerializable("prvEVM").equals(null)){
final EVMData prvEvm = (EVMData) evmBundle.getSerializable("prvEVM");
edtPrvAC = (TextView) findViewById(R.id.edtPrvEVMAC);
edtPrvAC.setText(prvEvm.getAc().toString());
}
else{
edtPrvAC = (TextView) findViewById(R.id.edtPrvEVMAC);
edtPrvAC.setText("0");
}
I know something is getting passed through in the bundle for "prvEVM" because it showed up as part of the bundle in the debugger.
I also tried pulling it out of the bundle first and then trying to compare it. After pulling it out of the bundle, prvEvm is null (looking at the variables in the debugger), so I thought something like this might work:
if (!prvEvm.equals(null)){
edtPrvAC = (TextView) findViewById(R.id.edtPrvEVMAC);
edtPrvAC.setText(prvEvm.getAc().toString());
}else{
edtPrvAC = (TextView) findViewById(R.id.edtPrvEVMAC);
edtPrvAC.setText("0");
}
But I get a NullPointerException because prvEvm is Null. So I tried flipping the if test around, but got the same results. I should note that no matter how I set this up, if prvEvm is not null, all configurations here work - the requested data is put in the TextView. Basically, I need to be able to get around this null pointer exception. I know the object is null, I want to test for that so that if it is, that object isn't used. It will only be null once.
Don't use equals(null) as you call a method (equals) on a null object. Instead, compare to null:
if (prvEvm != null){
besides, equals(null) always returns false.

How can I " printf " variables in android to check my code?

I have a problem which i'm trying to solve, I've been trying to fetch my data from an intent using mRowId below which I've been constantly returned a NullPointerException from fetchDrug() on LogCat.
Doing some troubleshooting using debugging, I've realized my variable mRowId is not Null and is pointing to something but I don't know what its pointing.
How can i check what is my variable mRowId pointing ? Or will normally such variables be gibberish that is incomprehensible?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drug_info);
//Defining the views
mDrugText = (TextView) findViewById(R.id.drug);
mContentText = (TextView) findViewById(R.id.content);
Bundle extras = getIntent().getExtras();
mRowId = extras.getLong(DrugsDbAdapter.KEY_ROWID);
if(mRowId == null) {
Log.e("mRowId is null", "ok");
} else {
Cursor drug = mDbHelper.fetchDrug(mRowId);
//Managing Cursor to pluck values to display
startManagingCursor(drug);
mDrugText.setText(drug.getString(drug.getColumnIndexOrThrow(DrugsDbAdapter.KEY_DRUG)));
mContentText.setText(drug.getString(drug.getColumnIndexOrThrow(DrugsDbAdapter.KEY_CONTENT)));
}
}
Instead of printf, use the existing log functionality in the SDK.
Output will appear in the logcat window of Eclipse (probably best option, since it's reasonably real-time and you can filter the display), or you can pull the logs off the device/emulator manually.
For example:
Log.i ( "MyApp", "Drug = " + drug.getString ( drug.getColumnIndexOrThrow ( DrugsDbAdapter.KEY_DRUG ) ) );
Use the debug function of eclipse and walk trough the code step by step. It gives the values of all variables.
Often objects will have a "toString()" method to represent the object in a human readable form; you could pass that into a Log.e() call. In your case, it appears to be a numeric (long) rather than an object, so you can directly display it in your log.
Once you know the row id you're trying to fetch, you could verify that its valid by examining your database (using the sqlite3 command which is built into the emulator, or extracting the file to your development machine and using any of myriad sqlite tools).
If the row id is valid, I'd suggest looking into your database helper code to see how the fetchDrug() method is using it. It's possible the null pointer has nothing to do with the parameter, but with other items in that method.
Here are a couple of options to consider:
Option 1: Set a breakpoint in onCreate in Eclipse. You can find more detail on debugging Android apps in Eclipse here: http://developer.android.com/guide/developing/debugging/debugging-projects.html
Option 2: Add Log statements to your code and view the output in logcat. You can read more about logging in Android here: http://developer.android.com/reference/android/util/Log.html

Categories

Resources