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
Related
I have been making an app that will ask a name at the first start of my app and should display it afterwards but whenever I am trying to save either I am Having a NullPointerExceptionor the name
display is empty.
This is my MainActivity
package com.example.sas;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity implements namedialog.ExampleDialogListenerName {
private ImageView imageView;
public static final int IMAGE_PICK_CODE = 1000;
private SharedPreferences prefs;
public static final int PERMISSION_CODE = 1001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences preferences = getSharedPreferences("preferences",MODE_PRIVATE);
boolean firststart = preferences.getBoolean("firstStart",true);
if (firststart) {
OpenNameDialog();
}else {
savename();
}
TextView dateview = findViewById(R.id.date);
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-YYYY");
String date = dateFormat.format(calendar.getTime());
dateview.setText(date);
imageView = findViewById(R.id.selfpicture);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_DENIED){
String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
requestPermissions(permissions,PERMISSION_CODE);
}else {
pickImageFromGallery();
}
}else {
pickImageFromGallery();
}
}
});
}
private void OpenNameDialog(){
namedialog namedialog = new namedialog();
namedialog.show(getSupportFragmentManager(),"name dialog");
SharedPreferences preferences = getSharedPreferences("preferences",MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("firstStart",false);
editor.apply();
}
#Override
public void ApplyNameDialog(String name) {
prefs = getSharedPreferences("prefs",MODE_PRIVATE);
final SharedPreferences.Editor editor = prefs.edit();
editor.putString("susanth",name);
}
public void savename(){
String names = prefs.getString("susanth","");
TextView display = findViewById(R.id.namename);
display.setText(names);
}
public void pickImageFromGallery(){
Intent intent1 = new Intent(Intent.ACTION_PICK);
intent1.setType("image/*");
startActivityForResult(intent1,IMAGE_PICK_CODE);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case PERMISSION_CODE:{
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
pickImageFromGallery();
}else {
Toast.makeText(getApplicationContext(),"Permission Denied",Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == IMAGE_PICK_CODE) {
imageView.setImageURI(data.getData());
}
}
}
This is my namedialog
package com.example.sas;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatDialogFragment;
import java.util.Objects;
public class namedialog extends AppCompatDialogFragment {
private EditText name ;
private ExampleDialogListenerName listener;
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = Objects.requireNonNull(getActivity()).getLayoutInflater();
View view = inflater.inflate(R.layout.namedialog,null);
builder.setView(view)
.setTitle("Welcome Fill your details")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final String namef = name.getText().toString();
listener.ApplyNameDialog(namef);
}
});
name = view.findViewById(R.id.etname);
return builder.create();
}
#Override
public void onAttach(#NonNull Context context) {
context = getActivity();
super.onAttach(context);
try {
listener = (ExampleDialogListenerName) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()+
"must implement ExampleDialogListenerName");
}
}
public interface ExampleDialogListenerName{
void ApplyNameDialog (String name);
}
}
Can you tell me what should I use for storing the name permanently.
Please Help Me Fast Thank You :)
#Override
public void ApplyNameDialog(String name) {
prefs = getSharedPreferences("prefs",MODE_PRIVATE);
final SharedPreferences.Editor editor = prefs.edit();
editor.putString("susanth",name);
}
It seems like the string is never saved. You should call editor.commit() or editor.apply()
in the Mainclass Im creating a variable called mDatabase. In the Mainclass there is a button called Database. When I click on it, it opens a new Activity. Then it starts the onCreate-Method of the second class databasegrocery.
When the program executes the command:
mAdapter=new GroceryAdapter(this, activity.getAllItems());
(...) it returns back to Main-Activity to call the method getAllItems().
When im returning to this method, mDatabase is null (mDatabase was already declared and initialized, when the app started with the MainActivity), why?
As Im totally new to android programing its possible that Im trying something stupid,
so I appreciate your help.
(I read something about activity-lifecycles and I saw that the MainActivity is in Stop-Status, when the second Activity is active. So the data from MainActivity is not destroyed, right?)
If you need more information, tell me!
Thank you.
package com.example.grocerylist;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public class MainActivity extends AppCompatActivity{
public SQLiteDatabase mDatabase;
private EditText mEditTextName;
private EditText mEditTextName2;
private EditText mEditTextName3;
private EditText mEditTextName4;
private EditText mEditTextName5;
private EditText mEditTextName6;
private EditText mEditTextName7;
private EditText mEditTextName8;
private EditText mEditTextName9;
Button buttonIncrease;
Button buttonDecrease;
Button buttonAdd;
Button buttonDatabase;
public databasegrocery database;
Intent IntentDatabase;
private TextView mTextViewAmount;
private int mAmount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GroceryDBHelper dbHelper = new GroceryDBHelper(this);
mDatabase = dbHelper.getWritableDatabase();
mEditTextName = findViewById(R.id.edittext_name);
mTextViewAmount = findViewById(R.id.textview_amount);
mEditTextName2=findViewById(R.id.edittext_name2);
mEditTextName3=findViewById(R.id.edittext_name3);
mEditTextName4=findViewById(R.id.edittext_name4);
mEditTextName5=findViewById(R.id.edittext_name5);
mEditTextName6=findViewById(R.id.edittext_name6);
mEditTextName7=findViewById(R.id.edittext_name7);
mEditTextName8=findViewById(R.id.edittext_name8);
mEditTextName9=findViewById(R.id.edittext_name9);
IntentDatabase=new Intent(MainActivity.this,databasegrocery.class);
buttonIncrease = findViewById(R.id.button_increase);
buttonDecrease = findViewById(R.id.button_decrease);
buttonAdd = findViewById(R.id.button_add);
buttonDatabase=findViewById(R.id.buttonDatabase);
buttonDatabase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(IntentDatabase);
}
});
buttonIncrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
increase();
}
});
buttonDecrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
decrease();
}
});
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addItem();
}
});
}
private void increase() {
mAmount++;
mTextViewAmount.setText(String.valueOf(mAmount));
}
private void decrease() {
if (mAmount > 0) {
mAmount--;
mTextViewAmount.setText(String.valueOf(mAmount));
}
}
private void addItem() {
if (mEditTextName.getText().toString().trim().length() == 0 || mAmount == 0) {
return;
}
String name = mEditTextName.getText().toString();
String mkcal1 = mEditTextName2.getText().toString();
String mkcal2=mEditTextName3.getText().toString();
String mFett=mEditTextName4.getText().toString();
String mDavongesaettigtefettsaueren=mEditTextName5.getText().toString();
String mKohlenhydrate=mEditTextName6.getText().toString();
String mZucker=mEditTextName7.getText().toString();
String mEiweiss=mEditTextName8.getText().toString();
String mSalz=mEditTextName9.getText().toString();
//___________________________________________________________________
ContentValues cv = new ContentValues();
cv.put(GroceryContract.GroceryEntry.COLUMN_NAME, name);
cv.put(GroceryContract.GroceryEntry.COLUMN_AMOUNT, mAmount);
//----------------------------------------------------------------------------------------
cv.put(GroceryContract.GroceryEntry.COLUMN_KCAL1, mkcal1);
cv.put(GroceryContract.GroceryEntry.COLUMN_KCAL2, mkcal2);
cv.put(GroceryContract.GroceryEntry.COLUMN_FETT, mFett);
cv.put(GroceryContract.GroceryEntry.COLUMN_DAVONGESAETTIGTEFETTSAEUREN, mDavongesaettigtefettsaueren);
cv.put(GroceryContract.GroceryEntry.COLUMN_Kohlenhydrate, mKohlenhydrate);
cv.put(GroceryContract.GroceryEntry.COLUMN_Zucker, mZucker);
cv.put(GroceryContract.GroceryEntry.COLUMN_EIWEIS, mEiweiss);
cv.put(GroceryContract.GroceryEntry.COLUMN_SALZ, mSalz);
//------------------------------------------------------------------------------------------
mDatabase.insert(GroceryContract.GroceryEntry.TABLE_NAME, null, cv);
databasegrocery.mAdapter.swapCursor(getAllItems());
mEditTextName.getText().clear();
mEditTextName2.getText().clear();
mEditTextName3.getText().clear();
mEditTextName4.getText().clear();
mEditTextName5.getText().clear();
mEditTextName6.getText().clear();
mEditTextName7.getText().clear();
mEditTextName8.getText().clear();
mEditTextName9.getText().clear();
}
public Cursor getAllItems() {
return mDatabase.query(GroceryContract.GroceryEntry.TABLE_NAME, null, null, null, null, null, GroceryContract.GroceryEntry.COLUMN_TIMESTAMP + " ASC");
}
}
package com.example.grocerylist;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public class databasegrocery extends AppCompatActivity {
public static GroceryAdapter mAdapter;
public MainActivity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.databasegrocery);
activity=new MainActivity();
RecyclerView recyclerView = findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new GroceryAdapter(this, activity.getAllItems());
recyclerView.setAdapter(mAdapter);
}
}
I make two activity first is timer.java activity which is an countdown activity and second activity is SaveRestTime.java in this activity user input number value in edittext and user will save it i use shared preference in this activity now I want which value user save in SaveRestTime.java class is automatically make value of countdown if user not save any value then default value is 30 sec please help me i am confuse how to read value from another activity
here is timer.java code
package com.cinegoes.www.daily10exercise;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import com.cinegoes.www.daily10exercise.SaveRestTime;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.concurrent.TimeUnit;
import static com.cinegoes.www.daily10exercise.SaveRestTime.mypreference;
/**
* Created by ever on 7/25/2017.
*/
public class timer extends Activity implements View.OnClickListener {
private CountDownTimer countDownTimer;
private boolean timerStarted = false;
private Button buttonStart;
public TextView textView;
private ProgressBar progressBarCircle;
private final long startTime = 30 * 1000;
private final long interval = 1 * 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.timer);
buttonStart = (Button) this.findViewById(R.id.button);
progressBarCircle = (ProgressBar) findViewById(R.id.progressBarCircle);
buttonStart.setOnClickListener(this);
textView = (TextView) this.findViewById(R.id.textView);
countDownTimer = new CountDownTimerActivity(startTime, interval);
textView.setText(textView.getText() + String.valueOf(startTime/1000));
}
#Override
protected void onStart() {
super.onStart();
countDownTimer.start();
timerStarted = true;
setProgressBarValues();
}
#Override
public void onClick(View v) {
finish();
}
public class CountDownTimerActivity extends CountDownTimer {
public CountDownTimerActivity(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
textView.setText(msTimeFormatter(startTime));
textView.setText("Time's up!");
setProgressBarValues();
finish();
}
#Override
public void onTick(long millisUntilFinished) {
textView.setText(msTimeFormatter(millisUntilFinished));
progressBarCircle.setProgress((int) (millisUntilFinished / 1000));
}
}
private void setProgressBarValues() {
progressBarCircle.setMax((int) startTime / 1000);
progressBarCircle.setProgress((int) startTime / 1000);
}
private String msTimeFormatter(long milliSeconds) {
String ms = String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(milliSeconds) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(milliSeconds)),
TimeUnit.MILLISECONDS.toSeconds(milliSeconds) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(milliSeconds)));
return ms;
}
}
here is my SaveRestTime.java code
package com.cinegoes.www.daily10exercise;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class SaveRestTime extends Activity {
SharedPreferences sharedpreferences;
TextView name;
public static final String mypreference = "mypref";
public static final String Name = "nameKey";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.saveresttime);
name = (TextView) findViewById(R.id.etName);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
}
public void Save(View view) {
String n = name.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.commit();
}
public void Get(View view) {
name = (TextView) findViewById(R.id.etName);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name))
{name.setText(sharedpreferences.getString(Name, ""));
}
}
}
SharedPreferences prefs = this.getSharedPreferences("myPref", Context.MODE_PRIVATE);
String lanSettings = prefs.getString("nameKey", null);
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);
}
});
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, ""));