Hi I'm a college student and I'm struggling with an app I have to make. The app is a subtraction app and I can't seem to get it to work. Every time I press the subtraction button it crashes.
My code:
public void onClick(View view){
switch (view.getId()) {
case R.id.subtract_button:
setContentView(R.layout.activity_main);
EditText firstNumber = (EditText) findViewById(R.id.input_box_1);
int num1 = Integer.parseInt(firstNumber.getText().toString());
EditText secondNumber = (EditText) findViewById(R.id.input_box_2);
int num2 = Integer.parseInt(secondNumber.getText().toString());
int result = num1 - num2;
setContentView(R.layout.activity_result);
TextView subResult = (TextView)findViewById(R.id.result_view);
subResult.setText(Integer.toString(result));
break;
case R.id.exit_button: // the 'exit' button has been pressed.
// Delay the exit by 1 second at this time!
new Handler().postDelayed(new Runnable() {
public void run() {
//Finish the app
finish();
}
}, 1000);
break; // End of case.
}
}
At First Post your Logcat
Problem for your wrong setContentView placing .
Why multiple setContentView ?? Must be One .
Don't
switch (view.getId()) {
case R.id.subtract_button:
setContentView(R.layout.activity_main); // Problem here i guess
Do
setContentView call in your onCreate(Bundle savedInstanceState) section.
An activity is a single, focused thing that the user can do. Almost
all activities interact with the user, so the Activity class takes
care of creating a window for you in which you can place your UI with
setContentView(View).
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_name);
I thought you missed button declaration check it
Button button;
button=(Button) findViewById(R.id.buttonid);
or else post ur log
Related
Like this https://androidexample365.com/content/images/2019/05/OtpEditText.gif
if wordbox1.setText("C") get clicked wordbox1 become invisible and matchbox1.getText("C") when matchbox1 get clicked wordbox1 become visible and matchbox1.getText(null)
I want check if matchbox1 , matchbox2 ,matchbox3 = getText(null) to fill who null
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//my answer buttons
//if you click on any button of my question buttons look for
// who is null first of my answer buttons
Button matchbox1,matchbox2,matchbox3;
//my question buttons wordbox1 = "C" wordbox2 = "A" wordbox3 = "R"
// car is the correct answer
Button wordbox1,wordbox2,wordbox3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
matchbox1= (Button)findViewById(R.id.matchbox1);
matchbox2= (Button)findViewById(R.id.matchbox2);
matchbox3= (Button)findViewById(R.id.matchbox3);
wordbox1= (Button)findViewById(R.id.wordbox1);
wordbox2= (Button)findViewById(R.id.wordbox2);
wordbox3= (Button)findViewById(R.id.wordbox3);
//for example if matchbox1.getText(R) wordbox3.setVisibility(View.Visible);
matchbox1.setOnClickListener(this);
//for example if matchbox2.getText(A) wordbox2.setVisibility(View.Visible);
matchbox2.setOnClickListener(this);
//for example if matchbox3.getText(C) wordbox1.setVisibility(View.Visible);
matchbox3.setOnClickListener(this);
wordbox1.setOnClickListener(this);
wordbox2.setOnClickListener(this);
wordbox3.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.wordbox1:
matchbox1.setText("C");
wordbox1.setVisibility(View.INVISIBLE);
break;
case R.id.wordbox2:
matchbox2.setText("A");
wordbox2.setVisibility(View.INVISIBLE);
break;
case R.id.wordbox3:
matchbox3.setText("R");
wordbox3.setVisibility(View.INVISIBLE);
break;
//for example any button pressed
case R.id.matchbox1:
wordbox3.setVisibility(View.VISIBLE);
matchbox1.setText("");
break;
case R.id.matchbox2:
wordbox2.setVisibility(View.VISIBLE);
matchbox2.setText("");
break;
case R.id.matchbox3:
wordbox1.setVisibility(View.VISIBLE);
matchbox3.setText("");
break;
}
if (matchbox1.getText().toString().equals("C") &&
matchbox2.getText().toString().equals("A")&&
matchbox3.getText().toString().equals("R")){
matchbox1.setBackgroundColor(Color.GREEN);
matchbox2.setBackgroundColor(Color.GREEN);
matchbox3.setBackgroundColor(Color.GREEN);
}
}
}
I hope i find the answer becase I need it very much
Hi so even though I have seen a couple of topics about linking activities or returning I can not get my return back to activity to work. I abit of back ground the the app when the user gets an answer wrong or runs out of time it goes to game over taking the score across with it and displaying it on the game over, here's the working code for that if it helps solve my issue:
Main Class:
public void fail(){
{
Intent myIntent = new Intent(MainActivity.this,gameover.class);
myIntent.putExtra("number", score);
MainActivity.this.startActivity(myIntent);
finish();
}
gameover class:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameover);
re_run = (Button) findViewById(R.id.retry);
EndScore = (TextView) findViewById(R.id.show);
int getVal;
getVal = getIntent().getExtras().getInt("number");
String s = String.valueOf( getVal );
EndScore.setText(s);
}
Now the reason I shared the above working code because I have the feeling the intent that takes the user and score to the gameover screen, is messing with the retry/return code as shown below:
private void setButtonOnClickListeners(){
re_run.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Intent retry = new Intent(getApplicationContext(),
MainActivity.class);
startActivity(retry);
}
});
}
From what I can find from those topics these seems to be the correct method. but when the code is run the re_run button does nothing. Any help?
You use "setButtonOnClickListeners()" to implement setOnClickListener and so override the onClick. But when did you call setButtonOnClickListeners?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameover); re_run = (Button)
findViewById(R.id.retry);
EndScore = (TextView) findViewById(R.id.show);
int getVal;
getVal = getIntent().getExtras().getInt("number");
String s = String.valueOf( getVal );
EndScore.setText(s);
setButtonOnClickListeners();
}
You can maybe check that your OnClick is working correctly adding a log line in LogCat. Log.d("GameOver", "Retry onclick ok");
You are finding a view before it was inflated (R.id.retry).
Change the sequence of commands to:
super.onCreate(savedInstanceState);
setContentView(R.layout.gameover);
re_run = (Button) findViewById(R.id.retry);
Also try changing the intent to:
Intent retry = new Intent(GameOver.this, MainActivity.class);
retry.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
I personally used startActivityForResult(Intent) to start the game over screen, and once the player inputted his name or pressed something or quit the activity with Back, then it returned a value to onActivityResult(..) in which I called finish().
EDIT:
Game ends, so I started activity using
Intent i = new Intent();
i.putExtra("Score", scoreCount);
i.setClass(context, HighScoreInputActivity.class);
context.startActivityForResult(i, 0);
Then when you insert the scores and stuff, you close the game screen in GameActivity with
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
this.finish();
}
I am trying to reduce the amount of code I have by making everything more efficient
I want to implement a switch statement instead of a long if statement
here is the switch i have began creating
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonA:
displayLetters(v);
break;
case R.id.buttonB:
displayLetters(v);
break;
and here is the displayLetters method that I want each case to run
private void displayLetters(View v) {
NewDisplayWord = EditText.getText().toString();
NewDisplayWord = NewDisplayWord + v.getTag();
EditText.setText(NewDisplayWord);
}
However instead of displaying A or B in the textedit when I press the buttons, I get null when I press any of the buttons
It seems that you are trying to get the text from the EditText by doing EditText.getText(). I think what you mean to do is use the v variable passed into displayLetters(). You can do something like this:
private void displayLetters(View v) {
NewDisplayWord = ((EditText)v).getText().toString();
NewDisplayWord = NewDisplayWord + v.getTag();// I do not know what is the use of `getTag()` here...
((EditText)v).setText(NewDisplayWord);
}
If the displayLetters() will only deal with EditTexts, you can make its parameter be an EditText
First, let's change displayLetters to accept String
private void displayLetters(final String letter) {
newDisplayWord = editText.getText().toString();
newDisplayWord = newDisplayWord + letter;
editText.setText(newDisplayWord);
}
Then call displayLetters() with String param:
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonA:
displayLetters(v.getTag());
break;
case R.id.buttonB:
displayLetters(v.getTag());
break;
default:
break;
}
}
If your onClick() listener will serve only the buttons, you could probably simplify it even further:
#Override
public void onClick(View v) {
//cast view to button
Button bt = (Button) v;
//get text from button
final String letter = bt.getText().toString();
//pass it to displayLetters()
displayLetters(letter);
}
Please follow Java naming convention, that is variable names start with lowercase. Also, I'm assuming that you have properly set your button and editText:
editText = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
I have a game activity and using an sqlite database I populate some buttons, randomly without repetition, and when the game gets finished I popup an alert dialog with OK button an some info. Now, I need when I press OK, to close that popup and in that game activity reload some other data to my buttons, without repetition. This I need to happen twice. I do this in my other game but that popup does not have OK button, it pops up for 3 seconds and using handler closes and my activity reloads with new data without repetition, and that works like a charm. In this game, only OK button is a difference, and it does not work. And I need that OK button. Two problems I have with this.
I successfuly reload my activity but with repetition, which tells me that my activity loads from scratch.
When the activity loads for the second time, when I press back button I can see previous game activity, which again tells me that I get one activity loaded twice. I only need it once with new data every time.
Also, my counter does not work, cause after second load, I get 3rd, 4th and so on.
Here are my game and popup activity:
public class ToploHladno extends Activity implements View.OnClickListener{
Button b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, bIzlaz, bDalje;
String mButtonText1, mButtonText2, mButtonText3, mButtonText4, mButtonText5, mButtonText6,
mButtonText7, mButtonText8, mButtonText9, mButtonText10, opis, odgovorNormalized;
MediaPlayer buttonClicks, buttonFinal, buttonBack;
public boolean music;
final Context context = this;
Editable ukucanRezultat;
String tacanRezultat, ukucanRezultatVelikaSlova;
int brojPoena;
int counter = 0;
LinkedList<Long> mAnsweredQuestions = new LinkedList<Long>();
private String generateWhereClause(){
StringBuilder result = new StringBuilder();
for (Long l : mAnsweredQuestions){
result.append(" AND _ID <> " + l);
}
return result.toString();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
addListenerOnButton();
nextQuestion();
}
private void addListenerOnButton() {
b1 = (Button) findViewById(R.id.button1);
b2 = (Button) findViewById(R.id.button2);
b3 = (Button) findViewById(R.id.button3);
b4 = (Button) findViewById(R.id.button4);
bIzlaz = (Button) findViewById(R.id.bIzlaz);
bDalje = (Button) findViewById(R.id.bDalje);
}
public void nextQuestion() {
counter++;
TestAdapter mDbHelper = new TestAdapter(this);
mDbHelper.createDatabase();
try{
mDbHelper.open();
Cursor c = mDbHelper.getTestData(generateWhereClause());
mAnsweredQuestions.add(c.getLong(0));
mButtonText1 = c.getString(2);
mButtonText2 = c.getString(3);
mButtonText3 = c.getString(4);
mButtonText4 = c.getString(5);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
b4.setOnClickListener(this);
if(counter < 3){
b1.setText("30 poena");
b2.setText("25 poena");
b3.setText("22 poena");
b4.setText("20 poena");
}else{
finish();
}
}
finally{
mDbHelper.close();
}
}
Popup:
public class Popup_opis extends Activity implements OnClickListener{
TextView tvOpis;
int brojPoenaPrimljeno;
Button OK;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popup_opis);
initVariables();
}
private void initVariables() {
OK = (Button) findViewById(R.id.bOK);
tvOpis = (TextView) findViewById(R.id.tvOpis);
OK.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
Intent intent = new Intent(Popup_opis.this, ToploHladno.class);
//intent.putExtra("myMethod", "nextQuestion"); //I tried also this
startActivity(intent);
}
});
}
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
If I understand you correctly, you are restarting your ToploHladno Activity from your Popup_opis Activity using an Intent. If the ToploHladno Activity hasn't been finished, which I don't think it has been, then no need for Intent. You can call invalidate() on the Views that you want to be repopulated in onResume() after calling setText() on them or whatever changes you need to make to those Views
#Override
public void onResume()
{
// change your Buttons however you need in here then say you have btn1
btn1.invalidate();
}
Your first Activity isn't being finished so you don't need or probably even want to start it with an Intent. You will just return to it after closing your Dialog Activity and onResume() will be called so you can do what you need in there. This will keep you from redrawing the whole Layout by not creating a new instance of your Activity.Let me know if this works for what you need or not
Invalidate
startActivityForResult() example:
Intent intent = new Intent(ToploHladno .this, Popup_opis .class);
intent.putExtra("counter", counter);
startActivityForResult( intent, 0 ); //second param is a request code. You will need this later
then in pop up activity
public class Popup_opis extends Activity implements OnClickListener{
TextView tvOpis;
int brojPoenaPrimljeno;
Button OK;
int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popup_opis);
//Get intent
Intent recIntent = getIntent();
counter = recIntent.getIntExtra("counter"); //get counter variable from previous activity
OK.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
counter++;
Intent intent = new Intent(Popup_opis.this, ToploHladno.class);
intent.putExtra("counter", counter); //SEND BACK COUNTER
setResult(RESULT_OK, intent); // send result
finish();
then in your previous activity
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
// would use REQUEST CODE sent earlier if more than one activity sends back intents here
if (resultCode == RESULT_OK)
{
counter = data.getInteExtra("counter", 0); // get updated counter variable
}
}
More about startActivityForResult in Docs
If anybody can tell me different way to do this, I would appreciate. How to reset class variable to 0, or default value? I use class variable cause I don't know another way to do this. After my game ends I place result in class variable, cause I have two rounds of my game, and after first round ends I add the result, and class variable is good for this cause even after I restart my game method it still holds my previous result. After second round is over I add that result to previous result and then close the activity and set text result as text to a button. But when I click New game, that button still holds that text, cause class variable still holds it. How to reset that class variable when I go on New game?
Here's my game code, some of it (100 points are start amount, and it gets lower in game progress):
public class Asocijacije extends Activity implements OnClickListener{
int brojPoenaAsocijacije = 100;
public static int brojPoenaUkupno;
Then I skip here a lot of code and here's where I add points. brojPoenaAsocijacije are points earned in that round:
brojPoenaUkupno = brojPoenaUkupno + brojPoenaAsocijacije;
Here's my main activity where I set points from my class variable to a button (where I added comment):
public class Izbor extends Activity implements OnClickListener{
Asocijacije poeni = new Asocijacije();
Button toploHladno, asocijacije, cigle, spojnice, nazad, poeniTH, poeniAso, poeniCigle, poeniSpojnice;
TextView naslov;
public boolean music;
MediaPlayer buttonClicks, buttonBack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.izbor);
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
music = getPrefs.getBoolean("checkbox", true);
addListenerOnButton();
}
private void addListenerOnButton() {
buttonClicks = MediaPlayer.create(this, R.raw.click);
buttonBack = MediaPlayer.create(this, R.raw.button31);
Typeface naslovType = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
Typeface dugmad = Typeface.createFromAsset(getAssets(), "Bebas.ttf");
naslov = (TextView) findViewById(R.id.tvIzborNaslov);
toploHladno = (Button) findViewById(R.id.bIzbor1);
asocijacije = (Button) findViewById(R.id.bIzbor2);
cigle = (Button) findViewById(R.id.bIzbor3);
spojnice = (Button) findViewById(R.id.bIzbor4);
nazad = (Button) findViewById(R.id.bIzborNazad);
poeniTH = (Button) findViewById(R.id.bPoeniTH);
poeniAso = (Button) findViewById(R.id.bPoeniAso);
poeniCigle = (Button) findViewById(R.id.bPoeniCigle);
poeniSpojnice = (Button) findViewById(R.id.bPoeniSpojnice);
naslov.setTypeface(naslovType);
toploHladno.setTypeface(dugmad);
asocijacije.setTypeface(dugmad);
cigle.setTypeface(dugmad);
spojnice.setTypeface(dugmad);
nazad.setTypeface(dugmad);
poeniAso.setTypeface(dugmad);
toploHladno.setOnClickListener(this);
asocijacije.setOnClickListener(this);
cigle.setOnClickListener(this);
spojnice.setOnClickListener(this);
nazad.setOnClickListener(this);
}
#Override
protected void onStart() {
super.onStart();
poeniAso.setText("" + poeni.brojPoenaUkupno); //I do it here
}
public void onClick(View v) {
switch(v.getId()){
case R.id.bIzbor1:
if(music == true){
buttonClicks.start();
}
startActivity(new Intent("rs.androidaplikacije.toplo_hladno.GAME"));
break;
case R.id.bIzbor2:
if(music == true){
buttonClicks.start();
}
startActivity(new Intent("rs.androidaplikacije.toplo_hladno.ASOCIJACIJE"));
break;
case R.id.bIzbor3:
if(music == true){
buttonClicks.start();
}
break;
case R.id.bIzbor4:
if(music == true){
buttonClicks.start();
}
break;
case R.id.bIzborNazad:
if(music == true){
buttonBack.start();
}
poeniAso.setText("");
finish();
break;
}
}
}
Because I don't find the piece of code where you start the new game, I can only say:
Asocijacije.brojPoenaUkupno = 0;
Probably want to reset your state when you close the in-game activity.
#Override
protected void onDestroy() {
super.onDestroy();
Asocijacije.brojPoenaUkupno = 0;
//whatever other things need to be reset.
}