java.lang.NullPointerException at android.content.ContextWrapper.getPackageName ANDROID - android

Hey I want to start an Activity from my MainActivity but not in the oncreate method.
public void awe()
{
Intent myIntent = new Intent(MainActivity.this, Awesome.class);
MainActivity.this.startActivity(myIntent);
}
Another class calls the method awe() and what I get is a crash and
05-25 04:06:51.034: E/AndroidRuntime(7161): FATAL EXCEPTION: main
05-25 04:06:51.034: E/AndroidRuntime(7161): java.lang.NullPointerException
05-25 04:06:51.034: E/AndroidRuntime(7161): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:151)
05-25 04:06:51.034: E/AndroidRuntime(7161): at android.content.ComponentName.<init>(ComponentName.java:106)
05-25 04:06:51.034: E/AndroidRuntime(7161): at android.content.Intent.<init>(Intent.java:2895)
05-25 04:06:51.034: E/AndroidRuntime(7161): at package name.MainActivity.awe(MainActivity.java:215)
Someone knows what I can do?
MainActivity
public class MainActivity extends Activity implements OnClickListener {
// (variable stuff)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonE = (Button) findViewById(R.id.buttonEASY);
buttonM = (Button) findViewById(R.id.buttonMED);
// here I do all that button stuff for the layout
}
public void onClick(View arg0) {
System.out.println("click");
if (arg0==buttonE) {
int checkedRadioButton = radioGroup1.getCheckedRadioButtonId();
String radioButtonSelected = "";
switch (checkedRadioButton) {
case R.id.radio0 : radioButtonSelected = "radiobutton1";
Toast.makeText(getApplicationContext(), "Easy, 10 selected", Toast.LENGTH_SHORT).show();
setContentView(R.layout.raten);
// Button stuff, again.
}
public void awe()
{ Intent tutorial = new Intent(MainActivity.this, Awesome.class);
if (tutorial != null) { startActivity(tutorial); }
}
Easy.java
Nothing important here, the place where I refer to awe():
if (s==max+1){System.out.println("AWESOME!"); MainActivity mA = new MainActivity(); mA.awe();}
Awesome.java
public class Awesome extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.awesome);
}
I hope I now posted everything that is important

The problem probably is that MainActivity has not been fully initialized yet when you are calling the awe() method, and the internal Context of the Activity is null.

Things to consider with Android Activities:
Do you have your classes that extend Activity defined in the AndroidManifest.xml?
Are you aware of your Context when using Intents?
For calling intents, always check for null, if you are calling via packagename:
Intent mTutorial = new Intent(MainActivity.this, TutorialActivity.class);
this.startActivity(mTutorial);
Your problem was simply trying to call your "awe()" method was in another Activity that did not have the correct Context for your MainActivity: http://developer.android.com/reference/android/content/Intent.html.
Android Intent requires a "Context" and a "Class".
Update: Here is another post that will help:
Launch an application from another application on Android
Regards,

I got the same error, which took me a while to figure it out.
Like #csgero mentioned, my problem was that the activity I tried to start was not initialized.
It means errors happen before onCreate is called. And it turned out that there was a error in the codes part where I defined the variables in the to-be-called activity. Good luck!

The problem probably is that MainActivity is null. in my case, the activity destroyed when run abvoe code. so the internal Context of the Activity is null.

Related

Calling findViewById() before setContentView() causes NullPointerException but not always? [duplicate]

This question already has answers here:
NullPointerException with findViewById in variable definition
(1 answer)
findViewByID returns null
(33 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
Well i get a NullPointerException when i I call findViewById() to access a Button. I think I understand why I'm getting this error but there are some questions I have unsolved in my head.
Well I think I'm getting this error because I moved the findViewById() calls from inside the onCreate() method to class scope, outside of all the methods.
So now I'm initializing my Button's and EditText's outside the onCreate() method.
Well if I understand correctly, this is happening(Null error) cause the setContentView() method is called after the findViewById() method, so that's why it throws an Exception.
But what I don't understand is that I have done the same thing in my second activity and works well without any null exception. And I'm initializing my Buttons etc outside the onCreate() method!
It does confuse me a little bit. Any help clearing this in my head would be much appreciated.
First Activity
public class FirstActivity extends AppCompatActivity {
private Button signUpButton= findViewById(R.id.lo_signUpButton);
private Button loginButton = findViewById(R.id.lo_loginButton);
private EditText username= findViewById(R.id.lo_usernameText);
private EditText password= findViewById(R.id.lo_passwordText);
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set view
setContentView(R.layout.activity_login);
Log.i(TAG,"Create "+formatter.format(new Date()));
//listeners
signUpButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(LoginActivity.this, SignUpActivity.class));
finish();
}
});
}
Second Activity
public class SecondActivity extends AppCompatActivity {
private EditText username = findViewById(R.id.su_username);
private EditText password = findViewById(R.id.su_password);
private TextView errorText= findViewById(R.id.su_error_msg);
private Button signUpButton=findViewById(R.id.su_signupButton);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set view
setContentView(R.layout.activity_signup);
Log.i(TAG,"Create");
//listeners
Button backButton = findViewById(R.id.su_backButton);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(SignUpActivity.this, LoginActivity.class));
Log.i(TAG,"Going Back ");
finish();
}
});
You can't use this initialization:
public class SecondActivity extends AppCompatActivity {
private Button signUpButton= findViewById(R.id.lo_signUpButton);
//....
}
Use:
public class SecondActivity extends AppCompatActivity {
private Button signUpButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set view
setContentView(R.layout.activity_signup)
signUpButton= findViewById(R.id.lo_signUpButton);
//...
}
}
In the 2nd Activity you are doing something different:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
Button backButton = findViewById(R.id.su_backButton);
//...
}
and it is correct since you declaring and initializing the backButton with the findViewById method inside the onCreate after the setContentView call.
In the 1st Activity you are setting the listener with signUpButton.setOnClickListener but the signUpButton is not initialized (since it is outside the onCreate method)
Also in the 2nd Activity the other buttons that are wrongly initialized are not used in the OnCreate method.
In second activity, you have not used the buttons that are wrongly initialized, once you use them, it will cause exception too.
You have used backButton which is correctly initialized.
The answer is quite simple. the global variables get initialized before setContentView() is called, meaning what findViewById() will return null. findViewById() returns the view if found or null. As you didn't call setContentView yet, it cannot find the view you want.
The global variables in FirstActivity as well as SecondActivity are all null.
The difference between FirstActivity and SecondActivity is, that you don't access any global variable in SecondActivity.
The only view you used in SecondActivity is backButton, which you retrieved after calling setContentView, so of course, no NullPointerException will be thrown.
Always declare the variable as globally and initialize it in onCreate(). Even better, try to avoid global variables and pass them though method parameters.

how to use intent caller on button click properly?

actually I am bit confused on some thing which is working in one scenario very well but in other scenario that is not working fine so I am here to explain my problem to identify the wrong move made by me, if any on will identify the problem please mention it. thank you.
working fine:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.distance_demo_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListViewClass.class);
intent.putExtra(ListViewClass.EXTRAS_TARGET_ACTIVITY, Distance.class.getName());
startActivity(intent);
}
});
NOt working fine:
scan = (Button) view.findViewById(R.id.scan);
scan.setOnClickListener(startListener);
}
//Create an anonymous implementation of OnClickListener
private OnClickListener startListener = new OnClickListener() {
public void onClick(View v) {
Toast.makeText(view.getContext(),"Scanning", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, ListViewClass.class);
intent.putExtra(ListViewClass.EXTRAS_TARGET_ACTIVITY, Distance.class.getName());
startActivity(intent);
}
}
now the problem is in this line
Intent intent = new Intent(MainActivity.this, ListViewClass.class);
when I use this line in this scenario it shows me error on this line:
Error: 'The constructor Intent(MainActivity, Class<ListViewClass>) is undefined' please mention my problem if you are well aware of it.
use a global context variable glaboaly and use it.
Context myContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myContext = MyActivity.this;
}
and use myContext insted of MainActivity.this.
Im not sure whether it solve the problem, just try it out
When your calling Intent intent = new Intent(MainActivity.this, ListViewClass.class); inside MainActivity class. It will work fine. But when your not in Context of MainActivity class. i.e move to other class. This error will occur.
If you want to rectify, You can follow #jithu method. Otherwise store the context in Application class. And use it in anywhere.
In the first case you are overriding the method onClick().
If you override the method it's like you are declaring the function in your activity class.
This is the reason that you can call MainActivity.this
In the second case you are implementing the abstract method onClick(). You can't call MainActivity.this because your "MainActivity.this" is referencing to the current context and this isn't accessible from OnClickListener.class.

Android.Intent[Another activity]

My task: after button pressed, - second activity opening.
Problem: after button pressed, - "application closed unexpectedly".
LogCat said (short version):
04-10 21:25:24.968: E/AndroidRuntime(13032):
java.lang.RuntimeException: Unable to start activity
ComponentInfo{cat.dog.szosta/cat.dog.szosta.ListaOcenActivity}:
java.lang.NullPointerException
LogCat said (full version):
https://drive.google.com/file/d/0B1jfkoUAwYVhYmFvSzBmS2ZIaU0/edit?usp=sharing
First activity code (partial):
private Button mOcenyPrzycisk;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
mOcenyPrzycisk = (Button)findViewById(R.id.ocenyPrzycisk);
mOcenyPrzycisk.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intencja = new Intent(MainActivity.this, ListaOcenActivity.class);
startActivity(intencja);
}
}
);
}
Second activity(partial):
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_ocen);
mprzyciskWroc = (Button) findViewById(R.id.przyciskWroc);
/*line 28*/ mprzyciskWroc.setOnClickListener(
new View.OnClickListener()
{
public void onClick (View v)
{
finish();
}
}
);
}
P.S: second activity declared in AndroidManifest.xml
I was looking in (didn't help):
Using Intent in an Android application to show another activity
android intents
Thanks in advance!
There is an exception in your second activity. (in ListaOcenActivity)
NullpointerException is thrown at line 28 of your ListaOcenActivity class, in the onCreate method. Search the method generating nullpointer exception, and handle it.
The way you are starting the activity is fine.
04-10 21:25:24.968: E/AndroidRuntime(13032): Caused by: java.lang.NullPointerException
04-10 21:25:24.968: E/AndroidRuntime(13032): at
cat.dog.szosta.ListaOcenActivity.onCreate(ListaOcenActivity.java:28) //here you can see its in your 2nd activity
Problem is here: cat.dog.szosta.ListaOcenActivity.onCreate(ListaOcenActivity.java:28)
Looking at your LogCat (long version) it shows that the NPE is in class ListaOceanActivity line 28. Which means this code is correct. Look into that class instead.

Android: using getIntent() only within onCreate?

In Android (targeting APIs 14-16) I have a MainActivity and a NextActivity. There is no difficulty using intents to start NextActivity from within MainActivity if the getIntent() method is called inside the onCreate() block of NextActivity:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int data = 7;
...
Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("data", data);
startActivity(intent);
}
}
public class NextActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final int data = this.getIntent().getIntExtra("data", 7);
...
}
...
}
However, since the field data is being used inside an anonymous ("inner") class in NextActivity, I am compelled to declare it final.
I'd prefer not to declare fields final, and I can usually avoid doing so if I declare them at the beginning of the class, before onCreate() begins. But for some reason, the app crashes when NextActivity starts if the getIntent() statement appears (without the final keyword) outside of onCreate().
Any idea why?
You can't getIntent() before onCreate() -- there's simply no Intent available at that point. I believe the same is true for anything that requires a Context.
Your anonymous inner class can still call getIntent(), however, so you don't need to declare this as a variable at all.
According to your question what i understand is u don't want to declare data as final in next activity..Then y cant u try for this./
public class NextActivity extends Activity {
int data=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
data = this.getIntent().getIntExtra("data", 7);
...
}
...
}
Try this...

Call Public void

I have a public void in one class and I want to call it in another class when it creates but nothing seems to be working. here is the code of my first activity
public class activityone extends Activity {
public void actionC() {
//actions
}
Does anyone know how to call it in my second class?
In general, you need to have an instance of your activityone class in order to call an instance method.
To create an instance, you generally use a constructor like:
activityone a = new activityone();
a.actionC();
I'm not sure this is what you want though, because Activitys are generally created by the Android system itself and you should handle the onCreate method instead.
Here is what you can do:
public class activityone extends Activity {
/*public void actionC() {*/ //Instead on normal method, write your actions in onCreate()
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//actions
}
and in your second activity, do this:
Intent intent = new Intent(getApplicationContext(),activityone.class);
startActivity(intent);
Hope it helps !!!

Categories

Resources