In my application, On the MainActivity.java I need to display two layouts, One is visible in the initial stage and the other is invisible. When a button is pressed the invisible one get visible and visible one get invisible, here is the code i have writen:
public class MainActivity extends AppCompatActivity {
DrawerLayout drawerLayout;
SupportMapFragment supportMapFragment;
SupportMapFragment supportMapFragment1;
FusedLocationProviderClient client;
View checkoutLayout, checkinLayout;
ImageButton checking_button, checkout_button;
Chronometer chronometer;
Handler handler;
long tMillisec, tStart, tBuff, tUpdate = 0L;
int sec, min, millisec, hr;
TextView tv_location, editText_remark, location_checkout, location_remark, dateView, timeView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
String date = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
String currentTime = new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date());
checking_button = findViewById(R.id.checkin_btn);
chronometer = findViewById(R.id.chrono);
checkoutLayout = findViewById(R.id.checkOut);
checkinLayout = findViewById(R.id.checkinLayout);
checkout_button = findViewById(R.id.checkout_btn);
tv_location = findViewById(R.id.tv_location);
editText_remark = findViewById(R.id.editText_remark);
location_checkout = findViewById(R.id.location_checkout);
location_remark = findViewById(R.id.Remark_checkout);
dateView = findViewById(R.id.date_pick);
timeView = findViewById(R.id.time_pick);
checkinLayout.setVisibility(View.VISIBLE);
checkoutLayout.setVisibility(View.INVISIBLE);
handler = new Handler();
drawerLayout = findViewById(R.id.drawer_layout);
supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map_view);
supportMapFragment1 = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_view1);
client = LocationServices.getFusedLocationProviderClient(this);
// check permission
if(ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
// when permission granted call method
getCurrentLocation();
}else{
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 44);
}
checking_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(tv_location.getText().toString().isEmpty() || editText_remark.getText().toString().isEmpty()){
Toast.makeText(getApplicationContext(), "Please Enter your Location and Remark", Toast.LENGTH_SHORT).show();
}else {
checkoutLayout.setVisibility(v.VISIBLE);
checkinLayout.setVisibility(v.GONE);
tStart = SystemClock.uptimeMillis();
handler.postDelayed(runnable, 0);
chronometer.start();
location_checkout.setText(tv_location.getText().toString());
location_remark.setText(editText_remark.getText().toString());
dateView.setText("Date:"+ date);
timeView.setText("Punch-In:"+ currentTime);
}
}
});
checkout_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkinLayout.setVisibility(v.VISIBLE);
checkoutLayout.setVisibility(v.GONE);
}
});
}
The code works good but the problem is when i make checkoutLayot visible and checkinLayout invisible, when i close the app and reopen it the layout changes to checkoutLayout invisible and checkinLayout visible, So i need to make the last visited page visible. I am new to android development, can any one help me to solve the problem.
You have to use SharePreference for this, to save the state that your app was in when the user closed the app. Save the state in the sharedpreference as soon as user presses a button and then in onStart method of the app, you can get the value of the state from the SharePreference and then show your layouts accordingly.
First thing first you should put all your variables including views(like Textview, Handler etc. private). Secondly our friend #rootass here is right you should use SharePrference so you can save changes. Here is an example of writing and getting SharedPreferences. Code for Wrting SharedPreferences ...
private SharedPreferences visibilityPreference;
private SharedPreferences.Editor prefEdit;
private final String visibilityKey = "visibility";
private void setVisibility(boolean flag){
prefEdit = visibilityPreference.edit();
visibilityPreference = context.getSharedPreferences(visibilityPreferenceName, Context.MODE_PRIVATE);
visibilityPreference.putBoolean(visibilityKey, flag);
prefEdit.apply();
}
And here code for reading SharedPreferences...
private boolean getVisibility(){
visibilityPreference = context.getSharedPreferences(visibilityPreferenceName, Context.MODE_PRIVATE);
return visibilityPreference .getBoolean(visibilityKey, false); //we set false as default value
}
ps : since you are new to android i probably should mention that instead of context in mentioned code above if you are in independtend activity you do not need to use context just put this or nothing and of you are not in an independent activity, in case of fragment use context or requireActivity() and in case of being in recyclerview use passed context.
Hope it helps you ;)
Related
I am trying to change the text on a button after setOnLongClickListener amd there are six buttons to choose from. Currently, regardless of which button I click, the list button is updated with the new text.
I think I have tried everything on this thread:
setonlongclicklistener for several buttons at once
Eventually i hope to save these new button values to shared preferences so they are there when the app is next started.
public class MainActivity extends AppCompatActivity {
private Button btn;
Context context;
final String[] task = new String[1];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = MainActivity.this;
Resources r = getResources();
String pName = getPackageName();
String PREFERENCES_FILE_KEY = "com.example.buttondemo";
String SECURE_PREFS_FILE_KEY = "com.example.buttonnames";
// Declare shared preferences
SharedPreferences sharedPreferences = this.getSharedPreferences(PREFERENCES_FILE_KEY, Context.MODE_PRIVATE);
// get shared preferences for each button and apply the stored name to each button
//String buttonText = sharedPreferences.getString("Value01", "Button_01");
for (int i=1;i<=6;i++) {
String buttonId = "button" + i;
btn = (Button) findViewById(r.getIdentifier(buttonId, "id", pName));
btn.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
task[0] = showAddItemDialog(MainActivity.this, btn);
//sharedPreferences.edit().putString(buttonId, task[0]).apply();
return true;
}
});
}
}
private String showAddItemDialog(Context context, Button btnNew) {
final EditText taskEditText = new EditText(context);
taskEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});
final String[] task = new String[1];
AlertDialog dialog = new AlertDialog.Builder(context)
.setTitle("Enter New button value")
.setMessage("Enter New button value:")
.setView(taskEditText)
.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
task[0] = String.valueOf(taskEditText.getText());
btnNew.setText(String.valueOf(taskEditText.getText()));
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
return task[0];
}
}
Thanks.
What's happening is the btn variable is getting reassigned each iteration of your loop. Therefore once the long click listener fires, you are calling showAddItemDialog(this, btn) where btn is holding a reference to whatever it was set to in the last loop iteration (when i = 6).
So the behaviour you're experiencing makes sense. Hopefully this is enough to point you in the right direction.
As a side note, finding views based on dynamic ids that come from r.getIdentifier() might be a bit of a bad design choice and could open up bugs in the future. I would recommend simplifying it to just use R.id.button1, R.id.button2 etc. if possible.
I am working on a Quiz app. First when a user opens the app they go to the MainActivity, from there when they press start they go to the Categories Activity , from there after selecting a category they go to the Sets Activity, from there after selecting a set the go to the Questions Activity and finally after completing all the questions they reach the Score Activity. Here in the score activity when the click on Done button they are redirected to the MainActivity. In the Score Activity i want to change the color of the Set that they completed to green instead of the default color. How can i do this? I created a sets item layout xml file and used an adapter to fill the gridview in the Sets Activity with views from the adapter. Currently i am getting a null object reference after clicking the Done button in the ScoreActivity.
Here is the code :
SetsAdapter.java
public class SetsAdapter extends BaseAdapter {
private int numOfSets;
public SetsAdapter(int numOfSets) {
this.numOfSets = numOfSets;
}
#Override
public int getCount() {
return numOfSets;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View view;
if(convertView == null){
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.set_item_layout, parent, false);
}
else {
view = convertView;
}
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent questionIntent = new Intent(parent.getContext(), QuestionActivity.class);
questionIntent.putExtra("SETNUM", position +1);
parent.getContext().startActivity(questionIntent);
}
});
((TextView) view.findViewById(R.id.setNumber)).setText(String.valueOf(position+1));
return view;
}
}
SetsActivity.java
public class SetsActivity extends AppCompatActivity {
private GridView sets_grid;
private FirebaseFirestore firestore;
public static int categoryID;
private Dialog loadingDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sets);
Toolbar toolbar = (Toolbar)findViewById(R.id.set_toolbar);
setSupportActionBar(toolbar);
String title = getIntent().getStringExtra("CATEGORY");
categoryID = getIntent().getIntExtra("CATEGORY_ID",1);
getSupportActionBar().setTitle(title);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
sets_grid = findViewById(R.id.sets_gridView);
loadingDialog = new Dialog(SetsActivity.this);
loadingDialog.setContentView(R.layout.loading_progressbar);
loadingDialog.setCancelable(false);
loadingDialog.getWindow().setBackgroundDrawableResource(R.drawable.progress_background);
loadingDialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
loadingDialog.show();
firestore = FirebaseFirestore.getInstance();
loadSets();
}
private void loadSets() {
firestore.collection("Quiz").document("CAT" + String.valueOf(categoryID))
.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot doc = task.getResult();
if (doc.exists()) {
long sets = (long) doc.get("SETS");
SetsAdapter adapter = new SetsAdapter(Integer.valueOf((int)sets));
sets_grid.setAdapter(adapter);
} else {
Toast.makeText(SetsActivity.this, "No Sets Exists!", Toast.LENGTH_SHORT).show();
finish();
}
} else {
Toast.makeText(SetsActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
loadingDialog.cancel();
}
});
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
}
ScoreActivity.java
public class ScoreActivity extends AppCompatActivity {
private TextView score;
private Button done;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score);
score = findViewById(R.id.score_tv);
done = findViewById(R.id.score_activity_done);
String score_str = getIntent().getStringExtra("SCORE");
final int setNum = getIntent().getIntExtra("SetNum", 1);
score.setText(score_str);
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Here is the issue I am facing
View view = findViewById(R.id.setNumber);
view.setBackgroundColor(Color.GREEN);
Intent mainIntent = new Intent(ScoreActivity.this, MainActivity.class);
startActivity(mainIntent);
ScoreActivity.this.finish();
}
});
}
}
As your activity Sequence is MainActivity -> Categories -> Sets -> Scores.
You've two options to change the color with two different life cycle of the change.
To change the color on a temporary basis, this will reset itself after closing the app or resrtating the 'Sets' activity. It can be done in two ways: Using Public Static Variable and using a public function.
To change the color on a permanent basis until the app is uninstalled/reinstalled. You should use SharedPreferences. SharedPreferences acts like a private data stored in device's memory for further use and it stays there unchanged until and unless the app is removed/data is cleared. Although, apps with root permission can access any app's SharedPreferences data and can modify it as well.You can use SharedPreferences as explained here. Or, you can use some library to access it an easy way. The way I use it in all my apps is TinyDB(it's just a java/kotlin file). This works as:
//store the value from ScoreActivity after completion as
TinyDB tinyDB = TinyDB(this);
tinyDB.putBoolean("isSet1Completed",true);
//access the boolean variable in SetsActivity to change the color of any set that
//is completed and if it's true, just change the color.
TinyDB tinyDB = TinyDB(this);
Boolean bool1 = tinyDB.getBoolean("isSet1Completed");
But, it's your choice what way you want to prefer.
Now, this was about the lifecycle of the change you'll do: Temp or Permanent. Now, we'll talk about how you change the color.
Using public static variable in Sets activity. What you can do is you can set the imageView/textview whose background you want to change as public static variable. Remember, this idea is not preferred as it causes memory leak but it's just easy.
Declare it as public static ImageView imageview;(or TextView) intialize it in the
onCreated() as imageView = finViewById(R.id.viewId); in Sets activity. Call
it as new SetsActivity().imageView.setBackgroundColor(yourColor); in ScoreActivity.
Second way is to create a public function in SetsAcitvity, putting the color change code in it, and then calling it from the ScoreActivity. Just declare it as public void changeColor(){ //your work} and call it from ScoreActivity as new SetsActivity().changeCOlor(). You can also pass some arguments to the function like setId.
I've provided you every thing you need. Rest you should figure out yourself to actually learn it and not copy it.
I think simply you add flag in MainActivity.
for example, add flag in MainActivity.
boolean isFromDone = false;
and when done clicked,
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Here is the issue I am facing
Intent mainIntent = new Intent(ScoreActivity.this, MainActivity.class);
mainIntent.putExtra("FromDone", true);
startActivity(mainIntent);
ScoreActivity.this.finish();
}
});
and in MainActivity, add this.
#Override
protected void onResume() {
super.onResume();
isFromDone = getIntent().getBooleanExtra("FromDone", false);
if(isFromDone) {
(TextView) view.findViewById(R.id.setNumber)).setBackgroundColor(Color.GREEN);
}
}
Suppose you have a Linear Layout in Activity A and you want to change it's background color from a button click which is present in Activity B.
Step 1 Create a class and declare a static variable.
class Util { private static LinearLayout mylayout ; }
Step 2
In the activity which is holding this layout, initialize it.
Util.mylayout = findviewbyid(R.id.linear);
Step 3Change the background color on button click from Activity B
onClick{
Util.mylayout.setBackgroundColor(Color.RED);
}
I have an Activity in which I want to ask for a PIN code. In this Activity the user can go to a separate Activity in which he can set the PIN. If no PIN is set, then a default PIN should be used.
This is the code of the first Activity:
public class activity_identification extends AppCompatActivity {
SharedPreferences pins_pref = null;
EditText pin_entry = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_identification);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
pin_eingabe = (EditText) findViewById(R.id.et_pin_entry);
pins_pref = getApplicationContext().getSharedPreferences("UserPin", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = pins_pref.edit();
edit.putString("default_pin", "0000");
edit.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_pin_identifikation, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_change_pin) {
startActivity(new Intent(this, pin_settings.class));
return true;
}
else if (id == R.id.home) {
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public void onClickPinSummit(View button){
if(pin_entry.getText().toString().equals( pins_pref.getString("user_pin", null).toString())) {
Toast.makeText(this, "Authorization Right", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "Authorization Wrong", Toast.LENGTH_SHORT).show();
}
}
}
And this is the second Activity:
public class pin_settings extends AppCompatActivity {
EditText et_old_pin = null;
EditText et_new_pin = null;
EditText et_new_pin_repeat = null;
Button btn_pin_save = null;
TextView tv_sharedPIN = (TextView) null;
SharedPreferences pins_prefs = null;
private String default_pin = null;
private String user_pin = null;
private String old_pin = null;
private String new_pin = null;
private String new_pin_repeat = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pin_einstellungen);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
et_old_pin = (EditText) findViewById(R.id.et_old_pin);
et_new_pin = (EditText) findViewById(R.id.et_new_pin);
et_new_pin_repeat = (EditText) findViewById(R.id.et_new_pin_repeat);
btn_pin_save = (Button) findViewById(R.id.btn_pin_save);
tv_sharedPIN = (TextView) findViewById(R.id.sharedPIN);
pins_prefs = getApplicationContext().getSharedPreferences("UserPin", Context.MODE_PRIVATE);
general_pin = pins_prefs.getString("default_pin", null);
tv_sharedPIN.setText(pins_prefs.getString("general_pin", null));
}
public void onClickNewPinSave(View button){
old_pin = et_old_pin.getText().toString();
new_pin = et_new_pin.getText().toString();
new_pin_repeat = et_new_pin_repeat.getText().toString();
if(old_pin.equals(pins_prefs.getString("default_pin",null).toString())){
if (new_pin.equals(new_pin_repeat)){
SharedPreferences.Editor edit = pins_prefs.edit();
edit.putString("user_pin", user_pin);
edit.commit();
tv_sharedPIN.setText(pins_prefs.getString("user_pin", null));
} else {
Toast.makeText(this, "New Pins are not the same", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "Old Pin is wrong.", Toast.LENGTH_LONG).show();
}
}
}
Now the problem is that the app does not save the PIN which is set in the second Activity. It works as long as the app is open, but as soon as I restart it the PIN reverts back to the default PIN. I think this is because I set the default PIN in the onCreate() method of the first Activity, but I just can't figure out how to get around doing that.
Of course the PIN will always be reset to the default since you set it each time on startup. All you need to do to fix that is remove that line and instead use the default value which is passed into getString() correctly.
You don't need to set the default PIN at all! Remove all of that from onCreate()
getString() accepts a default value as second parameter. This default value is returned if no value is set. Let me repeat that: The default value is return if no value has been set.
So instead of setting the default PIN in onCreate() you can simply pass in the default PIN into getString() and if no PIN has been set, getString() will then return the default PIN. So what you are looking for is this:
String pin = preferences.getString("default_pin", "0000");
On a side note: Please adhere to the common Java naming conventions. Also don't hardcode so many Strings. Use constants instead.
EDIT: As Xaver Kapeller pointed out my earlier solution wont work. Although his one is simpler, i'll fix mine just because
Set default_pin to 0000 if getString(default_pin, "-1") returns "-1".
OLD: Try only setting the default_pin to 0000 if default_pin is null, which will only happen at the very first launch of your activity
I have made an application. It's a button that shows the time you have pressed it. Every time I "kill" the application, the timer starts at 0 again (naturally). How can I make the application save the time the button is pressed, so when the application is killed, and then you open it, the timer is at that time you stopped.I have red some about how this is done, and I think it has something to do with SharedPreferences.
My code:
public class MainActivity extends ActionBarActivity {
Button button1;
Chronometer chromo;
protected long time;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1=(Button)findViewById(R.id.button1);
chromo=(Chronometer)findViewById(R.id.chromo);
button1.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN){
chromo.setBase(SystemClock.elapsedRealtime()+time);
chromo.start();
}
else if( event.getAction() == MotionEvent.ACTION_UP){
time =chromo.getBase()-SystemClock.elapsedRealtime();
chromo.stop();
}
return true;
}
});
}}
Saving in SharedPreferences :
SharedPreferences prefs= getSharedPreferences("prefs", Context.MODE_PRIVATE);
// We use an editor to insert values in SharedPreferences
Editor editor = prefs.edit();
// Saving the values
editor.putLong("myTime", time);
// Committing the changes
editor.commit();
Retrieving saved values :
long savedValue = 0l;
SharedPreferences prefs= getSharedPreferences("prefs", Context.MODE_PRIVATE);
if (prefs.contains("hello")){
savedValue = sharedpreferences.getLong("myTime", 0l));
}
EDIT :
public class MainActivity extends ActionBarActivity {
Button button1;
Chronometer chromo;
protected long time = 0;
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1=(Button)findViewById(R.id.button1);
chromo=(Chronometer)findViewById(R.id.chromo);
prefs = getSharedPreferences("prefs", Context.MODE_PRIVATE);
long savedValue = prefs.getLong("my_chrono", 0);
if(savedValue == 0)
chromo.setBase(SystemClock.elapsedRealtime());
else
chromo.setBase(SystemClock.elapsedRealtime() + savedValue);
button1.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN){
chromo.start();
}
else if( event.getAction() == MotionEvent.ACTION_UP){
time =chromo.getBase()-SystemClock.elapsedRealtime();
chromo.stop();
prefs.edit().putLong("my_chrono", time).apply();
}
return true;
}
});
}}
============================================================================
To use the shared preferences, initialize this in you onCreate
SharedPreferences prefs = getSharedPreferences("the_package_of_your_app", Context.MODE_PRIVATE);
Then, try to get the saved value
int my_saved_value = prefs.getInt("the_package_of_your_app.my_int_1", 0);
if(my_saved_value != 0)
//your value of your timer was saved, do what's needed with it
else
//there was no value saved, or the timer was at 0
Now you have to save that value when needed (when the timer is stopped, or the application is closed)
prefs.edit().putInt("the_package_of_your_app.my_int_1", my_value).apply();
To elaborate on #2Dee's answer:
SharedPreferences prefs= getSharedPreferences("prefs", Context.MODE_PRIVATE);
// We use an editor to insert values in SharedPreferences
Editor editor = prefs.edit();
// Saving the values
editor.putLong("myTime", time);
// Committing the changes
editor.commit();
can go into the
protected void onDestroy();
method. This method can be overloaded in an Activity to be called as the activity is destroyed (killed, closed, etc) so that any data may be saved (which is what you want to do).
Likewise,
SharedPreferences prefs= getSharedPreferences("prefs", Context.MODE_PRIVATE);
time = sharedpreferences.getLong("myTime", 0l);
can go into the
protected void onCreate(Bundle savedInstanceState);
method. This method is called when the activity is first created. This will set your time to the saved value (defaulting to 0 if there is none).
If for some reason these need to be called at different times (such as later or earlier in the Activity's lifecycle) you can read more about it here.
If you like this answer, please upvote 2Dee's answer as well. Some of the code is literally copy/pasted from there.
Happy Coding! Leave a comment if you have more questions.
i have posting question in here but i got nothing, so i decide to make a new question for searching other solution.
this is my case : First, I was using Shared preferences for my application for sending data from one activity to another, when listview is clicked in first activity, it will going to detail. when other list is clicked, it will going to first data that i've clicked before it. then i realize if i use sharedpreferences for sending data from one activity to other activity, it will save in device memory, so i change my code and decide to use intent, but my sharedpreferences's file is not remove. when list is clicked, it will going to first data that i've clicked when i use shared preferences.
I have used:
settings.edit().clear().commit();
and
settings.edit().remove().commit();
but i think it doesn't work. this is my first activity using intent:
public class TerbaruSimasCard extends ListActivity {
String nama1,alamat1,ket1,img_id1,telp1,begdate1,enddate1;
private ProgressDialog dialog;
private ArrayList<TerbaruModel>ListTerbaru;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
//hide title bar
BasicDisplaySettings.toggleTaskBar(TerbaruSimasCard.this, false);
//show status bar
BasicDisplaySettings.toggleStatusBar(TerbaruSimasCard.this, true);
SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
settings.edit().clear().commit();
super.onCreate(savedInstanceState);
setContentView(R.layout.terbarusimascard);
ListTerbaru= new ArrayList<TerbaruModel>();
new TerbaruAsyncTask().execute();
}
public class TerbaruAsyncTask extends AsyncTask<Void, Void, String> {
String url = ("http://www.abc.xyz/sc_merchant.htm?s=3&d=25");
public TerbaruAsyncTask() {
this.url=url;
}
protected void onPreExecute (){
super.onPreExecute();
dialog = ProgressDialog.show(TerbaruSimasCard.this,"", "melakukan pengambilan data...");
}
#Override
protected String doInBackground(Void... params) {
String result = "";
try {
result= Connection.get(url);
} catch (Exception e){
result = "";
Log.d("test", e.getMessage());
}
return result;
}
#Override
protected void onPostExecute (String result){
super.onPostExecute(result);
fetchResponse(result.replace("\n","").trim());
dialog.dismiss();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent detail= new Intent (TerbaruSimasCard.this, TerbaruDetail.class);
detail.putExtra("nama", nama1);
detail.putExtra("alamat",alamat1);
detail.putExtra("ket", ket1);
detail.putExtra("telp",telp1);
detail.putExtra("begdate", begdate1);
detail.putExtra("enddate",enddate1);
detail.putExtra("img_id", img_id1);
System.out.println(nama1);
startActivity (detail);
}
});
}
}
private void fetchResponse (String result){
if (!result.equals("")){
try {
JSONArray jsonArray = new JSONArray(result);
TerbaruModel LT=null;
for (int i= 0; i < jsonArray.length(); i++) {
JSONObject jsonObject= jsonArray.getJSONObject (i);
LT= new TerbaruModel (jsonObject.optString("kat"),
img_id1=jsonObject.optString("img_id"),
nama1= jsonObject.optString("nama"),
alamat1=jsonObject.optString("alamat"),
ket1=jsonObject.optString("ket"),
jsonObject.optString("tgl"),
jsonObject.optString("accday"),
telp1=jsonObject.optString("telp"),
begdate1=jsonObject.optString("begdate"),
enddate1=jsonObject.optString("enddate")
);
ListTerbaru.add(LT);
list=(ListView)findViewById(android.R.id.list);
setListAdapter (new TerbaruAdapter(this, ListTerbaru));
}
this is for detail:
public class TerbaruDetail extends Activity {
String nama1,alamat1,ket1,img_id1,telp1,begdate1,enddate1;
#Override
public void onCreate (Bundle savedInstanceState){
SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
settings.edit().clear().commit();
//hide title bar
BasicDisplaySettings.toggleTaskBar(TerbaruDetail.this, false);
//show status bar
BasicDisplaySettings.toggleStatusBar(TerbaruDetail.this, true);
super.onCreate(savedInstanceState);
setContentView(R.layout.detailviewer);
Intent detail= getIntent();
nama1=detail.getStringExtra("nama");
alamat1= detail.getStringExtra("alamat");
ket1= detail.getStringExtra("ket");
img_id1= detail.getStringExtra("img_id");
telp1= detail.getStringExtra("telp");
begdate1= detail.getStringExtra("begdate");
enddate1= detail.getStringExtra("enddate");
System.out.println(nama1+"nama");
TextView detail_phone=(TextView) findViewById(R.id.detail_phone);
TextView detail_begdate=(TextView) findViewById(R.id.begdate);
TextView detail_enddate=(TextView) findViewById(R.id.endate);
TextView detail_name =(TextView) findViewById(R.id.detail_name);
TextView detail_adress =(TextView) findViewById(R.id.detail_adress);
TextView keterangan =(TextView) findViewById(R.id.keterangan);
ImageView detail_img_id= (ImageView) findViewById(R.id.img_kategori);
detail_name.setText(nama1);
detail_phone.setText(telp1);
detail_begdate.setText(begdate1);
detail_enddate.setText(enddate1);
detail_adress.setText(alamat1);
keterangan.setText(ket1);
}
If You do not mind just delete the app then reload the apk.
From what I know the Shared Preferences value will remain until you uninstall an app.
If the above did not work then try to deleted manually
/data/data/com.package.name/shared_prefs/PREFS_NAME.xml
If you just want to clear out your data (because it is corrupt or whatever), you can do that manually from the home screen. setting -> application manager -> "your app" -> clear data
SharedPreferences.Editor.clear() will not delete the sharedpreferences file, it only clears the contents in this file.
If you really want to delete this file, you should use file operation , sharedprefereces file location is /data/data/com.yourpackage.name/shared_prefs/filename.xml. BTW, you'd better use intent to send data between activities.