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, ""));
Related
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 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();
}
}
i m working on an application and i want to make user login only when he/she logouts his previous session but i m unable to do it. whenever i close my program and re-open it. it directs to Homepage again even if i had'nt logout. plz
package in.co.medimap.www.medimap;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import static in.co.medimap.www.medimap.R.layout.login;
/**
* Created by sony on 28-04-2016.
*/
public class login extends Activity {
TextView signup_text;
Button login_button;
EditText PHONE_NO,PASSWORD;
AlertDialog.Builder builder;
public static final String MyPREFERENCE ="Myprefs";
public static final String PHONE="phone";
public static final String PASS="password";
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.login);
signup_text=(TextView)findViewById(R.id.sign_up);
signup_text.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
startActivity(new Intent(login.this,register.class));
}
});
PHONE_NO=(EditText)findViewById(R.id.phone_no);
PASSWORD=(EditText)findViewById(R.id.password);
login_button=(Button)findViewById(R.id.login_button);
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String ph = PHONE_NO.getText().toString();
String p=PASSWORD.getText().toString();
if (ph.equals("")||p.equals("")) {
builder = new AlertDialog.Builder(login.this);
builder.setTitle("Something went wrong...");
builder.setMessage("Please fill all the fields...");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
else
{
//see from here
sharedPreferences = getSharedPreferences(MyPREFERENCE,Context.MODE_PRIVATE );
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(PHONE, ph);
editor.putString(PASS, p);
editor.commit();
BackgroundTask backgroundTask = new BackgroundTask(login.this);
backgroundTask.execute("login",ph,p);
}
}
});
}
}
this is my homeactivity where after logging user goes
and i want that if i hadn't logout then whenever i open my app it should start from here
package in.co.medimap.www.medimap;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class HomeActivity extends Activity {
Button Logout = null;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Logout = (Button) findViewById(R.id.Logout);
textView = (TextView) findViewById(R.id.welcome_txt);
String message = getIntent().getStringExtra("message");
textView.setText(message);
Logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences(login.MyPREFERENCE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
Intent intent = new Intent(HomeActivity.this,MainActivity.class);
startActivity(intent);
}
});
}
}
If you want logout to happen each time user leaves the application, why don't you just do it manually?
you've already set Logout buttons setOnClickListener so just do this:
#Override
protected void onPause() {
super.onPause();
if(Logout != null) {
Logout.callOnClick();
}
}
This means every time user leaves this activity it will logout.
make sure you handle cases where if they leave activity but go to a different activity on your page, it doesn't log out.
=========== EDIT ===========
I'm guessing your login activity is the main activity that starts when application opens so just put this in onCreate before you perform any other tasks. right after setContentView, you should do this.
SharedPreferences sharedPreferences = getSharedPreferences(login.MyPREFERENCE, Context.MODE_PRIVATE);
String phone = sharedPreferences.getString(PHONE, "");
String pass = sharedPreferences.getString(PASS, "");
if(!phone.isEmpty() && !pass.isEmpty()) {
// this means ID and passwords are already saved so just start your home activity here
startActivity(new Intent(context, MainActivity.class));
finish();
}
In your MainActivity:
Just read the values from SharedPreferences and login if you have to.
Hope this helps.
========== EDIT 2
Also, your Logout should look like this. Don't use commmit or clear. put empty values and use apply
Logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences(login.MyPREFERENCE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(PHONE, "");
editor.putString(PASS, "");
editor.apply();
Intent intent = new Intent(HomeActivity.this,MainActivity.class);
startActivity(intent);
}
});
I am getting a runtime exception when I am calling NavDrawerActivity from LoginScreen activity.
Error
java.lang.RuntimeException: Performing stop of activity that is not
resumed:
{com.example.owner.loginapp/com.example.owner.loginapp.NavDrawerActivity}
How to fix this error?
Here is my loginScreen code
package com.example.owner.loginapp;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import android.content.SharedPreferences;
public class LoginScreen extends AppCompatActivity {
ImageView image;
ImageView user_img;
ImageView pass_img;
Button log_in;
Button reg;
EditText editText_Username;
EditText editText_Pass;
UserSessionManager session;
private SharedPreferences sharedPreferences;
private static final String PREFER_NAME = "Reg";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
session = new UserSessionManager(getApplicationContext());
image = (ImageView) findViewById(R.id.imageView);
image.setImageResource(R.drawable.smile);
user_img = (ImageView) findViewById(R.id.user_img);
user_img.setImageResource(R.drawable.user_img);
pass_img = (ImageView) findViewById(R.id.pass_img);
pass_img.setImageResource(R.drawable.img_pass);
log_in = (Button) findViewById(R.id.btn_Login);
reg = (Button) findViewById(R.id.btn_Reg);
editText_Username = (EditText) findViewById(R.id.editText_UserName);
editText_Pass = (EditText) findViewById(R.id.editText_Password);
Bitmap icon = BitmapFactory.decodeResource(getResources(),
image.setImageBitmap(icon);
Toast.makeText(getApplicationContext(),
"User Login Status: " + session.isUserLoggedIn(),
Toast.LENGTH_LONG).show();
sharedPreferences = getSharedPreferences(PREFER_NAME, Context.MODE_PRIVATE);
log_in.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String username = editText_Username.getText().toString();
String password = editText_Pass.getText().toString();
if (username.trim().length() > 0 && password.trim().length() > 0) {
String uName = null;
String uPassword = null;
if (sharedPreferences.contains("Name")) {
uName = sharedPreferences.getString("Name", "");
}
if (sharedPreferences.contains("Password")) {
uPassword = sharedPreferences.getString("Password", "");
}
if (username.equals(uName) && password.equals(uPassword)) {
session.createUserLoginSession(uName, uPassword);
Intent i = new Intent(getApplicationContext(), NavDrawerActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
} else {
Toast.makeText(getApplicationContext(),
"Username/Password is incorrect",
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(),
"Please enter username and password",
Toast.LENGTH_LONG).show();
}
}
});
reg.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setContentView(R.layout.register);
Intent i = new Intent(getApplicationContext(), Reg.class);
startActivity(i);
}
});
}
}
I copied your code and tried to instantiate a Reg Activity class that I designed and everything worked fine. It is possible that you are doing something wrong in the 1onResumeoronCreate` of Reg class.
Post that class too for more information.
I have a SharedPreference in this .java File; towards the bottom you can see I save the values to the SharedPreferences GB_PREFERENCES_BENCH, and GB_PREFERENCES_FLIES. How do I use these values in another activity? See the second code example for how I want to use it.
package com.creativecoders.gymbuddy;
import com.creativecoders.gymbuddy.R;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
public class Benchmark extends Activity {
public static final String GB_PREFERENCES = "Prefs";
public static final String GB_PREFERENCES_BENCH = "Bench";
public static final String GB_PREFERENCES_FLIES = "Flies";
SharedPreferences gBValues;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_benchmark);
gBValues = getSharedPreferences(GB_PREFERENCES, Context.MODE_PRIVATE);
}
public void onStart() {
super.onStart();
findViewById(R.id.button5).setOnClickListener(new handleButton5());
}
class handleButton5 implements OnClickListener {
public void onClick(View v) {
EditText editText1 = (EditText)findViewById(R.id.editText1);
String sWeight = editText1.getText().toString();
final double dWeight = Double.parseDouble(sWeight);
EditText editText2 = (EditText)findViewById(R.id.editText2);
String sPush = editText2.getText().toString();
final double dPush = Double.parseDouble(sPush);
EditText editText3 = (EditText)findViewById(R.id.editText3);
String sSit = editText3.getText().toString();
final double dSit = Double.parseDouble(sSit);
EditText editText4 = (EditText)findViewById(R.id.editText4);
String sPull = editText4.getText().toString();
final double dPull = Double.parseDouble(sPull);
double dBench = (((Math.floor(dWeight*.0664))*10)-10)+dPush;
double dFlies = (Math.floor(((Math.floor(dBench*.6)/10)*10)));
int iBench = (int)dBench;
int iFlies = (int)dFlies;
Editor editor1 = gBValues.edit();
editor1.putInt(GB_PREFERENCES_BENCH, iBench);
editor1.commit();
Editor editor2 = gBValues.edit();
editor2.putInt(GB_PREFERENCES_FLIES, iFlies);
editor2.commit();
}
}
}
Here is how I want to use it; (specifically in the on create method to set a TextView's text to the value in the SharePreference)
package com.creativecoders.gymbuddy;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class Upper100Start extends Activity {
public static final String GB_PREFERENCES = "Prefs";
public static final String GB_PREFERENCES_CURLS = "Curls";
SharedPreferences gBValues;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upper100start);
if (gBValues.contains(GB_PREFERENCES_CURLS)){
TextView TextView2 = (TextView)findViewById(R.id.textView2);
TextView2.setText(gBValues.getString(GB_PREFERENCES_CURLS, ""));
}
}
public void onStart() {
super.onStart();
findViewById(R.id.button2).setOnClickListener(new handleButton2());
findViewById(R.id.button3).setOnClickListener(new handleButton3());
}
class handleButton2 implements OnClickListener {
public void onClick(View v) {
Intent intent = new Intent(Upper100Start.this, Upper101.class);
startActivity(intent);
}
}
class handleButton3 implements OnClickListener {
public void onClick(View v) {
Intent intent = new Intent(Upper100Start.this, Main.class);
startActivity(intent);
}
}
}
The shared preferences are accessible throughout your application, so you can read them from any activity in the application.
Storing a key/value pair in activity A:
SharedPreferences settings = getSharedPreferences("mysettings",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("mystring", "wahay");
editor.commit();
Reading this value from another activity:
SharedPreferences settings = getSharedPreferences("mysettings",
Context.MODE_PRIVATE);
String myString = settings.getString("mystring", "defaultvalue");
You can find more information at http://developer.android.com/guide/topics/data/data-storage.html#pref