Here is my code it is working please tell me code button for "no thanks" if user tap on this button then dialog box never show at all
public class MainActivity extends Activity {
Button btnRegId;
EditText etRegId;
String regID;
GoogleCloudMessaging gcm;
String regid,url;
//String PROJECT_NUMBER = "90787073097";
String PROJECT_NUMBER = "440085976573";
String android_id,version,ver;
ImageView mega4,todayTips,latstnews,sportquiz,tipister;
TextView txtname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// etRegId = (EditText) findViewById(R.id.edtvID);
//********************For Rating APP **********************
SharedPreferences sharedPrefs = MainActivity.this.getSharedPreferences("RATER", 0);
SharedPreferences.Editor prefsEditor = sharedPrefs.edit();
long time = sharedPrefs.getLong("displayedTime", 0);
if (time < System.currentTimeMillis() - 259200000) {
displayDialog();
prefsEditor.putLong("displayedTime", System.currentTimeMillis()).commit();
}
}
//dialog box Function for rating app.
private void displayDialog() {
// TODO Auto-generated method stub
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
Intent in = new Intent(android.content.Intent.ACTION_VIEW);
in.setData(Uri.parse(url));
startActivity(in);
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Rate This App");
builder.setMessage("You really seem to like this app, "
+"since you have already used it %totalLaunchCount% times! "
+"It would be great if you took a moment to rate it.")
.setPositiveButton("Rate Now", dialogClickListener)
.setNegativeButton("Latter", dialogClickListener)
.setNeutralButton("No,thanks", dialogClickListener).show();
}
//End dialog box Function for rating app.
}
Here is my code actually i want to implement app rating dialog box in application that should display once in three day
You have to initialize your SharedPreferences and Editor Object like this:
SharedPreferences prefs = mContext.getSharedPreferences("RATER", 0);
SharedPreferences.Editor editor = prefs.edit();
UPDATE
Just save a boolean when user cliks on no thanks and check it before showing the dialog. If it true then it will not show the dialog box.
//Saving a boolean on no thanks button click
SharedPreferences prefs = mContext.getSharedPreferences("RATER", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("NO THANKS", true));
editor.apply();
Access it in your dialog showing method.
SharedPreferences prefs = mContext.getSharedPreferences("RATER", 0);
if (prefs.getBoolean("NO THANKS", false)) {
return;
}else {
SharedPreferences.Editor editor = prefs.edit();
//YOUR CODE TO SHOW DIALOG
editor.apply();
}
FULL CODE
public class MainActivity extends Activity {
Button btnRegId;
EditText etRegId;
String regID;
GoogleCloudMessaging gcm;
String regid, url;
//String PROJECT_NUMBER = "90787073097";
String PROJECT_NUMBER = "440085976573";
String android_id, version, ver;
ImageView mega4, todayTips, latstnews, sportquiz, tipister;
TextView txtname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// etRegId = (EditText) findViewById(R.id.edtvID);
//********************For Rating APP **********************
SharedPreferences sharedPrefs = MainActivity.this.getSharedPreferences("RATER", 0);
if (sharedPrefs.getBoolean("NO THANKS", false)) {
return;
} else {
SharedPreferences.Editor prefsEditor = sharedPrefs.edit();
//YOUR CODE TO SHOW DIALOG
long time = sharedPrefs.getLong("displayedTime", 0);
if (time < System.currentTimeMillis() - 259200000) {
displayDialog();
prefsEditor.putLong("displayedTime", System.currentTimeMillis()).commit();
}
prefsEditor.apply();
}
}
//dialog box Function for rating app.
private void displayDialog() {
// TODO Auto-generated method stub
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
Intent in = new Intent(android.content.Intent.ACTION_VIEW);
in.setData(Uri.parse(url));
startActivity(in);
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
//Saving a boolean on no thanks button click
SharedPreferences prefs = MainActivity.this.getSharedPreferences("RATER", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("NO THANKS", true);
editor.apply();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Rate This App");
builder.setMessage("You really seem to like this app, "
+ "since you have already used it %totalLaunchCount% times! "
+ "It would be great if you took a moment to rate it.")
.setPositiveButton("Rate Now", dialogClickListener)
.setNegativeButton("Latter", dialogClickListener)
.setNeutralButton("No,thanks", dialogClickListener).show();
}
//End dialog box Function for rating app.
}
here is my code as a function for 10 days.
I made the initial value current time - 11 days to make sure it will run first time app launches
public void dialogEvery10Days() {
Long duration = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getLong("duration", System.currentTimeMillis()-TimeUnit.DAYS.toMillis(11));
if (System.currentTimeMillis()-duration > TimeUnit.DAYS.toMillis(10)) {
// inflateDialog is a function containing the functionality of popping up the dialog
Dialog dialog = inflateDialog(R.layout.dialog_layout);
getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.edit()
.putLong("duration", System.currentTimeMillis())
.apply();
}
}
Related
I would like to know how I can store a boolean with SharedPreferences and disable a button. If you restart the app, the button should remain disabled.
Here is my Code, but something is wrong.
public class Pass extends AppCompatActivity implements View.OnClickListener {
private Button btn1;
private EditText text1;
private SharedPreferences speicher;
private SharedPreferences.Editor editor;
final boolean enabled = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pass);
btn1 = (Button) findViewById(R.id.button);
btn1.setOnClickListener(this);
text1 = (EditText) findViewById(R.id.editText);
text1.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
speicher = getApplicationContext().getSharedPreferences("Daten", 0);
editor = speicher.edit();
speicher = getSharedPreferences("Daten", 0);
speicher.getBoolean("Data1", enabled);
}
public void onClick (View view){
if (text1.getText().toString().equals("pass")){
AlertDialog ad = new AlertDialog.Builder(this).create();
ad.setMessage("Great");
ad.show();
Intent intent = new Intent(this,Popup.class);
startActivity(intent);
btn1.setEnabled(enabled);
editor.putBoolean("Data1", enabled);
editor.commit();
}else{
String message = "Wrong";
Toast.makeText(this,message, Toast.LENGTH_LONG).show();
}
}
}
I hope you can help me.
since
Strecki
You're not checking the condition to enable or disable button that you're getting from SharedPreference. Do something like this:
btn1.setEnabled(speicher.getBoolean("Data1", enabled));
Try this one it will work.
Remove this line on your code. Because initialized again here.
"speicher = getSharedPreferences("Daten", 0);"
You have to try like this
SharedPreferences speicher = getApplicationContext().getSharedPreferences("Daten", 0);
SharedPreferences.Editor editor = speicher.edit();
Store the value like this
editor.putBoolean("Data1", true); editor.commit();
Get value like this
Boolean result = speicher.getBoolean("Data1", false); //false is default value.
I want to add pictures to my favorite activity when a user tap on a picture. So far I'm able to get the data and display it but for some reason whenever I tap on an image it displays the favorited image, however, when I recheck the favorite activity by clicking on it, it shows empty.
Here's the little flow chart.
imageOnTap is implemented on RecyclerAdapter class. I have my Favorite activity and MainActivity.Any help would be appreciated. Thanks
Here's my MyRecyclerAdapter class
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.nameTxt.setText(albums.get(position).getName());
holder.img.setImageResource(albums.get(position).getImage());
//listener
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v, int pos) {
Toast.makeText(c,albums.get(pos).getName() + " ,added to favorite ",Toast.LENGTH_SHORT).show();
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("favorite",albums.get(pos).getImage());
editor.commit();
Toast.makeText(c,albums.get(pos).getName() + " ,added to favorite ",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(c, favorite.class);
// intent.putExtra(Intent.EXTRA_TEXT, albums.get(pos).getImage());
c.startActivity(intent);
}
});
}
Here's my favorite activity
public class favorite extends AppCompatActivity {
int favImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorite);
ImageView displayImage = (ImageView) findViewById(R.id.movieImage);
SharedPreferences settings = getSharedPreferences(PREFS_NAME,0);
displayImage.setImageResource(settings.getInt("Favorite", 0));
// Intent intent = getIntent();
// if (intent.hasExtra(Intent.EXTRA_TEXT)) {
// favImage = intent.getIntExtra(Intent.EXTRA_TEXT,image);
// displayImage.setImageResource(favImage);
//
// }
}
}
Here's my MainActivity
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_favorite) {
Intent intent = new Intent(this,favorite.class);
startActivity(intent);
}
If you are checking favourite activity from nav menu then it will not display anything afterall you are not passing any intent extras in it. Is it being display when you click the image? Are you getting intent params null here?
Use those preferences:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(ctx.getApplicationContext());
In your case it might be different activities observe different areas of settings.
THAT IS:
use:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(ctx.getApplicationContext());
SharedPreferences.Editor editor = settings.edit();
editor.putInt("favorite",albums.get(pos).getImage());
editor.commit();
instead of:
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("favorite",albums.get(pos).getImage());
editor.commit();
AND
this:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(ctx.getApplicationContext());
displayImage.setImageResource(settings.getInt("Favorite", 0));
instead of:
SharedPreferences settings = getSharedPreferences(PREFS_NAME,0);
displayImage.setImageResource(settings.getInt("Favorite", 0));
I want create content application, i load data from JSON and when users click on button save this content into SQLitedatabase.
I want use this library for button.
And for checkable button, I use this code
I write below codes, when click on button i save this content into SQLitedatabase, but i can't save button sate into SharedPreferences!
When click on button (boolean checked) button is turn on, and when click again on the button turn off this button.
I want when click on button, turn on this button and save in SharedPreferences and when go to other activity and again back this activity, see turn on this button NOT turn off. when click again this button at that time turn off button!
Activity codes:
private ShineButton postShow_favPost;
private String favData = "FavPrefsList";
private Boolean favState;
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.post_show_page);
bindActivity();
//Give Data
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
title = bundle.getString("title");
image = bundle.getString("image");
content = bundle.getString("content");
dateTime = bundle.getString("dateTime");
author = bundle.getString("author");
category = bundle.getString("category");
categoryID = bundle.getString("categoryID");
}
mAppBarLayout.addOnOffsetChangedListener(this);
//// Save Fav state
final SharedPreferences saveFavPrefs = getSharedPreferences(favData, MODE_PRIVATE);
final SharedPreferences.Editor editor = saveFavPrefs.edit();
favState = saveFavPrefs.getBoolean("isChecked", false);
postShow_favPost = (ShineButton) mToolbar.findViewById(R.id.post_FavImage);
postShow_favPost.init(this);
postShow_favPost.setOnCheckStateChangeListener(new ShineButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(View view, boolean checked) {
if (checked == true) {
editor.putBoolean("isChecked", true);
editor.commit();
//////////// Database
favDB = new FavHelper(context);
long addNewFAV = favDB.insertFAV(title, image, content, dateTime, author, category);
if (addNewFAV < 0) {
TastyToast.makeText(context, "Not save in database", TastyToast.LENGTH_LONG, TastyToast.ERROR);
} else {
TastyToast.makeText(context, "Save in database", TastyToast.LENGTH_LONG, TastyToast.SUCCESS);
}
////////////////////
} else {
editor.putBoolean("isChecked", false);
editor.commit();
Toast.makeText(context, "Checked False", Toast.LENGTH_SHORT).show();
}
}
});
How can i fix my issue ?
Well you need to save the state when you click the button.
For example :
postShow_favPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (postShow_favPost.isChecked()){
editor.putBoolean("isChecked", true);
editor.apply();
}
else{
editor.putBoolean("isChecked", false);
editor.apply();
}
}
});
Then you have to load it in your onCreate():
#Override
protected void onCreate(Bundle savedInstanceState)
{
SharedPreferences saveFavPrefs = getSharedPreferences(favData, MODE_PRIVATE);;
postShow_favPost.setChecked(saveFavPrefs.getBoolean("isChecked", true));
}
Maybe this example will help you.
EDIT
Ok let's presume in your f function you just finished doing whatever you're doing to your database, after that, set the state as on or off, let's say you want on.
So :
public void loadPrefs(SharedPreferences prefs){
favState = prefs.getBoolean("isChecked",false);
}
public void f(SharedPreferences.Editor editor){
//database stuff
editor.putBoolean("isChecked", true); // or false
editor.apply();
loadPrefs(prefs);
// in here your state will be saved for your button as soon as you
finish working with your database, after that in your onResume() you
may change that state to false(off) in case you want it just for that post
}
I am using shared preferences but my code is not working. I don't know what's wrong with it. Am I implementing something wrong?
My main java activity(relevant bit of code) is:
public class MainActivity extends AppCompatActivity {
private String s;
public static final String subjectKey = "SubjectID";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SharedPreferences sharedPreferences = getSharedPreferences(subjectKey, Context.MODE_PRIVATE);
TextView calc_monday = (TextView) findViewById(R.id.monday_calc);
calc_monday.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View v){
CustomDialogClass cdd = new CustomDialogClass(MainActivity.this);
cdd.show();
TextView text1 = (TextView) cdd.findViewById(R.id.Subject_ID);
String text = sharedPreferences.getString(subjectKey, " ");
if(text != " ")
{
text1.setText(text); /* Edit the value here*/
}
TextView text2 = (TextView) cdd.findViewById(R.id.Room_ID);
text2.setText("6 (SEECS)");
TextView text3 = (TextView) cdd.findViewById(R.id.Time_ID);
text3.setText("09:00am - 09:50am");
}
}
);
calc_monday.setOnLongClickListener(
new Button.OnLongClickListener() {
public boolean onLongClick(View v) {
SettingDialogClass SDC = new SettingDialogClass(MainActivity.this);
SDC.show();
EditText texii = (EditText) SDC.findViewById(R.id.set_Subject_ID);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(subjectKey, texii.getText().toString());
editor.apply();
return true;
}
}
);
Basically I want that when I longClick a textbox (calc_monday), a dialog box should appear which appears. Now I should be able to write something on the EditText field which appears on this dialog box. Whatever I write should be stored and then displayed when I SINGLE CLICK on the same textbox (calc_monday)
Please see the 2 methods: onClick and onLongClick to understand.
The code is not working, i.e the text I write on EditText field on onLongCLick dialog box is not being displayed when I single click on the textbox.
What's wrong with the code
When you long press calc_monday, it just show your custom dialog with empty value for EditText. To save your text when input in EditText, create a button in your custom dialog, and call onClickListener action for this button, then save value to SharePreferences.
calc_monday.setOnLongClickListener(
new Button.OnLongClickListener() {
public boolean onLongClick(View v) {
SettingDialogClass SDC = new SettingDialogClass(MainActivity.this);
EditText texii = (EditText) SDC.findViewById(R.id.set_Subject_ID);
Button btnSave = (Button)SDC.findViewById(R.id.your_custom_button);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(subjectKey, texii.getText().toString());
editor.apply();
SDC.dismiss();
}
});
SDC.show();
return true;
}
}
);
I think it's should be :
String text = sharedPreferences.getString("Name", " ");
Try these methods for saving and loading Strings with preferences:
//save prefs
public void savePrefs(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
//get prefs
public String loadPrefs(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String data = sharedPreferences.getString(key, value);
return data;
}
You can call the load method like this:
subjectKey = loadPrefs("YouCanNameThisAnything", subjectKey);
And you can call the save method like this:
savePrefs("YouCanNameThisAnything", subjectKey);
More details on how to use shared preferences is also available in the documentation here:
http://developer.android.com/reference/android/content/SharedPreferences.html
//create and initialize the intance of shared preference
SharedPreferences sharedPreferences = getSharedPreferences("Session", MODE_PRIVATE);
//save a string
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putString(subjectKey , texii.getText().toString());
edit.commit();
//retrieve the string
String subject = sharedPreferences.getString(subjectKey, "");
I am new in Android, and got a task to develop a small project to submit in my college, i have tried my best but now i need some help
Let me tell you first, what i am trying to do ?
I have two Activities, MainActivity and AccountActivity
In MainActivity i am using button to switch to AccountActivity
In AccountActivity i am trying to store strBalance value in SharedPreference but whenever i do click on back button and then again come to AccountActivity always getting "1000" not that value which i have stored in SharedPreference.
Here is the complete code of AccountActivity.java:-
public class AccountActivity extends Activity {
EditText editAmount;
int strAmount;
Button btnPayment;
TextView textBalance;
int strBalance;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
editAmount = (EditText) findViewById(R.id.editAmt);
btnPayment = (Button) findViewById(R.id.btnPay);
textBalance = (TextView) findViewById(R.id.textBalance);
strBalance = 1000;
textBalance.setText("Your current balance is: $ "+strBalance);
btnPayment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();
strAmount = Integer.parseInt(editAmount.getText().toString().trim()); // user input
if(strAmount>strBalance) {
Toast.makeText(AccountActivity.this, "You don't have enough balance", Toast.LENGTH_SHORT).show();
}
else
{
strBalance = strBalance - strAmount; // 1000 - 500 = 500
textBalance.setText("Your current balance is: $ "+strBalance);
Log.v("strBalance", String.valueOf(strBalance)); // 500
editor.putInt("key_balance", strBalance);
editor.commit();
}
}
});
}
}
Do this,
SharedPreferences sharedPreferences = getSharedPreferences("MyPref", MODE_PRIVATE);
int any_variable = sharedPreferences.getInt("key_balance", 0);
Remove initialisation and do this in your onCreate and then use the new variable as you strBalance.
-Check Both the preference and key name are same or not.
You did not retrieve data from SharedPreferences
Write your code in onResume() like this:
#Override
protected void onResume() {
super.onResume();
// SharedPreferences retrieval code
}
To know more about SharedPreferences check this link.
This should work fine:
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
if (pref.getInt("key_balance", 1000) != null) {
strBalance = pref.getInt("key_balance",1000);
} else {
strBalance = 1000;
}
Instead of
strBalance = 1000;