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
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 am creating a simple clicker program. I am clicking a pear picture and then it increments by 1 and displays that. I want to save this number so I they can click and then completely exit the app and when they return the same number they left off at is still there. This is my code but yet it still does not save that pears int when I restart the app.
CODE:
package pearclicker.pearclicker;
import android.content.SharedPreferences;
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 {
ImageButton imageButtonPear;
TextView showValue;
int pears;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showValue = (TextView) findViewById(R.id.countText);
}
public void PearIncrease(View v) {
SharedPreferences pref = getApplicationContext().getSharedPreferences("PearCount", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("pearCount", pears);
pears++;
if (pears == 1) {
showValue.setText(pears + " pear");
editor.putInt("pearCount", pears);
editor.apply();
}
else {
showValue.setText(pears + " pears");
editor.putInt("pearCount", pears);
editor.apply();
}
}
}
Your code is doing fine when clicking the button to increase the value of your pear. but you're doing nothing in your onCreate() so you think that the SharedPreference is not storing the value of pear when you restart the app..
to do that you need some modification to your code.
public class MainActivity extends AppCompatActivity {
ImageButton imageButtonPear;
TextView showValue;
int pears = 0;
SharedPreferences pref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = getApplicationContext().getSharedPreferences("PearCount", MODE_PRIVATE);
showValue = (TextView) findViewById(R.id.countText);
pears = pref.getInt("pearCount", 0); // This will get the value of your pearCount, It will return Zero if its empty or null.
showValue.setText(pears + " pears");
}
public void PearIncrease(View v) {
editor = pref.edit();
pears++;
showValue.setText(pears + " pears");
editor.putInt("pearCount", pears);
editor.apply();
}
}
[Android newbie] Help required in adding 4 math operations as options to a radion button.
Also I need to perform respective options on selecting radio button option.
package com.sivaneshsg.wallet;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class MainActivity extends AppCompatActivity {
int cashamount = 0;
int cardamount = 0;
int walletamount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText et = (EditText) findViewById(R.id.inputamount);
final RadioButton card1 = (RadioButton) findViewById(R.id.card1);
final RadioButton cash1 = (RadioButton) findViewById(R.id.cash1);
final RadioButton card2 = (RadioButton) findViewById(R.id.card2);
final RadioButton cash2 = (RadioButton) findViewById(R.id.cash2);
final RadioGroup rg =(RadioGroup) findViewById(R.id.rgroup);
final TextView t1 = (TextView) findViewById(R.id.amountcard);
final TextView t2 = (TextView) findViewById(R.id.amountcash);
final TextView t3 = (TextView) findViewById(R.id.amountwallet);
Button but = (Button) findViewById(R.id.button);
final int amount = Integer.parseInt(et.getText().toString());
cash1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cash2.setChecked(false);
card1.setChecked(false);
card2.setChecked(false);
cashamount = cashamount + amount;
}
});
card1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cash2.setChecked(false);
cash1.setChecked(false);
card2.setChecked(false);
cardamount=cardamount+amount;
}
});
cash2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cash1.setChecked(false);
card1.setChecked(false);
card2.setChecked(false);
cashamount = cashamount - amount;
}
});
card2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cash2.setChecked(false);
cash1.setChecked(false);
card2.setChecked(false);
cardamount=cardamount-amount;
}
});
but.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
t1.setText("Amount in Card : RS. " + cardamount);
t2.setText("Amount in Cash : Rs. " + cashamount);
walletamount = cardamount + cashamount;
t3.setText("Total Amount in Wallet : RS. " + walletamount);
}
});
}
}
your amount variable taking value at onCreate() method which is initially 0
Can someone please help me edit the following code so that it saves the info typed into the edittext and then once the app is relaunched it will automatically display the text that was saved in the edittext field. I have tried SharedPreferences tutorials but so far I have not been able to get it working.
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText txtLink;
Button btnOpenLink;
String defaultLink;
String secondLink;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
defaultLink = "http://";
secondLink = ".whatver.com";
txtLink = (EditText) findViewById(R.id.editText);
btnOpenLink = (Button) findViewById(R.id.button);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
btnOpenLink.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String server = txtLink.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, server);
editor.commit();
if(!TextUtils.isEmpty(server)){
Intent intent=new Intent(MainActivity.this,webactivity.class);
intent.setData(Uri.parse(defaultLink+server+secondLink));
startActivity(intent);
}else{
Toast.makeText(MainActivity.this, "Please enter your server name.", Toast.LENGTH_LONG).show();
}
}
});
}
}
Verify the stored preferences and load them if any avaliable, after that display them in the textview
Example:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
defaultLink = "http://";
secondLink = ".whatver.com";
txtLink = (EditText) findViewById(R.id.editText);
btnOpenLink = (Button) findViewById(R.id.button);
checkIfPreferencesAvaliable();
if(defaultLink!=null && secondLink!=null){
txtLink.setText(defaultLink+secondLink);
}
defaultLink = "http://";
secondLink = ".whatver.com";
void checkIfPreferencesAvaliable(){
SharedPreferences preferences = getPreferences(Activity.MODE_PRIVATE);
defaultLink = preferences.getStr("mydefaultLink", null);
secondLink = preferences.getStr("mysecondLink", null);
}
In your onCreate(), check if you have already have values in your preferences-
String savedVal = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE).getString(Name, null);
if(savedVal == null){ //This means you don't have the saved values in your prefs file
//Do whatever you want to
} else{
//Use "savedVal" anyway you want
}
I fixed it by calling this
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
txtLink.setText(sharedpreferences.getString(Name, ""));
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
}
});