Android: App crashes on calling toast from another class [duplicate] - java

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 2 years ago.
I am a novice Android Developer.
I have created a package-private class which extends Application, and contains the required code for specific functions. I basically want to display if the user-selected button is the correct choice or not, via a toast. Since I have to call this code for many activities, I just created a package-private class for it. However, on clicking the button, the app crashes. Please see the code given below for reference.
I cannot change the onClick method to non-static because if I do that, Android Studio shows an error, and if I change it to static, I am unable to use the method getApplicationContext(), because it is not accessible inside static blocks.
I think that using view.getContext() is causing the crash.
Is there any workaround, or a solution?
Your help would be greatly appreciated. Thanks :)
Here is the code for your reference.
activity.java:
public class activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(functions.select);
functions.makeLayout(expression, buttons);
}
}
Here is the code which crashes the app.
functions.java:
class functions extends Application {
private static int idx;
public static View.OnClickListener select=new View.OnClickListener() {
#Override
public void onClick(View view) {
int selected_index=(int) view.getTag();
if(selected_index==idx)
{
Toast.makeText(view.getContext(), "Correct.", Toast.LENGTH_LONG).show();
((Button) view).setTextColor(Color.GREEN);
}
else
{
Toast.makeText(view.getContext(), "Wrong.", Toast.LENGTH_LONG).show();
((Button) view).setTextColor(Color.RED);
}
}
};

Okay, I figured out that it was not view.getContext() but the line int selected_index=(int) view.getTag(); which was causing the crash. I solved it first making it into a string and then int by using the following code:
String selected_index=view.getTag.toString();
int sidx=Integer.parseInt(selected_index);

Related

Can't get a game loop to work in Android Studio

So I understand the basics of java programming but when I'm trying to use my little knowledge in android studio it make everything harder having classes and different files needing to be referenced. Coming from python, when making a simple game I would define different functions, then run them in a game loop like
while running:
or something similar. I know to define something in java you go like
public void Example() {}
but when I use this in java, when I try to run the program my game either instantly crashes or doesnt load anything.
The code at the moment is
public class MainActivity extends AppCompatActivity {
//Variables
Boolean running = true;
public int years = 0;
//Setup Year Counter
TextView textView = (TextView) findViewById(R.id.year_counter);
//Advance Button
public void advance() {
ImageButton button = (ImageButton) findViewById(R.id.advance);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
years += 1;
textView.setText("" + years + "");
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Game Loop
while (running) {
advance();
}
}
}
And this results in the app not opening.
Any help at all would mean a lot to me.
Thanks in advance :)
Although I don't actually see a crash, since you didn't really upload one, I can see why you might think your app wont work.
What you are doing constantly in the while loop is that you are only setting the button's click listener over and over again.
public class MainActivity extends AppCompatActivity {
//Variables
Boolean running = true;
public int years = 0;
//Setup Year Counter
TextView textView;
ImageButton button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// you set up your views once, after the layout is inflated
setUpViews();
// you initialize your buttons functionality
initClickEvents();
//Game Loop
while (running) {
// do other stuff
}
}
private void setUpViews() {
textView = (TextView) findViewById(R.id.year_counter);
button = (ImageButton) findViewById(R.id.advance);
}
private void initClickEvents() {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
years += 1;
textView.setText("" + years + "");
}
});
}
}
I'd recommend working with a game engine.
If you want to stick with java, libGDX is an option.
But if language (and IDE) doesn't matter, than a better option is Godot. The reason why I recommend Godot over some of the more popular game engines is because it's open source, 100% free and plus GDScript (godot's scripting language) is heavily influenced by python.
If you want to make you own game engine in java check out this: https://java-design-patterns.com/patterns/game-loop/#
Keep in mind that the while loop is calling the advance method. So every loop you are setting the view for button and then setting an OnClickListener for it. Not everything needs to be in the while loop.
You must implement (override) the render method (it is called in the game loop).
I suggest trying a complete example in the documentation.
``
#Override
public void render() {
ScreenUtils.clear(0, 0, 0.2f, 1);
advance();
...
``

Android app crashes when changing activity [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
New to Android developing, using Android Studio. The first activity of my app is a simple main menu with a "Start" and a "Quit" button. When i press the "Start" button, the app should take me to the second activity named "EncounterScreen". Instead, the app crashes. enter image description here. I am trying to display the current health of the player object, of class Player. Apparently the problem is with "TextView healthText=findViewById(R.id.healthText);". This is the error: "Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference"
public class EncounterScreen extends AppCompatActivity implements View.OnClickListener {
Player player=new Player();
TextView healthText=findViewById(R.id.healthText);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_encounter_screen);
Player player=new Player();
TextView healthText=findViewById(R.id.healthText);
healthText.setText("Health "+player.getCurrentHP());
Button attackButton=findViewById(R.id.attackBtn);
Button drinkPotButton=findViewById(R.id.drinkPotBtn);
Button runButton=findViewById(R.id.runBtn);
attackButton.setOnClickListener(this);
drinkPotButton.setOnClickListener(this);
runButton.setOnClickListener(this);
}
#SuppressLint("SetTextI18n")
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.drinkPotBtn:
player.drinkPotion(player);
healthText.setText("Health "+player.getCurrentHP());
break;
}
}
Make sure the TextView id that you are trying to find has the correct id. You are using "R.id.healthText"
Does the TextView in your activity_ecounter_screen have a different id?
Player player=new Player();
TextView healthText=findViewById(R.id.healthText);
I believe the issue is with the above line. remove =findViewById(R.id.healthText).

android onclick () not responding

I am new to android programming and trying to develop TIC TAC TOE game. I have created gameLogic() method and the problem is this that it is not working as it is expected to do, means on click of ImageView none of the images is getting displayed. Any help will be highly appreciated.
This is my code:
public class MainActivity extends AppCompatActivity {
public void gameLogic(View view) {
ImageView tappedView = (ImageView)view;
tappedView.setTranslationY(-3000f);
tappedView.setImageResource(R.drawable.black);
tappedView.animate().translationYBy(3000f).setDuration(500);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public void onClick (View view) {
ImageView tappedView = (ImageView)view;
tappedView.setTranslationY(-3000f);
tappedView.setImageResource(R.drawable.black);
tappedView.animate().translationYBy(3000f).setDuration(500)
Try changing the class name to onClick and go to XML the page where you designs the button and declare onClick method in the image view button.
All you have to do is let the design page know where the code is by providing a common name to look for which is on click.
Also you have to add an onClick listener which listens for the button to click as the code should know which button it is linked to.
So declare a setonclicklistener method on the button Id and you're set to go.
Also write the code within the override after the setting of the layout.
Hope you understood :)
If you're new try head first Android it'll be really helpful I know how struggling it is during the initial days.

User Input Time - Android [duplicate]

This is my first app and I'm having some trouble.
When I run the app it crashes and I don't know how to fix this error.
public class MainActivity extends AppCompatActivity {\
TextView outputBottom = (TextView)findViewById(R.id.output);
}
public void play_the_big_lie(View view) {
the_big_lie.start();
outputBottom.setText("ObamaCare, the big lie");
}
String literal in setText cannot be translated
This is not an error and you can safely ignore it (unless you need translation in your app).
It is simply a notification by Android Studio that you should be using a string resource file instead of a hard-coded string.
If I had to guess at the source of the issue since you did not post the logcat, it is this.
You can't use findViewById before setContentView because there is no view to "find".
Please try something like the following code
public class MainActivity extends AppCompatActivity {
private TextView outputBottom;
protected void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_main);
outputBottom = (TextView)findViewById(R.id.output);
}
There are two issues here. First, you can't use findViewById until you have "created" things and have a view to find things with, so as the previous answer you want to separate them.
public class MainActivity extends AppCompatActivity {
private TextView outputBottom;
protected void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_main);
outputBottom = (TextView)findViewById(R.id.output);
}
...
}
To set text, it's better not to "hardcode" with a string in quotes, but to create a string file and ask for it, which will look more like this:
outputBottom.setText(R.string.my_words);
Here are the developer notes on strings.
If you're using Android Studio there are tutorials for how to make that happen.
You can ignore these warning by adding
lintOptions {
disable 'MissingTranslation'
}
to the gradle.build file.

Android WebView Refresh Page and Display Toast [HW]

This is for study and I just want to make sure my answers are 100% right. The question gives me skeleton code and I'm required to fill it in. Here is the code.
public class WebFragment extends WebViewFragment {
private WebView mWebView;
#Override
public void onActivityCreated(Bundle.savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Fill in here
}
public void refreshPage(View view) {
// Fill in here
}
}
Now I am asked three questions. I have put my answers below each question.
a. Instantiate the WebView property in the class
b. When the activity has started, make the WebView component load the url "http://www.google.com/"
#Override
public void onActivityCreated(Bundle.savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mWebView = (WebView) findViewById(R.id.webview); // question a
mWebView.getSettings().setJavaScriptEnabled(true); // question a
mWebView.loadUrl("http://www.google.com"); // question b
}
c. Assuming a button is available in the activity layout and runs refreshPage when pressed, make the function reload the WebView page and show a Toast with the message "Page has been refreshed!"
public void refreshPage(View view) {
mWebView.reload();
Toast toast = Toast.makeText(getApplicationContext(), "Page has been refreshed!"), Toast.LENGTH_SHORT().show();
}
Any feedback is appreciated.
answer a seems ok, for the toast you don't need the variable, unless you don't want to do something other than showing the toast
mWebView.reload();
Toast.makeText(getApllicationContext(),"foo",Toast.LENGTH_SHORT).show();
or pass a custom time in milliseconds
Toast.makeText(getApllicationContext(),"foo",2000).show();
you can also initialize a Toast variable and than call show on it, it works, it's just a useless variable if you're not going to do anything with it but it's not wrong
Toast toast = Toast.makeText(getApplicationContext(),"foo",1000);
toast.show();
oh, I don't know if it's required, but like this refreshPage method is not callable by anybody, maybe you want to set an OnClickListener to the button (that we assume is in the layout) so that refreshPage can be called
((Button)findViewById(R.id.buttonId)).setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
refreshPage(v);
}
});

Categories

Resources