Wrong calculation after using sharedpreferences - java

I'm building an app to check prime numbers and display them. the user need to be able to save the number and load it upon restart of the app.
I have problem when retrieving the saved int from Sharedprefrences. the codes saves the int and loads it on the "loaddata" function. But when I start checking if the saved in is a primenumber, the code jumps 2 primenumbers. Eg if I save "11", the next primenumber should be "13" but it jumps to "19".
Would be great if someone could point into the right direction since i'm a bit of newbie.
public class MainActivity extends AppCompatActivity {
private TextView textView;
private EditText editText;
private Button applyPrimeButton;
private Button saveButton;
private Button loadButton;
public static final String SHARED_PREFS = "sharedPrefs";
int max = 500;
int j = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textview);
editText = (EditText) findViewById(R.id.edittext);
applyPrimeButton = (Button) findViewById(R.id.apply_prime_button);
saveButton = (Button) findViewById(R.id.save_button);
loadButton = (Button) findViewById(R.id.load_button);
applyPrimeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int i = j; i <= max; i++) {
if (isPrimeNumber(i)) {
textView.setText(i+"");
j = i+1;
break;
}
}
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveData();
}
});
loadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadData();
}
});
}
public boolean isPrimeNumber(int nummer) {
for (int i = 2; i <= nummer / 2; i++) {
if (nummer % i == 0) {
return false;
}
}
return true;
}
public void saveData() {
SharedPreferences sp = getSharedPreferences(SHARED_PREFS, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
int nummer = Integer.parseInt(textView.getText().toString());
editor.putInt("prime_save", nummer);
editor.commit();
Toast.makeText(this, "Data saved", Toast.LENGTH_SHORT).show();
}
public void loadData() {
SharedPreferences sp = getSharedPreferences(SHARED_PREFS, Activity.MODE_PRIVATE);
int nummer = sp.getInt("prime_save",0);
textView.setText(String.valueOf(nummer));
}
}

Several issues:
You are not updating j to the correct value when loading data, and instead relying on what you are displaying in the textview.
To find prime number, it is enough to check until the square root of the original number and not half of it.
Try this:
applyPrimeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(j<max ){
if (isPrimeNumber(j)) {
textView.setText(j+"");
j++;
}
}
}
});
public void saveData() {
SharedPreferences sp = getSharedPreferences(SHARED_PREFS, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("prime_save", j);
editor.commit();
Toast.makeText(this, "Data saved", Toast.LENGTH_SHORT).show();
}
public void loadData() {
SharedPreferences sp = getSharedPreferences(SHARED_PREFS, Activity.MODE_PRIVATE);
int nummer = sp.getInt("prime_save",0);
j = nummer;
textView.setText(String.valueOf(nummer));
}

Related

Could we define unknown amount of clickable texts which have different outputs in for loop?

I want all ClickableSpans to have toasts show their own text. But whatever I write in Toast in onClick in for loop, all ClickableSpans show same Toast output. Briefly, I just want ClickableSpans to show different Toasts in for loop. How can I do it? I want all words have clickable. And when all words are clicked, they do different thing. Thank you for your help.
public class MainActivity extends AppCompatActivity {
private String[] textArray;
private String text = "1981 senesinde kuantum bilgisayar fikrini Paul Beniof, Max Planck’ın " +
"enerjinin sürekli olmadan kesikli değerlerde yer alan m, n, k enerji kuantlarıyla ";
private Chronometer chronometer;
private int hold=0;
private TextView textView;
private int i;
private MediaPlayer player;
private long pauseOffset;
private boolean running;
private boolean start=true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textArray = text.split(" ");
final SpannableString ss = new SpannableString(text);
chronometer = findViewById(R.id.chronometer);
chronometer.setFormat("Time: %s");
chronometer.setBase(SystemClock.elapsedRealtime());
textView = findViewById(R.id.text_view);
textView.setText(text);
textView.setTextColor(Color.BLACK);
final ClickableSpan[] clickableSpans = new ClickableSpan[textArray.length];
for(i = 0; i<textArray.length; i++){
clickableSpans[i] = new ClickableSpan() {
#Override
public void onClick(View widget) {
Toast.makeText(MainActivity.this, "", Toast.LENGTH_LONG).show();
}
#Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setColor(Color.BLACK);
ds.setUnderlineText(false);
}
};
final boolean[] c = {true};
chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
#Override
public void onChronometerTick(Chronometer chronometer) {
if ((SystemClock.elapsedRealtime() - chronometer.getBase()) >= 5000&& c[0]) {
for(int i=0; i<textArray.length;i++){
ss.setSpan(clickableSpans[i], hold, hold + textArray[i].length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
hold+=textArray[i].length();
hold++;
}
start=false;
hold=0;
textView.setText(ss);
textView.setMovementMethod(LinkMovementMethod.getInstance());
if (running) {
chronometer.stop();
pauseOffset = SystemClock.elapsedRealtime() - chronometer.getBase();
running = false;
}
c[0]=false;
}
}
});
hold=0;
}
i=0;
}
public void play(View v) {
if(start){
if (!running) {
chronometer.setBase(SystemClock.elapsedRealtime() - pauseOffset);
chronometer.start();
running = true;
}
}
}
public void stop(View v) {
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}

I am making a quiz app when i pressing the answer A,B,C,D it was not showing the next one

I am making a quiz app when I pressing the answer it was not showing the next question directly it was going to done activity where the score of the quiz will be displayed. Please tell me what to do and the changes i have to made for it. Please tell me in detail and which line the problem causes, because I am still learning, plz And also suggest me some improvements.
public class Playing extends AppCompatActivity implements View.OnClickListener {
final static long INTERVAL = 1000; // 1sec = 1000
final static long TIMEOUT = 7000; // 7000 = 7sec
int progressValue = 0;
CountDownTimer mCountDown;
int index = 0, score = 0, thisQuestion = 0, totalQuestion, correctAnswer;
ProgressBar progressBar;
ImageView question_image;
Button btnA, btnB, btnC, btnD;
TextView txtScore, txtQuestionNum, question_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playing);
//View
txtScore = (TextView) findViewById(R.id.txtScore);
txtQuestionNum = (TextView) findViewById(R.id.txtTotalQuestion);
question_text = (TextView) findViewById(R.id.question_text);
question_image = (ImageView) findViewById(R.id.question_image);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnA = (Button) findViewById(R.id.btnAnswerA);
btnB = (Button) findViewById(R.id.btnAnswerB);
btnC = (Button) findViewById(R.id.btnAnswerC);
btnD = (Button) findViewById(R.id.btnAnswerD);
btnA.setOnClickListener(this);
btnB.setOnClickListener(this);
btnC.setOnClickListener(this);
btnD.setOnClickListener(this);
}
#Override
public void onClick(View view) {
mCountDown.cancel();
if (index < totalQuestion) //still have question in List
{
Button clickedButton = (Button) view;
if (clickedButton.getText().equals(Common.questionList.get(index).getCorrectAnswer())) {
//Choose correct answer
score += 10;
correctAnswer++;
showQuestion(++index); //next question
} else {
//Choose wrong answer
Intent intent = new Intent(this, Done.class);
Bundle dataSend = new Bundle();
dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL", totalQuestion);
dataSend.putInt("CORRECT", correctAnswer);
intent.putExtras(dataSend);
startActivity(intent);
finish();
}
}
}
private void showQuestion(int index) {
if (index < totalQuestion) {
thisQuestion++;
txtQuestionNum.setText(String.format(Locale.getDefault(), "%d / %d", thisQuestion, totalQuestion));
progressBar.setProgress(0);
progressValue = 0;
if (Common.questionList.get(index).getIsImageQuestion().equals("true")) {
//if is image
Picasso.get().load(Common.questionList.get(index).getQuestion()).into(question_image);
question_image.setVisibility(View.VISIBLE);
question_text.setVisibility(View.INVISIBLE);
} else {
question_text.setText(Common.questionList.get(index).getQuestion());
//If question is text,we will set image to invisible
question_image.setVisibility(View.INVISIBLE);
question_text.setVisibility(View.VISIBLE);
}
btnA.setText(Common.questionList.get(index).getAnswerA());
btnB.setText(Common.questionList.get(index).getAnswerB());
btnC.setText(Common.questionList.get(index).getAnswerC());
btnD.setText(Common.questionList.get(index).getAnswerD());
mCountDown.start(); //Start timer
} else {
//If it is final question
Intent intent = new Intent(this, Done.class);
Bundle dataSend = new Bundle();
dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL", totalQuestion);
dataSend.putInt("CORRECT", correctAnswer);
intent.putExtras(dataSend);
startActivity(intent);
finish();
}
}
#Override
protected void onResume() {
super.onResume();
totalQuestion = Common.questionList.size();
mCountDown = new CountDownTimer(TIMEOUT, INTERVAL) {
#Override
public void onTick(long minisec) {
progressBar.setProgress(progressValue);
progressValue++;
}
#Override
public void onFinish() {
mCountDown.cancel();
showQuestion(++index);
}
};
showQuestion(index);
}
}
There is no onClickListener within your Activity. I would recommend creating a "next()" function, and then, for each of the buttons, do something along the lines of:
btn.setOnClickListener(new View.OnClickListener(){
next()
})

increment and save incrementation in SharedPreferences

I have a simple scenario but can't seem to wrap my head around it.
I want to save a incremented value as a int to SharedPreferences every time a user tap on a item, let me show what I have:
int counter = 0;
mBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
counter++;
SharedPreferences shareOpenClose = getSharedPreferences("Counter", Context.MODE_PRIVATE);
SharedPreferences.Editor editorOpenClose = shareOpenClose.edit();
editorOpenClose.putInt("count", counter);
editorOpenClose.apply();
SharedPreferences getCount = getSharedPreferences("Counter", Context.MODE_PRIVATE);
int getCountAmmount = getCount.getInt("count", 0);
if (getCountAmmount>3){
Toast.makeText(c, "success!", Toast.LENGTH_SHORT).show();
}
}
});
So, when I close the activity and open it again the counter will be reset to zero and the first save to SharedPreferences back to 0. If I keep the activity open and test this it work and I get the toast as expected.
Can someone please point out what I'm doing wrong?
Because you never set the counter back when the activity loads. try this:
int counter = 0;
onCreate(...){
SharedPreferences countPref = getSharedPreferences("Counter", Context.MODE_PRIVATE);
counter = countPref.getInt("count", 0);
}
mBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
counter++;
SharedPreferences countPref = getSharedPreferences("Counter", Context.MODE_PRIVATE);
SharedPreferences.Editor editorOpenClose = countPref.edit();
editorOpenClose.putInt("count", counter);
editorOpenClose.apply();
if (counter>3){
Toast.makeText(c, "success!", Toast.LENGTH_SHORT).show();
}
}
});
Make the following changes in your code
#Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences shareOpenClose = getSharedPreferences("Counter", Context.MODE_PRIVATE);
final SharedPreferences.Editor editorOpenClose = shareOpenClose.edit();
final int[] counter = {0};
mBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
counter[0]++;
editorOpenClose.putInt("count", counter[0]);
editorOpenClose.apply();
SharedPreferences getCount = getSharedPreferences("Counter", Context.MODE_PRIVATE);
int getCountAmmount = getCount.getInt("count", 0);
if (getCountAmmount>3){
Toast.makeText(c, "success!", Toast.LENGTH_SHORT).show();
}
}
});
}
I hope this will help you, Happy Coding

Trouble using SharedPreferences to persist data

I am trying to save the value of swipesRemaining via the SharedPreferences interface. The value of the variable does not persist. I'm not sure what I am doing wrong.
Here is the source code:
public class MainActivity extends AppCompatActivity {
private TextView swipes;
private int swipesRemaining = 11;
private static final String SWIPES = "swipes";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipes = (TextView) findViewById(R.id.textView);
loadInt();
if(savedInstanceState != null) {
swipesRemaining = savedInstanceState.getInt(SWIPES);
}
updateText(swipesRemaining);
}
public void save(View view) {
saveInt("key", swipesRemaining);
}
public void reset(View view) {
swipesRemaining = 11;
updateText(swipesRemaining);
}
public void swipe(View view) {
if(swipesRemaining > 1) {
swipesRemaining--;
updateText(swipesRemaining);
} else {
Toast toast = Toast.makeText(this, "You ran out of swipes!...Resetting", Toast.LENGTH_SHORT);
toast.show();
reset(view);
}
}
private void updateText(int swipesRemaining) {
swipes.setText("Swipes: " + swipesRemaining);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt(SWIPES, swipesRemaining );
super.onSaveInstanceState(savedInstanceState);
}
private void saveInt(String key, int value) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
private void loadInt() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
swipesRemaining = sharedPreferences.getInt("key", swipesRemaining);
Toast toast = Toast.makeText(this, "Swipes left: " + swipesRemaining, Toast.LENGTH_SHORT);
toast.show();
}
}

how disable button on click when the application first time runs

In my application I have 2 buttons.
The first button in start game and the second button in continue game.
I want to disable my second button for the first time when my application runs.
It means just for the first time my second button is disabled to onClick. How to handle this?
How can I make it understand it is the first time?
public class Menu extends Activity implements View.OnClickListener {
SharedPreferences prefs;
Editor edit;
TextView best;
private boolean flag;
public static ImageView btn1, conti, but3, but4;
static Noti_Queue noti_queue;
static Splash splash;
public static AppList applist;
public static int userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.home_activity);
flag = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("flag", false);
if (applist == null) {
applist = new AppList(this);
applist.set_identity("1");
}
if (splash == null) {
splash = new Splash(this);
splash.set_identity("1");
}
if (noti_queue == null) {
noti_queue = new Noti_Queue(this);
noti_queue.set_identity("1");
}
btn1 = (ImageView) findViewById(R.id.button1);
conti = (ImageView) findViewById(R.id.btn2);
but3 = (ImageView) findViewById(R.id.button3);
but4 = (ImageView) findViewById(R.id.button4);
btn1.setOnClickListener(this);
conti.setOnClickListener(this);
conti.setBackgroundResource(R.drawable.cont);
if (!flag) {
flag = true;
conti.setBackgroundResource(R.drawable.cont_press);}
conti.setEnabled(flag);
but3.setOnClickListener(this);
but4.setOnClickListener(this);
// giving question id
final int que_id = getIntent().getIntExtra("integer", 0);
Log.e("mhs", que_id + "");
//now lets save the que_id(now it is save to SharedPreferences
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
userId = myPrefs.getInt("userId", 0);
//let get it to show
Log.e("saved", que_id + "");
setsize();
best = (TextView) findViewById(R.id.textView1);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf");
best.setTypeface(tf, Typeface.BOLD);
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
edit = prefs.edit();
if (prefs.getInt("Best", 0) <= 0) {
edit.putInt("Best", 0);
edit.commit();
}
best.setText("بیشترین امتیاز : " + prefs.getInt("Best", 0));
}
#Override
public void onBackPressed() {
splash.Display();
splash = null;
super.onBackPressed();
}
#Override
protected void onResume() {
best.setText("بیشترین امتیاز : " + prefs.getInt("Best", 0));
super.onResume();
}
private void setsize() {
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int h = dm.heightPixels;
int w = dm.widthPixels;
h = h / 6;
w = w - ((w * 30) / 100);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(w, h);
but4.setLayoutParams(params);
but3.setLayoutParams(params);
btn1.setLayoutParams(params);
conti.setLayoutParams(params);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
if (!flag) {
flag = true;
PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean("flag", flag).commit();
conti.setEnabled(flag);
conti.setBackgroundResource(R.drawable.cont_press);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
//finishing this activity is important to exit from app
Menu.this.finish();
}
break;
case R.id.btn2:
Toast.makeText(getApplicationContext(), userId + "", Toast.LENGTH_LONG).show();
Intent intent1 = new Intent(Menu.this, ContinueActivity.class);
intent1.putExtra("integer2", userId);
startActivity(intent1);
Menu.this.finish();
break;
case R.id.button3:
Toast.makeText(getApplicationContext(), "help", Toast.LENGTH_LONG).show();
break;
case R.id.button4:
applist.Display();
break;
}
}
With the help of sharedprefrence you can achieve this for example.
SharedPreferences sharedPreferences = getSharedPreferences("myPref", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("enableButton", true);
editor.commit();
put this code for enabling Button.
SharedPreferences sharedPreferences = getSharedPreferences("myPref", MODE_PRIVATE);
flag = sharedPreferences.getBoolean("enableButton", false);
if (flag) {
conti.setEnabled(true); ;
}

Categories

Resources