How to set variable only on first launch of activity - java

Ive got a problem. Theres a String languages and I have MainActivity(A) and ChooseLanguageActivity(B). From A user goes to B to choose language after that he intented to A and languages get value from intent. I need to set default value for this variable languages. I tried to use it in onCreate. But I don't need use default value each time activity created. I need to use it only when app launching after that this variable need to use the value which it get from activity B intent.
Thats code
public class MainActivity extends AppCompatActivity {
AppCompatButton chooseLanguageButton;
AppCompatButton cleanButton;
AppCompatEditText translatedTextOutput;
AppCompatEditText translatedTextInput;
String translatedInputString;
RequestQueue requestQueue;
SharedPreferences sPref;
final String SAVED_TEXT = "saved_text";
final String TAG = "myTag";
String language;
private ProgressBar progressBar;
private Timer timer;
private TextWatcher searchTextWatcher = new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
if (translatedTextInput.getText().length() != 0){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
requestQueue = Volley.newRequestQueue(MainActivity.this);
sendJsonRequest();
}
});
}
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(translatedTextInput.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}, 600);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (timer != null) {
timer.cancel();
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
language = "en";
chooseLanguageButton = (AppCompatButton) findViewById(R.id.choose_language_button);
cleanButton = (AppCompatButton) findViewById(R.id.clean_button);
translatedTextOutput = (AppCompatEditText) findViewById(R.id.translated_text_field);
translatedTextInput = (AppCompatEditText) findViewById(R.id.translation_input_edit);
translatedTextInput.addTextChangedListener(searchTextWatcher);
chooseLanguageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveText();
Intent intent = new Intent(MainActivity.this, ChooseLanguageList.class);
startActivity(intent);
}
});
cleanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
translatedTextInput.setText("");
translatedTextOutput.setText("");
}
});
loadText();
}
#Override
protected void onDestroy() {
super.onDestroy();
sPref = null;
}
void saveText() {
sPref = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor ed = sPref.edit();
ed.putString(SAVED_TEXT, translatedTextInput.getText().toString());
ed.commit();
Toast.makeText(this, "Text saved", Toast.LENGTH_SHORT).show();
}
void loadText() {
sPref = getPreferences(MODE_PRIVATE);
String savedText = sPref.getString(SAVED_TEXT, "");
translatedTextInput.setText(savedText);
Toast.makeText(this, "Text loaded", Toast.LENGTH_SHORT).show();
}
public void sendJsonRequest() {
Intent myIntent = getIntent();
language = myIntent.getStringExtra("short");
Log.v(getClass().getSimpleName(), "language short = " + language);
translatedInputString = translatedTextInput.getText().toString().replace(" ","+");
String url = String.format(getApplicationContext().getResources().getString(R.string.request_template),
String.format(getApplicationContext().getResources().getString(R.string.query_Template), translatedInputString, language ));
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.v(TAG, "Inside OnResponse" + response.toString());
JSONArray results = null;
try {
results = response.getJSONObject("data").getJSONArray("translations");
for (int i=0,j=results.length();i<j;i++) {
String webTitle = results.getJSONObject(i).getString("translatedText");
translatedTextOutput.setText(webTitle);
}
} catch (JSONException e) {
Log.e(TAG, "Error :" + e);
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NetworkError) {
Log.e(TAG, "NetworkError");
} else if (error instanceof ServerError) {
Log.e(TAG, "The server could not be found. Please try again after some time!!");
} else if (error instanceof AuthFailureError) {
Log.e(TAG, "AuthFailureError");
} else if (error instanceof ParseError) {
Log.e(TAG, "Parsing error! Please try again after some time!!");
} else if (error instanceof NoConnectionError) {
Log.e(TAG, "NoConnectionError!");
} else if (error instanceof TimeoutError) {
Log.e(TAG, "Connection TimeOut! Please check your internet connection.");
}
}
});
requestQueue.add(jsObjRequest);
}
}
P.S.Hmmm i don't understand that -1. If you make -1 at least write in comment whats wrong with question not to duplicate this mistakes next time.

Short answer: Save boolean activityWasLauched on SharedPreferences
When the app launches always put the variable as false. Inside of the onCreate of the Activity put it true, then you can use:
if (activityWasLauched == false){
//use the default
}
else{
//use a bundle and get the value from an intent
}
To simplify the much as possible the use of SharedPreferences:
To store values in shared preferences:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
if(score > high_score)
{
editor.putInt("high_score", score);
editor.apply(); /* Edit the value here*/
}
To retrieve values from shared preferences:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String high_score= sp.getInt("high_score", "");

Remember that variables are stored in memory and are destroyed whenever your app stops running. To store a value more permanently, you need to save it to disk. For simple values, SharedPreferences is the way to go. You should load the value of languages from SharedPreferences when your app starts. If no such value exists, save a default value so that the next time your app starts, it just reads the value. If something in the app changes the value of this variable, such as a user action, be sure to save the new value so that it is correct the next time your app starts.

Hope I understood you right..
First:
Launch your "ChooseLanguageList" activity using startActivityForResult()
Intent intent = new Intent(MainActivity.this, ChooseLanguageList.class);
startActivityForResult(intent, ANY_REQUEST_CODE);
Second:
In your "ChooseLanguageList" after setting your language return result to "MainActivity" using set result
Intent returnIntent = new Intent();
returnIntent.putExtra(MY_LANG_EXTRA, language);
setResult(Activity.RESULT_OK, returnIntent);
finish();
Third:
Back to "MainActivity".. catch the returned result using onActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ANY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
language = data.getStringExtra(MY_LANG_EXTRA);
/* Save language in Shared Preferences */
}
Fourth:
Save your retrieved language in a Shared preference
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putInt(/*Key:*/"my_lang", /*value:*/language);
editor.apply();
Fifth:
Now every time you want to use language (eg. in onCreate()), just retrieve it from Shared Preferences, stating a default value in case it wasn't found
String language = sp.getString(/*Key:*/"my_lang", "en/*Default value*/");
Now each time "MainActivity" launches it will try to get language from Shared Prefs with key "my_lang", but if there is nothing there it will fall back to the default "en" until a new value is retrieved from "ChooseLanguageList" activity.
Hope this answers your question

Related

Android: How to save the best score in a game?

I am a beginner programmer and I create a game for android and I came across a problem that I want after finishing the game to show me the best score that I managed to achieve in playing this game I made a condition
if(DOD> sharedPreferences.getInt("DOD_SHA",0));
of course I use sharedPreferences to save the best score here but this condition doesn't work at all and my sharedPreference takes any value even less than the last score
public class EndScreen extends AppCompatActivity {
TextView Levelwys,war;
Button GotoMenu;
int DOD,ODE,MNO,PIE,DZI,POT,SIL,LOG;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_end_screen);
Levelwys = findViewById(R.id.textView15);
war = findViewById(R.id.textView19);
GotoMenu = findViewById(R.id.button);
sharedPreferences = getSharedPreferences("com.example.goodmath", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
Intent intent = getIntent();
int number = intent.getIntExtra(GameSingleActivity.LEVEL, 0);
DOD = intent.getIntExtra("DOD", 0);
ODE = intent.getIntExtra("ODE", 0);
MNO = intent.getIntExtra("MNO", 0);
PIE = intent.getIntExtra("PIE", 0);
DZI = intent.getIntExtra("DZI", 0);
POT = intent.getIntExtra("POT", 0);
SIL = intent.getIntExtra("SIL", 0);
LOG = intent.getIntExtra("LOG", 0);
Levelwys.setText(String.valueOf(number));
String test = String.valueOf(DOD);
Toast.makeText(getApplicationContext(), test, Toast.LENGTH_LONG).show();
Save();
GotoMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GotoMenu();
}
});
}
#Override
public void onBackPressed() {
}
void GotoMenu()
{
Intent intent1 = new Intent(this, MenuActivity.class);
startActivity(intent1);
}
void Save()
{
if(DOD> sharedPreferences.getInt("DOD_SHA",0));
{
editor.putInt("DOD_SHA",DOD);
editor.apply ();
editor.commit();
Toast.makeText(getApplicationContext(), "cos", Toast.LENGTH_LONG).show();
war.setText(String.valueOf(sharedPreferences.getInt("DOD_SHA",DOD)));
}
}
}
You have typo in your if condition:
if(DOD> sharedPreferences.getInt("DOD_SHA",0));
You have added extra semicolon at the end of this line. Because of this, the code below this condition was always called.
Delete this semicolon and everything should works fine:
if(DOD> sharedPreferences.getInt("DOD_SHA",0))
{
editor.putInt("DOD_SHA",DOD);
editor.apply ();
editor.commit();
Toast.makeText(getApplicationContext(), "cos", Toast.LENGTH_LONG).show();
war.setText(String.valueOf(sharedPreferences.getInt("DOD_SHA",DOD)));
}

service data reset after swiping away application

Purpose of program: I'm trying to make an app that will count how many times the user checked their phone by issuing a broadcast for Intent.ACTION_SCREEN_ON. it then increments a counter and updates the activity with the new counter.
The problem: This all works just fine but as soon as I swipe away the application from the apps tray, the counter goes back to zero.
obviously what is supposed to happen is the counter would continue.
I tried saving the counter value in the service onDestroy and then calling it again onCreate but onDestroy is never called.
Note that in the onCreate() for the activity it sends a broadcast to the service asking for the most recent value of counter and then updates it in the view. I couldn't find a better way to keep them in sync.
CounterService.java
public class CounterService extends Service {
public static boolean RERUN = true;
private int counter = 0;
private SharedPreferences SP;
private BroadcastReceiver mScreenStateBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
counter++;
System.out.println("************************************* \n \n " + counter);
}
sendCounterBroadcast();
}
};
public void sendCounterBroadcast() {
Intent i = new Intent();
i.setAction("com.inc.count");
i.putExtra("counterValue", counter);
sendBroadcast(i);
}
#Override
public void onCreate() {
super.onCreate();
System.out.println("********************** CounterService.onCreate()");
// get counter value from SP -- this is useful for when the service gets recreated
SP = getSharedPreferences("Counter Service Data", MODE_PRIVATE);
counter = SP.getInt("counter", 0);
// wait for screen to be turned on or for the activity to ask you for the counter number
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_ON);
intentFilter.addAction("send.counter.to.phonecounteractivity");
registerReceiver(mScreenStateBroadcastReceiver, intentFilter);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
System.out.println("***************************************** CounterService.OnDestroy()");
unregisterReceiver(mScreenStateBroadcastReceiver);
// Save counter value for when we restart service
SP = getSharedPreferences("Counter Service Data", MODE_PRIVATE);
SharedPreferences.Editor SPE = SP.edit();
if (RERUN) {
SPE.putInt("counter", counter);
System.out.println("******************************** RESTARTING SERVICE ");
startService(new Intent(getApplicationContext(), CounterService.class));
} else
SPE.putInt("counter", 0);
SPE.apply();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
PhoneCheckerCounter.Java
public class PhoneCheckerCounter extends AppCompatActivity {
private BroadcastReceiver changeCount;
private IntentFilter filter;
private int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_checker_counter);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
switcherOnClick();
assignValuesOnCreate();
System.out.println("**************************** onCreate()");
changeCounterText();
}
public void switcherOnClick() {
final Switch sCounter = findViewById(R.id.switchCounter);
sCounter.setOnClickListener(new View.OnClickListener() {
Intent intent = new Intent(getApplicationContext(), CounterService.class);
#Override
public void onClick(View v) {
if (sCounter.isChecked()) {
startService(intent);
CounterService.RERUN = true;
v.getContext().registerReceiver(changeCount, filter);
Toast.makeText(getApplicationContext(), "Counting has begun", Toast.LENGTH_SHORT).show();
} else {
TextView n = findViewById(R.id.counter);
n.setText("0");
CounterService.RERUN = false;
v.getContext().unregisterReceiver(changeCount);
stopService(intent);
Toast.makeText(getApplicationContext(), "The application stopped counting", Toast.LENGTH_SHORT).show();
}
}
});
}
public void changeCounterText() {
changeCount = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
TextView n = findViewById(R.id.counter);
counter = intent.getIntExtra("counterValue", 0);
System.out.println("************************ RECEIVED!!!! value of: " + counter);
n.setText("" + counter);
}
};
filter = new IntentFilter();
filter.addAction("com.inc.count");
this.registerReceiver(changeCount, filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(changeCount);
assignValuesOnDestroy();
System.out.println("**************************** onDestroy()");
}
public void assignValuesOnCreate() {
Switch s = findViewById(R.id.switchCounter);
if (getSwitchValueFromSP() == 1) s.setChecked(true);
else s.setChecked(false);
Intent f = new Intent();
f.setAction("send.counter.to.phonecounteractivity");
sendBroadcast(f);
}
public void assignValuesOnDestroy() {
SharedPreferences SP = getSharedPreferences("data", MODE_PRIVATE);
SharedPreferences.Editor edit = SP.edit();
Switch s = findViewById(R.id.switchCounter);
if (s.isChecked()) edit.putInt("switch", 1);
else edit.putInt("switch", 0);
edit.apply();
}
public int getSwitchValueFromSP() {
SharedPreferences SP = getSharedPreferences("data", MODE_PRIVATE);
int isOn = SP.getInt("switch", 0);
return isOn;
}
}
Sample of the activity

How to restart same Activity?

If i have 10 EditText and the user enter only in 5 then i exit my app on click the onBackPressed Button without submit the EditText data which is entering , and then when i restart my app i want to same activity on start up.Thanks to appriceat.
public class Registration_Form extends Activity {
EditText et_CompanyName;
EditText et_EmployeeName;
EditText et_CompanyWebsite;
EditText et_ContactNumber;
EditText et_Email_Id;
Button btnSubmit;
DatabaseHelper databaseHelper;
SQLiteDatabase db;
RadioGroup radioGroup_FinancialYaer;
RadioButton radioButton_FinancialYaer;
String strFinancialYear;
String appWidgetId = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registration_details);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor edit = prefs.edit();
boolean alldataSaved=prefs.getBoolean("SecondRun",false);
et_CompanyName = (EditText) findViewById(R.id.editText_CompanyName);
et_EmployeeName = (EditText) findViewById(R.id.editText_EmployeeName);
et_CompanyWebsite = (EditText) findViewById(R.id.editText_CompanyWebSite);
et_ContactNumber = (EditText) findViewById(R.id.editText_ConatctNo);
et_Email_Id = (EditText) findViewById(R.id.editText_EmailId);
et_CompanyName.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus)
{
edit.putString("Company_Name"+appWidgetId,et_CompanyName.getText().toString());
edit.commit();
}
}
});
et_EmployeeName.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus)
{
edit.putString("Employee_Name"+appWidgetId,et_EmployeeName.getText().toString());
edit.commit();
}
}
});
et_CompanyWebsite.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus)
{
edit.putString("Company_Website"+appWidgetId,et_CompanyWebsite.getText().toString());
edit.commit();
}
}
});
et_ContactNumber.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus)
{
edit.putString("Contact_Number"+appWidgetId,et_ContactNumber.getText().toString());
edit.commit();
}
}
});
et_Email_Id.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus)
{
edit.putString("Email_Id"+appWidgetId,et_Email_Id.getText().toString());
edit.commit();
}
}
});
SharedPreferences settings=getSharedPreferences("prefs",0);
boolean firstRun=settings.getBoolean("firstRun",false);
if(firstRun==false)//if running for first time
{
SharedPreferences.Editor editor=settings.edit();
editor.putBoolean("firstRun",true);
editor.commit();
//execute your code for first time
}
else
{
if(alldataSaved == false)
{
SharedPreferences.Editor editor=prefs.edit();
editor.putBoolean("SecondRun",true);
editor.commit();
Log.e("Second"," Steps !!!!");
}
else
{
Intent iSubmit = new Intent(Registration_Form.this,Employee_List.class);
startActivity(iSubmit);
finish();
//Default Activity startActivity(a);
}
}
databaseHelper = new DatabaseHelper(this);
databaseHelper.onOpen(db);
radioGroup_FinancialYaer = (RadioGroup)findViewById(R.id.radioGroupFinanncialYear);
btnSubmit = (Button) findViewById(R.id.buttonSubmit);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final String stringEmail_Id = et_Email_Id.getText().toString()
.trim();
final String stringCompanyWebsite = et_CompanyWebsite.getText()
.toString().trim();
if ((et_CompanyName.getText().toString().isEmpty()))
{
et_CompanyName.setError("Field Can Not Be Empty !");
}
else if (!et_CompanyName.getText().toString().trim()
.matches("[a-zA-Z ]+"))
{
et_CompanyName.setError("Accept Alphabets Only.");
}
else if ((et_EmployeeName.getText().toString().isEmpty()))
{
et_EmployeeName.setError("Field Can Not Be Empty !");
}
else if (!et_EmployeeName.getText().toString().trim()
.matches("[a-zA-Z ]+"))
{
et_EmployeeName.setError("Accept Alphabets Only.");
}
else if ((et_CompanyWebsite.getText().toString().isEmpty()))
{
et_CompanyWebsite.setError("Field Can Not Be Empty !");
}
else if (!isValidUrl(stringCompanyWebsite))
{
et_CompanyWebsite.setError("Invalid URL");
}
else if ((et_ContactNumber.getText().toString().isEmpty()))
{
et_ContactNumber.setError("Field Can Not Be Empty !");
}
else if (!isValidEmail(stringEmail_Id))
{
et_Email_Id.setError("Invalid Email");
}
else
{
String stringCompanyName = et_CompanyName.getText()
.toString().trim();
String stringContactNumber = et_ContactNumber.getText()
.toString().trim();
String stringEmployeeName = et_EmployeeName.getText()
.toString().trim();
int selectedId = radioGroup_FinancialYaer.getCheckedRadioButtonId();
Log.e("selectedId "," = " + selectedId);
radioButton_FinancialYaer = (RadioButton) findViewById(selectedId);
strFinancialYear = radioButton_FinancialYaer.getText().toString().trim();
Log.e("strRadioButton "," = " + strFinancialYear);
databaseHelper.insertRegstrationDetails(stringCompanyName,
stringEmployeeName, stringCompanyWebsite,
stringContactNumber, stringEmail_Id, strFinancialYear);
System.out.println("Data Inserted Successfully !!! ");
Intent iSubmit = new Intent(Registration_Form.this,Staff_Employee_Details.class);
startActivity(iSubmit);
finish();
}
}
});
}
you can simply use this
Intent intent = getIntent();
finish();
startActivity(intent);
I hope thats work
You can use sharedPreference for this. you can save the value of each edittext in one sharedprefrerece (with unique key for each edittext and set values at the time of focus change. see example:)
EditText txtEdit= (EditText) findViewById(R.id.edittxt);
txtEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus)
//do job here when Edittext lose focus
//means save value here
}
});
and load these saved value at on create.
Hope you are getting some idea from this
Edit: This is for your condition
if(firstRun==false)//if running for first time
{
SharedPreferences.Editor editor=settings.edit();
editor.putBoolean("firstRun",true);
editor.commit();
//execute your code for first time
}
else
{
if(alldataSaved==false)
{
//stay in this activiy
}
else
{
Intent iSubmit = new Intent(Registration_Form.this,Employee_List.class);
startActivity(iSubmit);
finish();
//Default Activity startActivity(a);
}
}
That's not how Android works. You cannot "restore" the same Activity in that fashion. What you CAN however do is save out the EditText content, for example in the onPause() or onStop() function, save out the contents of the EditTexts as Strings, put them in a List, then serialize that List out into a file. In the onResume() or onStart() method, deserialize this data from the file.
An example for such serialization is shown here, but I'll also paste it here:
Put objects into bundle
Serialization:
private List<String> list = new ArrayList<String>();
#Override
public void onPause()
{
super.onPause();
FileOutputStream out = null;
try
{
out = openFileOutput("ModelBackup",Context.MODE_PRIVATE);
try
{
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(list);
}
catch(IOException e)
{
Log.d(this.getClass().toString(), e.getMessage());
}
}
catch(FileNotFoundException e)
{
Log.d(this.getClass().toString(), e.getMessage());
}
finally
{
try
{
if(out != null) out.close();
}
catch(IOException e)
{
Log.d(this.getClass().toString(), e.getMessage());
}
}
}
Deserialization:
#Override
public void onResume()
{
super.onResume();
FileInputStream in = null;
try
{
in = openFileInput("ModelBackup");
ObjectInputStream oos = new ObjectInputStream(in);
try
{
list = (List<String>)oos.readObject();
}
catch(ClassNotFoundException e)
{
list = null;
}
}
catch(IOException e)
{
Log.d(this.getClass().toString(), e.getMessage());
}
finally
{
try
{
if(in != null) in.close();
}
catch(IOException e) {}
}
}
If restarting an activity from a fragment, I would do it like so:
new Handler().post(new Runnable() {
#Override
public void run()
{
Intent intent = getActivity().getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
getActivity().overridePendingTransition(0, 0);
getActivity().finish();
getActivity().overridePendingTransition(0, 0);
startActivity(intent);
}
});

In App Purchases Not Saving Shared Preferences

I have an android application similar to wheel of fortune where users have the option to purchase one consumable, $1000, and two entitlements, where they unlock two images as wheel styles. I am using the Amazon In-App Purchasing API. The user should be able to purchase as many consumables as they want but once they purchase the entitlements the unlocked image should be the only image that they see and they should no longer see the locked image. These in-app purchases work fine the first instance I initiate these purchases.
However, the consumable field will only update once and even though I can still go through the process of completing purchases for the consumable, the text view containing the score, or money, does not update other then that first initial purchase. Also the wheels return to the locked image rather then remaining as the unlocked image despite the fact that when I initiate the purchase for these entitlements I am told that I already own these items. Therefore I believe it may be something to do with my SharedPreferences. In short my purchases update my views once and then never again, however the backend code i.e the responses I receive from the Amazon client when completing purchases are correct. Can anyone see where I have made a mistake? Why does the textView containing the score update on the 1st purchase and never again from then on? Also how do I save the changes toe the wheel style so that when it reopens they no longer have the option to purchase the wheel? I have three classes and have included the code below. All and any help is greatly appreciated.
Game Class
public class Game extends Activity {
private ImageView wheel;
private int rand;
private int[] amounts = {100,650,-1,650,300,-1,800,250,-1,500};
private int score = 0;
private TextView scoreText;
private AnimatorSet set;
protected boolean animationDone = true;
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
prefs.registerOnSharedPreferenceChangeListener(prefsChanged);
wheel = (ImageView) findViewById(R.id.imageView1);
scoreText = (TextView) findViewById(R.id.score);
score = prefs.getInt("score", 0);
scoreText.setText("$" + String.valueOf(score));
}
private OnSharedPreferenceChangeListener prefsChanged = new OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences prefs,
String key) {
if(key.equals("money") && prefs.getBoolean(key, false)) {
score += 1000;
scoreText.setText("$" + String.valueOf(score));
prefs.edit().putBoolean("money", false);
}
}
};
#Override
protected void onStart() {
super.onStart();
InAppObserver obs = new InAppObserver(this);
PurchasingManager.registerObserver(obs);
}
#Override
protected void onPause() {
if(this.isFinishing())
{
prefs.edit().putInt("score", score).commit();
}
super.onPause();
}
#Override
protected void onStop() {
prefs.edit().putInt("score", score).commit();
super.onStop();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode != RESULT_CANCELED) {
String style = data.getStringExtra("wheel");
if(style.equals("camo"))
wheel.setImageResource(R.drawable.camowheel);
if(style.equals("gold"))
wheel.setImageResource(R.drawable.goldwheel);
if(style.equals("normal"))
wheel.setImageResource(R.drawable.wheel);
}
}
public void spinTheWheel(View v) {
if(animationDone) {
wheel.setRotation(0);
rand = (int) Math.round(2000 + Math.random()*360);
set = new AnimatorSet();
set.play(ObjectAnimator.ofFloat(wheel, View.ROTATION, rand));
set.setDuration(2000);
set.setInterpolator(new DecelerateInterpolator());
set.start();
animationDone = false;
set.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
calculateResult();
animationDone = true;
}
});
}
}
private void calculateResult() {
int angle = (int) wheel.getRotation();
angle %= 360;
angle = (int) Math.floor(angle/36);
if(amounts[angle] == -1) {
Intent intent = new Intent(this, GameOver.class);
intent.putExtra("score", score);
prefs.edit().putInt("score", 0).commit();
score = 0;
startActivity(intent);
}
else {
score += amounts[angle];
scoreText.setText("$"+String.valueOf(score));
prefs.edit().putInt("score", 0).commit();
}
}
public void upgradeWheel(View v) {
Intent intent = new Intent(getApplicationContext(), ChangeWheel.class);
startActivityForResult(intent, 1);
}
public void endGame(View v) {
Intent intent = new Intent(getApplicationContext(), GameOver.class);
intent.putExtra("score", score);
prefs.edit().putInt("score", 0).commit();
score = 0;
startActivity(intent);
}
public void addMoney(View v) {
PurchasingManager.initiatePurchaseRequest("money");
}
}
ChangeWheel Class
public class ChangeWheel extends Activity {
private Button buyCamoButton;
private Button buyGoldButton;
private ImageButton goldButton;
private ImageButton camoButton;
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change_wheel);
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
prefs.registerOnSharedPreferenceChangeListener(prefsChanged);
buyCamoButton = (Button) findViewById(R.id.buyCamo);
buyGoldButton = (Button) findViewById(R.id.buyGold);
goldButton = (ImageButton) findViewById(R.id.goldButton);
camoButton = (ImageButton) findViewById(R.id.camoButton);
goldButton.setEnabled(false);
camoButton.setEnabled(false);
}
private OnSharedPreferenceChangeListener prefsChanged = new OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences prefs,
String key) {
if(key.equals("camo") && prefs.getBoolean(key, false)) {
camoButton.setImageResource(R.drawable.camowheel);
camoButton.setEnabled(true);
buyCamoButton.setVisibility(View.INVISIBLE);
}
else if(key.equals("gold") && prefs.getBoolean(key, false)) {
goldButton.setImageResource(R.drawable.goldwheel);
goldButton.setEnabled(true);
buyGoldButton.setVisibility(View.INVISIBLE);
}
}
};
#Override
protected void onStart() {
super.onStart();
InAppObserver obs = new InAppObserver(this);
PurchasingManager.registerObserver(obs);
}
public void camoClick(View v) {
Intent intent = new Intent(getApplicationContext(), Game.class);
intent.putExtra("wheel", "camo");
setResult(RESULT_OK, intent);
finish();
}
public void goldClick(View v) {
Intent intent = new Intent(getApplicationContext(), Game.class);
intent.putExtra("wheel", "gold");
setResult(RESULT_OK, intent);
finish();
}
public void normalClick(View v) {
Intent intent = new Intent(getApplicationContext(), Game.class);
intent.putExtra("wheel", "normal");
setResult(RESULT_OK, intent);
finish();
}
public void buyCamo(View v) {
String req = PurchasingManager.initiatePurchaseRequest("camo");
prefs.edit().putString(req, "camo").commit();
}
public void buyGold(View v) {
String req = PurchasingManager.initiatePurchaseRequest("gold");
prefs.edit().putString(req, "gold").commit();
}
}
InAppObserver Class
public class InAppObserver extends BasePurchasingObserver {
private SharedPreferences prefs;
public InAppObserver(Activity caller) {
super(caller);
prefs = PreferenceManager.getDefaultSharedPreferences(caller.getApplicationContext());
}
#Override
public void onSdkAvailable(boolean isSandboxMode) {
PurchasingManager.initiatePurchaseUpdatesRequest(Offset.BEGINNING);
}
#Override
public void onPurchaseUpdatesResponse(PurchaseUpdatesResponse res) {
for(String sku : res.getRevokedSkus()) {
prefs.edit().putBoolean(sku, false).commit();
}
switch (res.getPurchaseUpdatesRequestStatus()) {
case SUCCESSFUL:
for(Receipt rec : res.getReceipts()) {
prefs.edit().putBoolean(rec.getSku(), true).commit();
}
break;
case FAILED:
// do something
break;
}
}
#Override
public void onPurchaseResponse(PurchaseResponse res) {
switch(res.getPurchaseRequestStatus()) {
case SUCCESSFUL:
String sku = res.getReceipt().getSku();
prefs.edit().putBoolean(sku, true).commit();
break;
case ALREADY_ENTITLED:
String req = res.getRequestId();
prefs.edit().putBoolean(prefs.getString(req, null), true).commit();
break;
case FAILED:
// do something
break;
case INVALID_SKU:
// do something
break;
}
}
}
It could be that you are not using the same editor.
preferences.edit().putString(PreferenceKey.DISTANCE, distance);
preferences.edit().commit();
two different SharedPreferences.Editors are being returned. Hence the
value is not being committed. Instead, you have to use:
SharedPreferences.Editor spe = preferences.edit();
spe.putString(PreferenceKey.DISTANCE, distance);
spe.commit();
From... SharedPreferences not working across Activities

how to sign in automatically using sharedpreferences in android

i have splash activity that will be directed to login activity, if login is true, then the user will be direct to home, but when the user press back in home, application will be closing automatically.
but the problem is when user open application, they must be login again, even they not logout before. so how to direct splash into home activity? i have read, to handle it i must used sharedpreferences so i have to used it, but i don't how to handle login automatically using it.
this is my spash:
public class SplashEpolicy extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
//hide title bar
BasicDisplaySettings.toggleTaskBar(SplashEpolicy.this, false);
//show status bar
BasicDisplaySettings.toggleStatusBar(SplashEpolicy.this, true);
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_epolicy);
Thread timer = new Thread() {
public void run() {
try {
//this is configuration for how long the splash will be shown.
//
int time = Integer.parseInt(getResources().getString(R.string.splashTransTime));
sleep(time);
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
} finally {
//line below is for direct new activity that will be run after
//current activity finished.
Intent intent = new Intent(SplashEpolicy.this,EpolicyMainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}
};
timer.start();
}
this is my login activity that containing sharedpreferences:
String KEY = jo.getString("key");
SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("etUser", strUser);
editor.putString("key",KEY);
editor.commit();
System.out.println(KEY+""+"key"+""+"etUser");
Dialog.dismiss();
Intent i = new Intent(LoginActivity.this,EpolicyMainTab.class);
startActivity(i);
}
}catch (JSONException e) {
e.printStackTrace();
}
so this is my Home (EpolicyListPolisActivity):
public class EpolicyListPolis extends ListActivity {
static String PEMEGANG="PEMEGANG";
static String POLIS="POLIS";
static String STATUS="STATUS";
static String TERTANGGUNG="TERTANGGUNG";
String KEY, strUser;
List NasabahList= new ArrayList();
private ProgressDialog Dialog;
private String strStoragePath = "",
strNameFileDiv = "";
ImageView LogoutButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.Nomor_Polis);
setContentView(R.layout.epolicy_list_polis);
SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
strUser= settings.getString("etUser", null);
KEY = settings.getString("key", null);
LogoutButton=(ImageView)findViewById(R.id.LogoutButton);
new NasabahAsyncTask().execute();
LogoutButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
dialogSignOut();
}
});
}
public class NasabahAsyncTask extends AsyncTask<Void, Void, String>{
String url = ("http://www.example.com?i="+strUser+"&k="+KEY);
public NasabahAsyncTask() {
this.url=url;
// TODO Auto-generated constructor stub
}
protected void onPreExecute() {
super.onPreExecute();
Dialog = ProgressDialog.show(EpolicyListPolis.this, "", "Melakukan Pengambilan Data");
}
#Override
protected String doInBackground(Void... params) {
String result="";
try {
result=Connection.get(url);
}catch (Exception e){
result=" ";
Log.d("test viewer",e.getMessage());
}
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
fetchResponse(result.replace("\n", "").trim());
ListAdapter adapter = new SimpleAdapter(
EpolicyListPolis.this, NasabahList, R.layout.epolicy_polis_listitem,
new String[] {POLIS, PEMEGANG, TERTANGGUNG, STATUS}, new int [] {R.id.polis, R.id.pemegang, R.id.tertanggung, R.id.status});
setListAdapter(adapter);
Dialog.dismiss();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String POLIS = ((TextView)view.findViewById(R.id.polis)).getText().toString();
SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("POLIS", POLIS);
editor.commit();
}
}
private void fetchResponse(String result) {
// TODO Auto-generated method stub
if (!result.equals("")) {
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
if (jsonObject.has("PEMEGANG"))
map.put("PEMEGANG", jsonObject.get("PEMEGANG").toString());
if (jsonObject.has("POLIS"))
map.put("POLIS", jsonObject.get("POLIS").toString());
if (jsonObject.has("STATUS"))
map.put("STATUS", jsonObject.get("STATUS").toString());
if (jsonObject.has("TERTANGGUNG"))
map.put("TERTANGGUNG", jsonObject.get("TERTANGGUNG").toString());
NasabahList.add(map);
System.out.println("json oke");
}
}catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onBackPressed() {
dialogExit();
}
public void dialogExit()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("do you want to exit?")
.setCancelable(false)
.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent itSplashEnd = new Intent(EpolicyListPolis.this, SplashEnd.class);
//setIntent.addCategory(Intent.CATEGORY_HOME);
itSplashEnd.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
itSplashEnd.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(itSplashEnd);
finish();
System.exit(0);
}
})
.setNegativeButton("no", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void dialogSignOut()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Sign out?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// what will i do here?
Intent itSignOut = new Intent(EpolicyListPolis.this, EpolicyMainActivity.class);
itSignOut.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(itSignOut);
finish();
}
})
.setNegativeButton("no", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
so how to sign in automatically into home without going to login activity again using sharedpreferences? and how to clear data that saved in sharedpreferences every time user sign out?
To sign in automatically:
Check if login details are saved in SharedPreferences. If found, you can retrieve that value and login automatically.
SharedPreferences prefs = this.getSharedPreferences("YOUR_PREF_NAME", Context.MODE_PRIVATE);
String loginID = prefs.getString("LOGIN_ID", "");
String loginPWD = prefs.getString("LOGIN_PWD", "");
if (loginID.length()>0 && loginPWD.length()>0) {
//YOUR LOGIN CODE
} else {
//SHOW PROMPT FOR LOGIN DETAILS
}
To clear the data when sign out, you can use the below piece of code in your sign out command:
SharedPreferences prefs = this.getSharedPreferences("YOUR_PREF_NAME", Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putString("LOGIN_ID", ""); //RESET TO DEFAULT VALUE
editor.putString("LOGIN_PWD", ""); //RESET TO DEFAULT VALUE
editor.commit();
I don't know what is wrong with Gokul Nath answer, but let's try again.
You can check if user already logged in by a simple if. First you load your user data (let's suppose username and password):
SharedPreferences prefs = this.getSharedPreferences("com.project.myProject", Context.MODE_PRIVATE);
String savedUser = "com.project.myProject.savedUser";
String user = prefs.getString(savedUser, "none"); // return "none" if user is not logged in
String savedPass = "com.project.myProject.savedPass";
String pass = prefs.getString(savedPass, "none");
if (user.equalsIgnoreCase("none") || pass.equalsIgnoreCase("none")) {
// Show a log in dialog and/or other stuff to let user log in
} else {
// Launch your main interface
}
This works if you launch the app for the first time or after a logout.
On logout you can clear all your SharedPreferences like this (N.B.: clear or reset SharedPreferences is the same for me):
YourActivity.this.getSharedPreferences("com.project.myProject", Context.MODE_PRIVATE).edit().clear().commit();
By doing this, if user launch again your app, he will have to log in again.
Another things that i saw in your code is this:
Intent intent = new Intent(SplashEpolicy.this,EpolicyMainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
I guess you addFlags on intent because when you press back button, your app go back in SplashEpolicy. If i'm right you can do better in your code, by adding this line "android:noHistory="true"" in your Manifest (if i'm wrong, skip this part of my answer):
<activity
android:name="com.project.myProject.SplashEpolicy"
android:label="#string/app_name"
android:noHistory="true" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
With this your splash activity will not leave a historical trace. It will not remain in the activity stack for the task, so the user will not be able to return to it (cit. Android Dev site).
You could use a boolean to keep a track of the login state, that is, true if logged in and false otherwise. You could check the value of this boolean variable at splash screen so that you open the login dialog just in case it is false.
Here is a simple way to store the above mentioned boolean:
SharedPreferences sharedPrefs = getSharedPreferences("youPrefsFile", 0);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putBoolean("isLoggedIn", true);
editor.commit();
And a simple way to get its value:
SharedPreferences settings = getSharedPreferences("youPrefsFile",0);
boolean isLoggedin = settings.getBoolean("isLoggedIn", false);
Hope it helps.
you can do this by using Shared Preferences.
use one boolean flag as
boolean signedflag=false;
store this flag in shared preferences.
check this flag at the time of login if 'signedflag=false' then only store 'login detail(login name and password)' to shared preferences else use existing value.
and when u will logout clear your all shared-preference variable and make the signedflag=false again.
Save the loggedInUser in shared preferences on successful login like:
SharedPreferences sharedPrefs = getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putBoolean("isLoggedIn", true);
editor.commit();
And check is logged in like this:
SharedPreferences prefs = this.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
boolean isLoggedIn = prefs.getString(isLoggedIn, false); // return "false" if user is not logged in
if (!isLoggedIn) {
// Show a log in dialog and/or other stuff to let user log in
} else {
// Launch your main interface
}

Categories