getApplicationContext causes a NullPointerException - java

I just started trying to learn development in Android Studio, and while I was trying to make my first application work ( I'm also new to stackoverflow, so sry if the way I present this thread isn't satisfactory ), I ran into a brickwall of nullpointerexceptions.
I just wanted to make a button that displays a text message (toast) when I click on it.
It probably is a typical newbie mistake, but I just can't seem to find out what the problem is exactly. Can somebody enlighten me please?
The relevant part of the error message as far as I can tell is:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
Heres the code:
public class FirstActivity extends AppCompatActivity {
private static FirstActivity instance;
Context context = getApplicationContext();
CharSequence text = "A text that appears for a short time";
int duration = Toast.LENGTH_SHORT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
public void buttonclick(View view){
Toast toast1 = Toast.makeText(context,text,duration);
}
}
and the xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.rayaqin.myfirstandroidapp.FirstActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="259dp"
android:text="Press Me"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Me"
tools:layout_editor_absoluteX="-498dp"
tools:layout_editor_absoluteY="527dp"
android:onClick="buttonclick"/>
</android.support.constraint.ConstraintLayout>

getApplicationContext() is an instance method and you're trying to call it from a static context.
Simply move it to onCreate().
But Activity doesn't need application Context as itself it extends it. Use this in
Toast toast1 = Toast.makeText(this,text,duration);
and to show it
Toast.makeText(this,text,duration).show();

You should do that assignment in onCreate().
And use context = this;.

Just replace your toast with
Toast toast1 = Toast.makeText(this,text,duration).show();

Related

The button of a Android project simply does not work [duplicate]

I am developing a small project of test, and I wrote the following code.
I already created in the xml file, a button with id called "registerBtn".
I erased the imports of this source code to shorten space of this source code.
In the java file, I created a variable called mRegisterBtn, in the type of Button.
Inside the method called onCreate(Bundle savedInstanceState) the mRegisterBtn receives the method called findViewById(R.id.registerBtn);
However, in the mRegisterBtn.setOnClickListener, the part of new View.OnClickListener appears in gray color, and it is not working when trying to test this code.
This image shows what I really mean. Please, perceive that the the part of new View.OnClickListener appears in gray color. It means a error. But trying to compile, this code runs, but the button simply does not work.
Can anyone know how to fix this error, please?
public class Register2 extends AppCompatActivity {
Button mRegisterBtn;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register2);
mRegisterBtn = findViewById(R.id.registerBtn);
mRegisterBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Testing", Toast.LENGTH_LONG).show();
}
});
}
}```
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#007FFF"
tools:context=".Register">
<Button
android:id="#+id/registerBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#color/white"
android:text="Register"
android:textColor="#color/black"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.499" />
</androidx.constraintlayout.widget.ConstraintLayout>
Try using the Activity itself as the Context.
If you want a log, then make one
If you want the gray to go away, use a lambda
Log.d("REGISTER", "Setting listener");
mRegisterBtn.setOnClickListener(view -> {
Log.d("REGISTER", "Clicked!");
Toast.makeText(Register2.this, "Testing", Toast.LENGTH_LONG).show();
});

Add an ImageView statically in Android Studio

I want to change the resource of an image view from a variable in android studio.
Let me explain you, i have first activity "selector activity" which has 21 images, on every image click, a variable god_name is changed to the particular god, now i am sending that variable using putExtra, now i want that to change the resource of an ImageView in MainActivity depending on the variable, for example if the variable is "two", then i want to change the resource to "R.drawable.two".
Something like that, I have some experience in python so I used f strings there, here can I do something?
MainActivity.class
(Note-I have not Included imports so the code is allowed to be uploaded.)
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String god_name = getIntent().getExtras().getString("chosen_god").toString();
ImageView god = findViewById(R.id.god);
god.setImageResource();
}
}
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black"
tools:context=".MainActivity">
<ImageView
android:id="#+id/god"
android:layout_width="413dp"
android:layout_height="496dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.666"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
app:srcCompat="#mipmap/hanuman" />
</androidx.constraintlayout.widget.ConstraintLayout>
I can use multiple if conditions and switch case statement but that would be so much large as I would have to write it 21 times so it is very difficult!
Thanks in advance for anyone kind of help!
That sounds like you need to use the resources.getIdentifier() to make this work.
I wrote once an answer to a related topic: https://stackoverflow.com/a/4865350/180538
Anyway what you need is to pass the name of the resource and then resolve the identifier to use it. So something like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// make sure that god_name is the name of the resource, so AFTER R.mipmap.[resourceName]
// so for R.mipmap.two you need to pass "two" as "chosen_god" extra
String god_name = getIntent().getExtras().getString("chosen_god").toString();
ImageView god = findViewById(R.id.god);
int resId = getResources().getIdentifier(god_name, "mipmap", getPackageName());
god.setImageResource(resId);
}

why might findViewById() crash relativeLayout init command?

I am writing a Chess app in Android Studio 3.0, and I want a PopupWindow to appear when the user clicks btnPopUpWindow, a button on the Chessboard layout. Here' the chessboard layout XML:
activity_chessboard.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="me.androidchess.MainActivity"
android:id="#+id/chessboardlayout">
<Button
android:id="#+id/popUpButton"
android:layout_width="172dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginTop="8dp"
android:text="Pop Up Menu"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginRight="8dp" />
</android.support.constraint.ConstraintLayout>
The XML layout above is loaded by Chessboard.java. Obviously, Chessboard would be the parent of the popup window, which is why I would want to use a RelativeLayout reference for the popup to see Chessboard.
Chessboard.java
public class Chessboard extends Activity {
Button btnPopUpWindow;
RelativeLayout relativeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chessboard);
btnPopUpWindow = findViewById(R.id.popUpButton); // This works
relativeLayout = (RelativeLayout)findViewById(R.id.chessboardlayout); // <--- CRASHES HERE!!!
btnPopUpWindow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// https://www.youtube.com/watch?v=wxqgtEewdfo
gameTextArea.setText("Pop up Menu appears...");
}
});
}
Its that relativeLayout = (RelativeLayout)findViewById(R.id.chessboardlayout); line which crashes the app.
I am assuming that findViewById() is failing to locate the ID chessboardlayout, but I can't figure out why. I can't find the R.id directory in Android Studio, but I notice that chessboardlayout appears in the drop-down options when I type out the command. Plus I see the Id when I walk through the debugger. So I assume the Id has been properly filed.
But when I follow the debugger, the findViewById() call returns null, which can't be good. Specifically, an "Unable to start activity" exception is thrown by performLaunchActivity() in ActivityThread.java No idea how that is happening.
I've read through the other findViewById() threads that pop up in StackOverview searches, and a lot of those issues seem to revolve around the item returned by findViewById() not matching the local variable Button x = findViewById(R.id.TextFieldHere); for example. But that doesn't seem to be the case here... unless I don't understand how a RelativeLayout is supposed to work here...? Any advice/insight is appreciated, thank you.
Your R.id.chessboardlayout is an android.support.constraint.ConstraintLayout so you cannot cast it to RelativeLayout or it will cause ClassCastException.
So if you still want to use RelativeLayout as root of your layout, change your activity_chessboard.xml to this:
activity_chessboard.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="me.androidchess.MainActivity"
android:id="#+id/chessboardlayout">
<Button
android:id="#+id/popUpButton"
android:layout_width="172dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginTop="8dp"
android:text="Pop Up Menu"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginRight="8dp" />
</RelativeLayout>
Then in your activity use the findViewById() normally.
setContentView(R.layout.activity_chessboard);
btnPopUpWindow = findViewById(R.id.popUpButton);
relativeLayout = (RelativeLayout)findViewById(R.id.chessboardlayout);

How to solve error: Could not find method onClick(View) in a parent or ancestor Context for android:onClick

I have seen that there's been some similar questions but the answers to those haven't helped me so far. The full error:
java.lang.IllegalStateException: Could not find method onClick(View)
in a parent or ancestor Context for android:onClick attribute defined
on view class android.support.v7.widget.AppCompatButton with id
'button_random'
The class (StartActivity.java):
public class StartActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
}
public void onClick(View v) {
Log.d("DEBUG", "CLICKED " + v.getId());
}
}
The XML (activity_start.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Random Game"
android:id="#+id/button_random"
android:layout_gravity="center_horizontal"
android:onClick="onClick" />
</LinearLayout>
I have added the activity to the AndroidManifest.xml. I have similar activities that work in the same way and I don't have any problems with those...
Does anyone see something where I am missing something or have made a mistake?
In my case I missed closing bracket at the end.
android:onClick="#{(v) -> CommentHandler.selectGallery(v)".
It should be like this.
android:onClick="#{(v) -> CommentHandler.selectGallery(v)}".
Please rename onClick method to anything other than that, Android thinks you are calling the internal onClick from View.java exposed via OnClickListener interface
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Random Game"
android:id="#+id/button_random"
android:layout_gravity="center_horizontal"
android:onClick="myOnClick" />
and in your Activity
public class StartActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
}
public void myOnClick(View v) {
Log.d("DEBUG", "CLICKED " + v.getId());
}
}
You can check the View documentation here
I had the same problem and in my case, I changed Button in XML to android.support.v7.widget.AppCompatButton and it worked.
Code with Error:
<Button
.... />
Fixed Code:
<android.support.v7.widget.AppCompatButton
.... />
You need to change android.support.v7.widget.AppCompatButton
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Random Game"
android:id="#+id/button_random"
android:layout_gravity="center_horizontal"
android:onClick="onClick" />
</LinearLayout>
I had the same issue, in my case I have 2 activities using the same layout so when I changed the OnClick event name it will crash in other activity try to check the setContentView layout in the crashing activity

setOnClickListener never fired - Android/Eclipse

I'm having a problem that seems to be quite common but none of the solutions on here so far have helped me.
I am trying to add a simple button to my app which will start a new activity when clicked.
The button displays ok in my app but when I touch it nothing happens.
My problem is that setOnClickListener() is never fired - when I debug it just skips right over it and no logging message is displayed in LogCat.
Here is my layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="sarah.tourapplication.MainActivity"
tools:ignore="MergeRootFrame" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment" />
<RelativeLayout
android:id="#+id/belowlayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal" >
<Button
android:id="#+id/cam_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:text="Take Picture" />
</RelativeLayout>
And this is my activity:
public class MainActivity extends FragmentActivity implements OnClickListener {
Button camButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent locationUpdatesIntent = new Intent(this, GetLocationUpdates.class);
startActivity(locationUpdatesIntent);
camButton = (Button)findViewById(R.id.cam_button);
//add button functionality
camButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("TEST", "Button was clicked.");
Intent cameraIntent = new Intent(getApplicationContext(), CameraActivity.class);
startActivity(cameraIntent);
}
});
}
Can anyone tell me where I've gone wrong? I'd really appreciate any pointers.
I'm using Eclipse on Windows 8 and everything I'm using is up to date.
Thanks in advance!
Thanks for all the help. It turns out that I was calling the click handler in the wrong activity.
Try removing the lines
Intent locationUpdatesIntent = new Intent(this, GetLocationUpdates.class);
startActivity(locationUpdatesIntent);
It looks like you're starting a different activity before you actually get to the point where you're adding the listener...
Sorry I'm on my phone but try to use setOnClickListener(this); and override the onClick method. Inside the onClick method use if (view == yourview) to do w/e you want. :). If it still doesn't work try removing the startActivity method at the very beginning of your codes

Categories

Resources