When the button is pressed, the app crashes - java

I've been having problems with Android buttons. I try to set an onClick listener, but it fails, crashes and doesn't print any helpeul error messages. Here is my code:
Button button;
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.choose_level);
}
});
I've tried putting in a try catch statement so it won't display annoying errors but the button still doesn't work. Would it be because the layout hasn't been loaded? or is it something else?
Thanks in advance.

you must call setContentView(R.layout.XML_LAYOUT); method before you callfindViewById for your button.
here XML_LAYOUT must be the Layout containing your Button ID.
Note:- it is not recommanded to call setContentView method multiple times. if you want to show a different layout/screen add it into Another activity and start that activity on button click.

you are calling setContentView(R.Layout.XML_LAYOUT) in your button onClick listener where as it should be above in oncreate method
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/
Button play = (Button)findViewById(R.id.play);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
show ur text here
}
});
I guess what u r trying to do is to set view for an XML file
which is some layout file i guess check out inflator and intent

I put that in a try, catch statement so it won't put annoying errors...
A catch block will not magically stop your error from occurring - you cannot use it to stop the application "putting annoying errors".
You use them to handle errors when it's possible to recover from those cases (e.g. wait and retry, fall back to a slower alternative, etc.)
What is the implementation of your catch block? If you're simply swallowing the error, your app will still fail - only you won't have any diagnostic information with which to deal with it.
You'll need to go back to your original "annoying error", work out why it was happening and then fix it rather than just suppressing its output.

Related

i have made one app to get ascii value of my character that i am going to put in my edit text but when i press my button to conver my app gets closed

i have made one app to get ascii value of my character that i am going to put in my edit text. i have made the code as-> `
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=findViewById(R.id.button);
TextView textview=findViewById(R.id.textView2);
EditText edittext=findViewById(R.id.editTextTextPersonName);
String sipla=edittext.getText().toString();
Button button2 = findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int t=sipla.charAt(0);
textview.setText("THE ASCII value of your character = "+t);
}
});`
but when i click my button my app gets closed. one more think
when i make certain changes in my code and put String sipla=edittext.getText().toString(); in my button setonclick function it works and everything is normal please tell me why my app was not working prevously .
The reason your app is crashing is because sipla is empty, and you try to get the first character from an empty string. The reason it is empty is that you get it in onCreate, before the user has had a chance to enter anything in the EditText. Even if they enter something later, you never update the value of sipla.
The fix for this is simple - don't get the value from the EditText until you are actually ready to use it and the user would have had time to enter something - so get it inside onClick.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// This code runs as the activity is getting set up
Button button=findViewById(R.id.button);
TextView textview=findViewById(R.id.textView2);
EditText edittext=findViewById(R.id.editTextTextPersonName);
Button button2 = findViewById(R.id.button2);
// if you get the value of edittext here it will always be empty,
// at this point the user hasn't even seen the screen yet
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// This code runs much later, when the user
// clicks the button
// Don't get the string until you are ready to process it, this code
// doesn't run until the user clicks the button, at which
// time edittext may also have a user value in it
String sipla = edittext.getText().toString();
if( !sipla.isEmpty() ) {
int t=sipla.charAt(0);
textview.setText("THE ASCII value of your character = "+t);
}
else {
textview.setText("You didn't enter anything");
}
}
});
}
Also, if your app crashes, look in the Logcat tab to see the full error message and stack trace. Learn to read that - it is an invaluable debugging skill. Also, learn to use Log/print statements in your code to help you understand what values are being used and what order things are run in when you are confused.

can I have two different onclick methods for one button

I wanted to know if its possible to have two onclick methods for one buttton..Im trying to have a button that can open a new activity and send a id token to the server for firebase purposes, if possible how do i go about it on android studio
I think you are getting the underlying concept wrong.
Buttons react to clicks.
The "ActionListener" that gets triggered on that click ... can do whatever it wants. There is nothing (conceptually) that prevents you in your code to just trigger various things. Of course, you have to understand what you are doing (things like: not blocking the UI thread for too long; or how to kick of things in background threads, and so on).
No. There is only one onClick method for a Button. But you can still perform two different purposes by one button.
I am using a button to hide and show a linear layout. The code is given below :
final int[] count = {2};
//here startTopics is the button....
startTopics.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(count[0] %2==0)
{
topicLin.setVisibility(View.VISIBLE);
count[0]++;
}
else
{
topicLin.setVisibility(View.GONE);
//here topicLin is the linear layout
count[0]++;
}
}
});
It is one button and so you should apply only one onClick listener which performs the buttons job.
In your onClick-method you can just call another (private) method if you want to do multiple things without sacrificing code management.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendTokenToServer();
// Include your code to open the activity here or outsource it again into another private method
}
});
And your method to send the token to the server:
private void sendTokenToServer() {
// Your code here.
}

Android: Passing 2 Input Parameters Through A Method Activated By A View

I'm trying to make a method that is activated when another method gives it an int, and at the same time, the method can also be activated by a view.
Here is the top line of the method and where in Java the method is called:
checkNum(theNumber, null);
public void checkNum (int num, View view){
I tried using "onClick" in the xml for a button, but checkNum did not appear as a suggestion and the app crashed when I ran it. How can I fix this?
Thanks so much!
When using the onClick attribute in XML, the correct signature to use is
public void checkNum (View view)
If you want to pass in a other parameters, I suggest that you set it in Java code.
Add a click listener to your button this way:
Button button = (Button) findViewById(R.id.your_button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something when the button is clicked
}
});

How to change color of background Android Java in Eclipse ADT

I am very new to mobile development, this isn't homework I am working ahead of my class, I developed a simple app that has a button and when it's pressed it shows a message "Hello Android". I would like to build on this and change the color of the background when the onClickListener is called, I will post my code below, I am asking for the best approach to achieve my goal (change background). I want to iterate that this code below works, and that I am not asking for anything to do with the code I have presented, I want to add to it to change the background color (it's currently white, I'm assuming by default). Oh and I have never worked with Java before (very difficult course teaching android/iOS/WinMobile in 1 class). Thank you.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupMessageButton();
}
private void setupMessageButton() {
// 1. Get a reference to the button
final Button messageButton = (Button) findViewById(R.id.helloDroidButton);
//Set the click listener to run my code.
//Code will run when user clicks button.
messageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Anonymous class? --> not sure what he means
Log.i("DemoButtonApp", "Hello Android!");
Toast.makeText(
MainActivity.this,
"Hello Android!",
Toast.LENGTH_LONG
).show();
}
});
}
Android support feature called Selector , that help you to change the background of any view in each state of it like pressed , forces and so one , take look on this useful tutorial and feed me back in any not obvious point
http://www.mkyong.com/android/android-imagebutton-selector-example/
hope it help you

Java Callback-like/event method?

I might be on the wrong track here, and should be thinking events/publish-subscriber, if so, please enlighten me.
I have an android project running, where I have a layout which acts as an on-screen menu. Implemented in several activities/"parent-views" with the use of '< include>'. Working nicely.
Now, some of the functionality is general and global. Like I have an "add"-button, which does something, that it should always do. Then I'd like the possibility to customize what it does in addition to this, based on the activity where the action originated.
I have seperated menulogic in a simple java class, with the constructor taking an activity as a parameter. From here, I can attach clicklisteners to the buttons in the menu fine, and do stuff on click.
What I'd like is something like:
private void addBtn(String text, String path) {
LinearLayout ll = (LinearLayout) parentActivity.findViewById(R.id.dynamicButtonLayout);
Button newButton = new Button(parentActivity);
newButton.setText(text);
newButton.setTag(path);
newButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
//Do Stuff.
fireDoneHandlingButtonClick();
} catch (Exception e) {
}
}
});
}
And then have a way of handling this method in the parent activity. Should I be thinking of events, or should I be thinking of a way to add a method as an argument to the addBtn method from the activity, which can be fired from inside the click-listener?
Look at How To Implement Your Own Listener in Android or Fire and Forget Messages (events) in Android

Categories

Resources