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.
Related
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
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
Can anybody tell me why this isn't working? I want it to load a specific layout depending on what page is loaded. The if clause seems to be faulty. It's always going to the else.
wordArray = getResources().getStringArray(resId);
int resIdBack = getResources().getIdentifier(wordArray[5], "drawable", "com.bobgle.libretto");
// If Background Image is dark use light theme, if not use dark theme.
if(wordArray[5] == "libretto"){
view = inflater.inflate(R.layout.activity_fragment_dark, container, false);
} else {
view = inflater.inflate(R.layout.activity_fragment_light, container, false);
}
When comparing strings in Java you should use the equals method.
When using equal is good to remember that it can cause nullpointer if the object you are using equals on are null (duh!) so if you got a fixed string, that can't be null always use that first.
"libretto".equals(wordArray[5]) //Can't cause nullpointerexception.
wordArray[5].equals("libretto") //Can cause nullpointerexception if wordArray[5] is null.
This SO question explains why that is the case.
Our app has several fragments. In one of them user fills several TextEdit fields. When he finishes he presses a button in the ActionBar to save the data. The Action just calls a private method named "saveData" that fetches all data from the fields and submit it to our server.
We have many stack traces from our users showing that getView() returns null in method saveData, but for just a small part of them. For most of them there is no problem at all. We cant reproduce the problem and we cant understand what might be causing it. The code is pretty simple:
View vw = this.getView();
EditText et;
et = (EditText)vw.findViewById(R.id.editEmail);
String email = et.getText().toString().trim();
et = (EditText)vw.findViewById(R.id.editPassword);
String password = et.getText().toString().trim();
The action is added in osResume, see below:
public void onResume() {
super.onResume();
MainActivity act = (MainActivity)this.getActivity();
act.bar.removeAllActions();
act.bar.addAction(new SaveAction());
}
Any ideas? How can we reproduce it?
Can you tell from your logs whether the problem is always for the same users / devices ?
I see from the code that you have submitted that the view is in the same fragment - is that actually the case ?
It's POSSIBLE that a fragment no longer in view can have their view destroyed in order to free up resources. e.g.
getView() returns null
If I suspected that this might be the case then I would attempt to recreate the problem on a phone / tablet / emulator with limited resources.
Good luck !
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