Ive got this button code as shown below but it only have one button and one textview my project require meant is that there needs to be two or more buttons that will count into separate systems but use the same code. Ill include the main code below but any help adding more functionality into the system is much loved!
main code
package com.example.counter;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
// Private member field to keep track of the count
private static int mCount = 0;
private TextView countTextView;
private Button countButton;
public static final String PREFS_NAME = "com.example.myApp.mCount";
private SharedPreferences settings = null;
private SharedPreferences.Editor editor = null;
/** ADD THIS METHOD **/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
countTextView = (TextView) findViewById(R.id.TextViewCount);
countButton = (Button) findViewById(R.id.ButtonCount);
countButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCount++;
countTextView.setText("Count: " + mCount);
editor = settings.edit();
editor.putInt("mCount", mCount);
editor.commit();
}
});
settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
mCount = settings.getInt("mCount", 0);
countTextView.setText("Count: " + mCount);
}
}
Create 3 buttons in your xml, lets assume their ids are ButtonCount, ButtonCount2 and ButtonCount3 as well as the countButton2 and countButton3 being declared as well. Then initialize them as follows:
countButton = (Button) findViewById(R.id.ButtonCount);
countButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCount++;
countTextView.setText("Count: " + mCount);
editor = settings.edit();
editor.putInt("mCount", mCount);
editor.commit();
}
});
countButton2 = (Button) findViewById(R.id.ButtonCount2);
countButton2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//do something here
}
});
countButton3 = (Button) findViewById(R.id.ButtonCount3);
countButton3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//do something else here
}
});
Related
Despite inputting my code below the only output to the user seems to be 0 in all three cases. Unsure on why this would be the case. Such as the image below seems to output the score to the user however does not register the score. To provide context provided the entire code for my end screen screenshot below. Any help would be appreciated.
package com.example.spaceattack;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class EndActivity extends AppCompatActivity {
private Button gameStart;
private TextView numberScore;
private String score;
TextView table_score;
int lastScore;
int best1, best2, best3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_end);
table_score = (TextView) findViewById(R.id.table_score);
SharedPreferences preferences = getSharedPreferences("PREFS", 0);
lastScore = preferences.getInt("lastScore", 0);
best1 = preferences.getInt("best1", 0);
best2 = preferences.getInt("best2", 0);
best3 = preferences.getInt("best3", 0);
if (lastScore > best3) {
best3 = lastScore;
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("best3", best3);
editor.apply();
}
if (lastScore > best2) {
int temp = best2;
best2 = lastScore;
best3 = temp;
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("best3", best3);
editor.putInt("best2", best2);
editor.apply();
}
if (lastScore > best1) {
int temp = best1;
best1 = lastScore;
best2 = temp;
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("best2", best2);
editor.putInt("best1", best1);
editor.apply();
}
table_score.setText("LAST SCORE: " + lastScore + "\n" +
"BEST1: " + best1 + "\n" +
"BEST2: " + best2 + "\n" +
"BEST3: " + best3);
score = getIntent().getExtras().get("score").toString();
gameStart = (Button) findViewById(R.id.restart_btn);
numberScore = (TextView) findViewById(R.id.scoreCount);
gameStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(EndActivity.this, WaterActivity.class);
startActivity(intent);
}
});
numberScore.setText("Score = " + score);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
package com.example.spaceattack;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import com.google.firebase.auth.FirebaseAuth;
public class WaterActivity extends AppCompatActivity {
private Button btn;
private Button buttonHelp;
int score;
Button btnLogout;
FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btnStart);
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
openMainActivity();
}
});
buttonHelp = (Button) findViewById(R.id.button);
buttonHelp.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
openHelpActivity2();
}
});
btnLogout = findViewById(R.id.logout);
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
Intent intToMain = new Intent(WaterActivity.this,LoginActivity.class);
startActivity(intToMain);
}
});
}
private void openMainActivity() {
SharedPreferences preferences = getSharedPreferences("PREFS", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("lastScore", score);
editor.apply();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
private void openHelpActivity2() {
Intent intent = new Intent(this, HelpActivity.class);
startActivity(intent);
}
}
[][2]
I want the user to have the same radio button checked which he had
previously checked before the app was closed.
This is my source code
package com.example.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.myapplication.R;
public class MainActivity extends AppCompatActivity {
RadioGroup radioGroup;
RadioButton radioButton;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup = findViewById(R.id.radioGroup);
textView = findViewById(R.id.text_view_selected);
Button buttonApply = findViewById(R.id.button_apply);
buttonApply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int radioId = radioGroup.getCheckedRadioButtonId();
radioButton = findViewById(radioId);
textView.setText("Your choice: " + radioButton.getText());
}
});
}
public void checkButton(View v) {
int radioId = radioGroup.getCheckedRadioButtonId();
radioButton = findViewById(radioId);
Toast.makeText(this, "Selected Radio Button: " + radioButton.getText(),
Toast.LENGTH_SHORT).show();
}
}
I want the radio button states to be saved for next time the app is
used.
You should take a look at sharedPreferences : https://developer.android.com/training/data-storage/shared-preferences
Save your data :
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("myRadio", radioButton.getText());
editor.commit();
Retrieve data :
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String defaultValue = "";
String radioButtonText = sharedPref.getString("myRadio", defaultValue);
For now, you can do this :
public class MainActivity extends AppCompatActivity {
RadioGroup radioGroup;
RadioButton radioButton;
TextView textView;
// Declare SharedPreferences as attributes
private SharedPreferences sharedPref;
private SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup = findViewById(R.id.radioGroup);
textView = findViewById(R.id.text_view_selected);
// Retrieve SharedPreferences
sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
editor = sharedPref.edit();
Button buttonApply = findViewById(R.id.button_apply);
buttonApply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int radioId = radioGroup.getCheckedRadioButtonId();
radioButton = findViewById(radioId);
textView.setText("Your choice: " + radioButton.getText());
}
});
}
#Override
protected void onResume() {
int radioIdChecked = -1;
radioIdChecked = sharedPref.getInt("myRadioChecked", radioIdChecked);
if (radioIdChecked == -1) {
// ERROR, don't check anything
Log.d("TAG", "error: don't check anything");
}
else {
RadioButton radioButton = radioGroup.findViewById(radioIdChecked);
if (radioButton != null) {
radioButton.setChecked(true);
}
}
}
#Override
protected void onPause() {
editor.putInt("myRadioChecked", radioGroup.getCheckedRadioButtonId());
editor.commit();
}
Best
I have no clue how to fix this, please help!
I am creating a counter app that shows numbers every time user press a button. It starts from 0 and to a maximum of 9999. My problem is that after the user closes the app it again starts from 0 but what I want is display the last number the user pressed instead of 0 when user open app again. I tried many shared preference codes but none of them worked. Here is my code:
import android.content.Context;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private int x;
Context context = this;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView number=(TextView) findViewById(R.id.numbers);
ImageButton btn_count=(ImageButton) findViewById(R.id.btn_countn);
ImageButton btn_reset=(ImageButton) findViewById(R.id.btn_resetn);
mp = MediaPlayer.create(context, R.raw.button_press);
number.setText(String.format("%04d", x)+"");
btn_count.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.button_press);
} mp.start();
} catch(Exception e) { e.printStackTrace(); }
x = x +1;
number.setText(String.format("%04d", x)+"");
}
});
btn_reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.button_press);
} mp.start();
} catch(Exception e) { e.printStackTrace(); }
x=0;
number.setText(String.format("%04d", x)+"");
}
});
}
}
You will need to use the Android Preferences for this:
How?
define when the app is getting closed and then call a method where you can write the actual value of the counter
Example
SharedPreferences buttonCounterValue = getSharedPreferences("counter", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = buttonCounterValue.edit();
editor.putInt("myCounter", i); //
editor.commit();
and when the app is open again you will need to call another method and read it back...
Example:
SharedPreferences buttonCounterValue = getPreferences(Activity.MODE_PRIVATE);
int storedCounter = buttonCounterValue.getInt("myCounter", 0);
so validate what you store and check if the preference you get is 0, that means nothing was stored before, so you can beging the game from 0...
Using SharedPreferences you can do something like this:
public class MainActivity extends AppCompatActivity {
private int x;
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
x = prefs.getInt("count", 0);
final TextView number=(TextView) findViewById(R.id.numbers);
ImageButton btn_count=(ImageButton) findViewById(R.id.btn_countn);
ImageButton btn_reset=(ImageButton) findViewById(R.id.btn_resetn);
number.setText(String.valueOf(x));
btn_count.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
x++;
prefs.edit().putInt("count", x).apply();
number.setText(String.valueOf(x));
}
});
btn_reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
x=0;
prefs.edit().putInt("count", x).apply();
number.setText(String.valueOf(x));
}
});
}
}
i was making an android app and i need to use one integer value in 2 activities. I tried using this code but it didn't work.
//Integer Sender
Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("MyIntNameGoesHere", intValue);
startActivity(myIntent);
//Integer receiver
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0);
It says Cannot resolve symbol intValue and Cannot resolve symbol A and the same for B.
Here's the whole code.
MainActivity:
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int balance;
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Hide notification bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//Click counter
final TextView text = (TextView) findViewById(R.id.balance_text);
assert text != null;
// to retreuve the values from the shared preference
preferences = PreferenceManager.getDefaultSharedPreferences(this);
balance = preferences.getInt("balance", 0);
text.setText(balance + " $");
final ImageButton button = (ImageButton) findViewById(R.id.click_button);
assert button != null;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
balance++;
text.setText("" + balance + " $");
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("balance", balance);
editor.apply();
}
});
final Button UpgradesButton = (Button) findViewById(R.id.upgrades_button);
assert UpgradesButton != null;
UpgradesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, UpgradesActivity.class));
}
});
//Balance Integer Sender
}
}
UpgradesActivity:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
public class UpgradesActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upgrades);
//Hide notification bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
final Button e2u_button = (Button) findViewById(R.id.e2u_button);
assert e2u_button != null;
e2u_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
final Button back_button = (Button) findViewById(R.id.back_button);
assert back_button != null;
back_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(UpgradesActivity.this, MainActivity.class));
}
});
//TODO: Pass balance integer from MainActivity to here.
}
}
Error code:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
public class UpgradesActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upgrades);
//Receive balance from MainActivity
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("key_int", 0);
//Hide notification bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
final Button e2u_button = (Button) findViewById(R.id.e2u_button);
assert e2u_button != null;
e2u_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(balance >= 300){ //ERROR ON THIS LINE
}
}
});
final Button back_button = (Button) findViewById(R.id.back_button);
assert back_button != null;
back_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(UpgradesActivity.this, MainActivity.class));
}
});
//TODO: Pass balance integer from MainActivity to here.
}
}
ALL ABOVE IS ANSWERED! ---------------------------------------------------------
Now i have problems with this part of the code:
#Override
public void onClick(View v) {
if(balance >= 300){
balance -= 300;
}
if(balance < 300){
final TextView text = (TextView) findViewById(R.id.not_enough_money_text);
assert text != null;
text.setText("You do not have enough money.");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
text.setText("");
}
}, 2000);
}
}
When i click the button it says i do not have enough money but i have over 300. Please help me.
I found out what the problem was but I'm not sure how to fix it. I need to send balance back to MainActivity. Can anyone help with that?
Send the data like this -
UpgradesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, UpgradesActivity.class);
intent.putExtra("key_int", balance);
startActivity(intent);
}
});
And fetch it in onCreate() of UpgradesActivity -
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("key_int", 0);
You're using different key when sending and receiving the Int.
Change this line:
int intValue = mIntent.getIntExtra("intVariableName", 0);
To this:
int intValue = mIntent.getIntExtra("MyIntNameGoesHere", 0);
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Anyone able to see whats wrong with this code? Is going to be a ticker code so when a button is clicked 1 is added and then again 1 is going to change to 2 and so on and on basically its a clicker that when closed will remember the number it was on.
To be more clear these lines are coming up as errors:
countButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mCount++;
countTextView.setTextView.setText("Count: " + mCount);
All of the code:
package com.example.counter;
import android.app.Activity;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
// Private member field to keep track of the count
private static int mCount = 0;
private TextView countTextView;
private Button countButton;
public static final String PREFS_NAME = "com.example.myApp.mCount";
private SharedPreferences settings = null;
private SharedPreferences.Editor editor = null;
/** ADD THIS METHOD **/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
countTextView = (TextView) findViewById(R.id.TextViewCount);
countButton = (Button) findViewById(R.id.ButtonCount);
countButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mCount++;
countTextView.setText("Count: " + mCount);
editor = settings.edit();
editor.putInt("mCount", mCount);
editor.commit();
}
});
settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
mCount = settings.getInt("mCount", 0);
countTextView.setText("Count: " + mCount);
}
}
You have switched the logic between resume and pause.
Pause should persist your number.
Resume should read the old number.
change new OnClickListener() to new View.OnClickListener() in addition to what everyone suggesting.
Do not use .setTextView.setText(..) but simply use .setText (CharSequence text).
See the Following Running Code For your requirement
public class MainActivity extends Activity {
// Private member field to keep track of the count
private static int mCount = 0;
private TextView countTextView;
private Button countButton;
public static final String PREFS_NAME = "com.example.myApp.mCount";
private SharedPreferences settings = null;
private SharedPreferences.Editor editor = null;
/** ADD THIS METHOD **/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
countTextView = (TextView) findViewById(R.id.TextViewCount);
countButton = (Button) findViewById(R.id.ButtonCount);
countButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mCount++;
countTextView.setText("Count: " + mCount);
editor = settings.edit();
editor.putInt("mCount", mCount);
editor.commit();
}
});
settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
mCount = settings.getInt("mCount", 0);
countTextView.setText("Count: " + mCount);
}
}
Just Copy And Paste it. thats it.
import android.content.DialogInterface.OnClickListener;
should be changed to
import android.view.View.OnClickListener;
You're importing the wrong listener, so it's expecting a different method signature for onClick()
In addition to all the other things mentioned.