How do I change this exception? - nullpointerexception

I'm new to Android Studio.
I'm getting
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String
com.alpha1.appname.rider.model.firebase.User.getName()' on a null
object reference.
Can anyone point me in the right direction. I can't seem to fix with the answers on the other similar questions.
\Here is the line that is producing the null pointer exception\
private void setDriverData() {
View navigationHeaderView = navigationView.getHeaderView(0);
TextView tvName = navigationHeaderView.findViewById(R.id.tvDriverName);
TextView tvStars = navigationHeaderView.findViewById(R.id.tvStars);
CircleImageView imageAvatar= navigationHeaderView.findViewById(R.id.imageAvatar);
tvName.setText(Common.currentUser.getName());
if(Common.currentUser.getRates() != null &&
!TextUtils.isEmpty(Common.currentUser.getRates()))
tvStars.setText(Common.currentUser.getRates());
if(Common.currentUser.getAvatarUrl()!=null &&
!TextUtils.isEmpty(Common.currentUser.getAvatarUrl()))
Picasso.get().load(Common.currentUser.getAvatarUrl()).into(imageAvatar);

This is the problematic line:
tvName.setText(Common.currentUser.getName());
The error message tells you that you cannot call getName of null. This means that Common.currentUser is null. Something being null means that it is not defined. Referring data members or calling methods of something that does not exist will yield this error. You can fix this issue by properly initializing Common.currentUser before that line executes, or defaulting it if it was not defined, like:
tvName.setText((Common.currentUser == null) ? "" : Common.currentUser.getName());

Related

Declare val without initialization in function

class Solution {
val message: String //error : val must be initialized or abstract
message = "love" //error : val cannot be reassigned
}
I understand what's happening in here - val cannot be reassigned.
So when I need val but can not initialize it i used to use by lazy
class Solution {
fun love(){
val message : String
message = "love" //this works
message = "hate" //this is error "val cannot be reassigned"
}
}
Here I can delcare val without initialization and later write codemessage = "love".what's happening here?
#deHaar noticed correctly that only var (mutable variable) is appropriate in your case.
The error you get is absolutely correct and expected.
what's happening here?
When you declare a read-only variable without initializing it you have to make sure that each execution path will have a value in this read-only variable. It means that Kotlin makes sure if your read-only variable was or was not initialized in every place it is used and raises errors if the variable is used inappropriately.
Here you have only one execution path as there are no when or if statements that can split execution into several possible paths.
class Solution {
fun love(){
val message : String
message = "love" // Kotlin knows that `message` was not yet initialized
message = "hate" // Kotlin knows that `message` was yet initialized! It does not allow to modify the value.
}
}
Here is what Kotlin documentation says:
... it is also possible (but discouraged) to split the declaration and the initial assignment, and even to initialize in multiple places based on some condition. You can only read the variable at a point where the compiler can prove that every possible execution path will have initialized it. If you're creating a read-only variable in this way, you must also ensure that every possible execution path assigns to it exactly once.
Example of an execution path
Using when or if statement you create two or more execution paths. Execution paths can be presented as a graph, I'll use #number as a node number. Example:
class Solution {
fun love(){
// #1
val message : String
if (System.currentTimeMillisec() % 2 == 0) {
message = "Not empty"
// #2
}
if (message.isEmpty) { // Error! Message could be not initialized at this point!
println("Empty message")
// #3
}
}
}
Looking at this example, that does not compile, we can calculate at least 3 execution paths.
#1 (none of the if statements was entered. All conditions are false)
#1 -> #2
#1 -> #3
Kotlin can calculate these paths and check if the message variable is initialized in every path it is used. As we can see, as soon as you reach the evaluation of the second if statement (in case of first and third paths) your program will crash because the message has no value. It has no address in memory and a computer which runs this program does not know how to get a value from an address that does not exist.
Now, let's modify this code to make it work:
class Solution {
fun love(){
// #1
val message : String
if (System.currentTimeMillisec() % 2 == 0) {
message = "Not empty"
// #2
} else {
message = ""
// #3
}
if (message.isEmpty) { // Error! Message could be not initialized at this point!
println("Empty message")
// #4
}
}
}
Execution paths:
#1 -> #2
#1 -> #3 -> #4
In this example, Kotlin is sure that the message read-only variable is initialized because there is a 100% chance that one of node 2 or node 3 will be executed. Right after the line where the message gets its initial value (initialized) Kotlin treats this variable as a read-only variable with a value.
Questions are welcome. I will try to simplify this answer.

Code analysis warning: CA1062 is really false positive?

In my code, I have a reference variable LogValidacionPagosDTO
public void InsertarArchivoXmlOk(ArchivoXmlDRO archivo, ref LogValidacionPagosDTO archivoRespuesta)
{
//Some code
}
When executing "code analysis" generates this warning
Warning CA1062
In externally visible method 'ArchivoXMLOperacion.ValidacionDuplicadosArchivoXmlFosyga(List<RegistroXmlFosygaDRO>, ref LogValidacionPagosDTO)',
validate local variable ''(*archivoRespuesta)'', which was reassigned from parameter 'archivoRespuesta', before using it.
Then try to validate the object as null
public void InsertarArchivoXmlOk(ArchivoXmlDRO archivo, ref LogValidacionPagosDTO archivoRespuesta)
{
if (archivoRespuesta == null || archivoRespuesta.DetalleRegistros == null)
throw new ExcepcionOperacion(HelperMensaje.Obtener(HelperCodigoMensaje.GEN_0003),
(int)CodigosHTTP.Error, archivoRespuesta, null);
//Some code
}
But this didn't solve the warning. I found this possible solution in Microsoft forum https://social.msdn.microsoft.com/Forums/en-US/fdb00899-c7ea-4e8e-b5f6-9768c2ac0001/ca1062-false-positive-in-externally-visible-method-xxx-validate-local-variable-x-which-was?forum=vstscode
But, I really need to know if this is a false positive, thks!

How to check auto_gcroot object for nullptr

I want to check if my C++/Cli managed auto_gcroot is null or not. Here's how I proceeded :
auto_gcroot<RefClassA^> m_a;
if (static_cast<RefClassA^>(m_a) != nullptr)
{
.....
}
The problem is that I get an error :
'No suitable conversion from 'auto_gcroot to object^ exists'
As I said in the comments, I'm not able to reproduce this on VS2012.
However, auto_gcroot has a get method that returns the object as a plain reference. You should be able to compare that to nullptr.
msclr::auto_gcroot<String^> m_a;
if (m_a.get() != nullptr)
{
// ...
}

findViewById() gives null pointer

I have below code which is giving null pointer exception in obtaining editText3 at line 4.
Intent intent = getIntent();
Double result = intent.getDoubleExtra(MainActivity.RESULT, 0);
setContentView(R.layout.activity_result);
EditText editText3 = (EditText)findViewById(R.id.editText3);
editText3.setText(Double.toString(result));
Can some please let me know what is the problem. I tried doing clean build but it didn't worked.
Thanks,
Rajan
You can double check if specify the wrong layout in setContentView() first.

AspectJ : can I neutralize 'throw' (replace it with log) and continue the method

In below code I want to neutralize the throw and continue the method - Can it be done ?
public class TestChild extends TestParent{
private String s;
public void doit(String arg) throws Exception {
if(arg == null) {
Exception e = new Exception("exception");
throw e;
}
s=arg;
}
}
The net result should be that, in case of the exception triggered (arg == null)
throw e is replaced by Log(e)
s=arg is executed
Thanks
PS : I can 'swallow' the exception or replace it with another exception but in all cases the method does not continue, all my interventions take place when the harm is done (ie the exception has been thrown)
I strongly doubt that general solution exists. But for your particular code and requirements 1 and 2:
privileged public aspect SkipNullBlockAspect {
public pointcut needSkip(TestChild t1, String a1): execution(void TestChild.doit(String))
&& this(t1) && args(a1) ;
void around(TestChild t1, String a1): needSkip(t1, a1){
if(a1==null) //if argument is null - doing hack.
{
a1=""; //alter argument to skip if block.
proceed(t1, a1);
t1.s=null;
a1=null; //restore argument
System.out.println("Little hack.");
}
else
proceed(t1, a1);
}
}
I think that generally what you want makes no sense most cases because if an application throws an exception it has a reason to do so, and that reason almost always includes the intention not to continue with the normal control flow of the method where the exception was thrown due to possible subsequent errors caused by bogus data. For example, what if you could neutralise the throw in your code and the next lines of code would do something like this:
if(arg == null)
throw new Exception("exception");
// We magically neutralise the exception and are here with arg == null
arg.someMethod(); // NullPointerException
double x = 11.0 / Integer.parseInt(arg); // NumberFormatException
anotherMethod(arg); // might throw exception if arg == null
Do you get my point? You take incalculable risks by continuing control flow here, assuming you can at all. Now what are the alternatives?
Let us assume you know exactly that a value of null does not do any harm here. Then why not just catch the exception with an after() throwing advice?
Or if null is harmful and you know about it, why not intercept method execution and overwrite the parameter so as to avoid the exception to begin with?
Speculatively assuming that the method content is a black box to you and you are trying to do some hacky things here, you can use an around() advice and from there call proceed() multiple times with different argument values (e.g. some authentication token or password) until the called method does not throw an exception anymore.
As you see, there are many ways to solve your practical problem depending on what exactly the problem is and what you want to achieve.
Having said all this, now let us return to your initial technical question of not catching, but actually neutralising an exception, i.e. somehow avoiding its being thrown at all. Because the AspectJ language does not contain technical means to do what you want (thank God!), you can look at other tools which can manipulate Java class files in a more low-level fashion. I have never used them productively, but I am pretty sure that you can do what you want using BCEL or Javassist.