how disable button on click when the application first time runs - java

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); ;
}

Related

Wrong calculation after using sharedpreferences

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));
}

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()
})

Simple EditText Alert dialog ran before main activity created

Trying to display simple edit text dialog, requesting a string be provided before the rest of my application starts. Currently im trying to make it so the APIKEY of my app is request first thing, then once entered its saved a shared preference and then the dialog will not display. The current code is being reused from a old project of mine. If anybody can help point me in the right direct to making this simple dialog.
public void getapikey() {
AlertDialog.Builder adb = new AlertDialog.Builder(this);
LayoutInflater adbInflater = LayoutInflater.from(this);
View eulaLayout = adbInflater.inflate(R.layout.custom_dialog, null);
editText = (EditText) eulaLayout.findViewById(R.id.editText1);
adb.setView(eulaLayout);
adb.setTitle("Api Key");
adb.setMessage("Welcome to the app, Please input your APIkey below");
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
// CheckBox Confirm for Alert Dialog
public void onClick(DialogInterface dialog, int which) {
String value = editText.getText().toString();
if (editText !=null)
//Unsure about this part above and below
editText = "0"
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("apikey", value);
// Commit the edits!
editor.commit();
return;
}
});
// Preferences For Alert Dialog
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String apikey = settings.getString("apikey", "0");
if (apikey!=null )
adb.setIcon(R.drawable.ic_launcher);
adb.show();
}
}
RECOMMENDED CHANGES
public class Welcome extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
public EditText editText;
public String value;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getapikey();
}
public void getapikey() {
// Alert Dialog
AlertDialog.Builder adb = new AlertDialog.Builder(this);
LayoutInflater adbInflater = LayoutInflater.from(this);
View eulaLayout = adbInflater.inflate(R.layout.custom_dialog, null);
// dontShowAgain = (CheckBox) eulaLayout.findViewById(R.id.checkBox1);
editText = (EditText) eulaLayout.findViewById(R.id.editText1);
adb.setView(eulaLayout);
adb.setTitle("Api Key");
adb.setMessage("Welcome to the app, Please input your APIkey below");
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//String checkBoxResult = "NOT checked";
String value = editText.getText().toString();
// if (dontShowAgain.isChecked())
// checkBoxResult = "checked";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
//editor.putString("skipMessage", checkBoxResult);
editor.putString("apikey", value);
// Commit the edits!
editor.commit();
return;
}
});
// Preferences For Alert Dialog
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
//String skipMessage = settings.getString("skipMessage", "NOT checked");
String apikey = settings.getString("apikey", value);
if(!value.equals(""))
adb.setIcon(R.drawable.ic_launcher);
adb.show();
setContentView(R.layout.splash_screen);
Thread splashThread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
// changed from 5000 to 4000 11.29
while (waited < 3000) {
sleep(100);
waited += 100;
}
} catch (InterruptedException e) {
// do nothing
} finally {
Intent i = new Intent();
i.setClassName("com.example.app",
"com.example.app.CardsTesting");
startActivity(i);
finish();
}
}
};
splashThread.start();
}
}
Still doesnt save the preference after the first time then never displays
//try this one i think it may be work
SharedPreferences settings = PreferenceManager.getSharedPreferences(PREFS_NAME, 0);

How can I make my android app have SharedPreferences as just one set of preferences, so that I can control it and clear the preferences with a button

I am trying to have SharedPreferences once and control it to different methods rather than having different SharedPreferences in different methods. I have SharedPreferences in the onCreate, LoadPreferences, SavePreferences and ClearTextViews methods. I want to make it so that I have preferences saved to the TextViews from entered text in the EditText and then be able to clear them all with a button. Please help me if you can. Here is the relevant code:
public class notesActivity extends Activity implements OnClickListener
{
Button saveNote;
Button clearText;
EditText note;
TextView textSavedNote1, textSavedNote2, textSavedNote3, textSavedNote4, textSavedNote5, textSavedNote6;
SharedPreferences spNote;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);
saveNote = (Button)this.findViewById(R.id.saveNotes);
saveNote.setOnClickListener(this);
clearText = (Button)this.findViewById(R.id.clearAllText);
clearText.setOnClickListener(this);
textSavedNote1 = (TextView)findViewById(R.id.stringSavedNote1);
textSavedNote2 = (TextView)findViewById(R.id.stringSavedNote2);
textSavedNote3 = (TextView)findViewById(R.id.stringSavedNote3);
textSavedNote4 = (TextView)findViewById(R.id.stringSavedNote4);
textSavedNote5 = (TextView)findViewById(R.id.stringSavedNote5);
textSavedNote6 = (TextView)findViewById(R.id.stringSavedNote6);
note = (EditText)this.findViewById(R.id.notes);
spNote = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = spNote.edit();
edit.putString("note"+saveNote,note.getText().toString());
edit.commit();
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Goes back to the home screen
case R.id.item1: Intent i = new Intent(notesActivity.this, UserSettingActivity.class);
startActivity(i);
case R.id.item2:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
// Refreshes the page.
case R.id.item3:
finish();
startActivity(getIntent());
default:
return super.onOptionsItemSelected(item);
}
}
public void onClick (View v){
if(v==saveNote){
SavePreferences("NOTE1", note.getText().toString());
LoadPreferences();
note.setText("");
if(textSavedNote1.getText().toString().length()>0){
SavePreferences("NOTE2", note.getText().toString());
LoadPreferences();
note.setText("");
}
else{
}
}
else if(v==clearText){
ClearTextViews();
}
}
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedNote1 = sharedPreferences.getString("NOTE1", "");
String strSavedNote2 = sharedPreferences.getString("NOTE2", "");
String strSavedNote3 = sharedPreferences.getString("NOTE3", "");
String strSavedNote4 = sharedPreferences.getString("NOTE4", "");
String strSavedNote5 = sharedPreferences.getString("NOTE5", "");
String strSavedNote6 = sharedPreferences.getString("NOTE6", "");
textSavedNote1.setText(strSavedNote1);
textSavedNote2.setText(strSavedNote2);
textSavedNote3.setText(strSavedNote3);
textSavedNote4.setText(strSavedNote4);
textSavedNote5.setText(strSavedNote5);
textSavedNote6.setText(strSavedNote6);
}
private void ClearTextViews(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
}
}
There are some links that can be helpfull
How to use SharedPreferences in Android to store, fetch and edit values
http://developer.android.com/reference/android/content/SharedPreferences.html
Examples
How to use SharedPreferences
http://android-er.blogspot.com.br/2011/01/example-of-using-sharedpreferencesedito.html
Try the code below.
/*I have added one more button, on click on that button i have set call clearText function and set all text empty, each time before clicking on save button you click first clear button then next value will be inserted in next textview.*/
public class SharedPreferenceJustOneSetOfPreferencesActivity extends Activity implements OnClickListener{
private Button saveNote,clearText,ClearAll;
static TextView textSavedNote1, textSavedNote2, textSavedNote3, textSavedNote4, textSavedNote5, textSavedNote6;
private EditText note;
private SharedPreferences spNote;
private static final String TAG = SharedPreferenceJustOneSetOfPreferencesActivity.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initView();
saveInPreference();
}
private void initView() {
textSavedNote1 = (TextView)findViewById(R.id.textSavedNote1);
textSavedNote2 = (TextView)findViewById(R.id.textSavedNote2);
textSavedNote3 = (TextView)findViewById(R.id.textSavedNote3);
textSavedNote4 = (TextView)findViewById(R.id.textSavedNote4);
textSavedNote5 = (TextView)findViewById(R.id.textSavedNote5);
textSavedNote6 = (TextView)findViewById(R.id.textSavedNote6);
note = (EditText)findViewById(R.id.note);
saveNote = (Button)findViewById(R.id.saveNote);
clearText = (Button)findViewById(R.id.clearText);
ClearAll = (Button)findViewById(R.id.ClearAll);
saveNote.setOnClickListener(this);
clearText.setOnClickListener(this);
ClearAll.setOnClickListener(this);
}
private void saveInPreference() {
spNote = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = spNote.edit();
edit.putString("note"+saveNote,note.getText().toString());
edit.commit();
}
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.layout.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case R.id.item1: Intent i = new Intent(SharedPreferenceJustOneSetOfPreferencesActivity.this, UserSettingActivity.class);
startActivity(i);
case R.id.item2:
Intent intent = new Intent(SharedPreferenceJustOneSetOfPreferencesActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
case R.id.item3:
finish();
startActivity(getIntent());
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View view) {
if (view == saveNote) {
String textvedNote1 =textSavedNote1.getText().toString();
String textvedNote2= textSavedNote2.getText().toString();
String textvedNote3 =textSavedNote3.getText().toString();
String textvedNote4= textSavedNote4.getText().toString();
String textvedNote5 =textSavedNote5.getText().toString();
String textvedNote6= textSavedNote6.getText().toString();
if (textvedNote1.equals("")) {
SavePreferences("NOTE1", note.getText().toString());
Log.e(TAG,"textvedNote1: Inside "+textvedNote1.length());
LoadPreferences();
note.setText("");
}else if (textvedNote2.equals("")&& !textvedNote1.equals("")) {
SavePreferences("NOTE2", note.getText().toString());
Log.e(TAG,"textvedNote2: Inside "+textvedNote1.length());
LoadPreferences();
note.setText("");
} else if (textvedNote3.equals("")&& !textvedNote2.equals("")) {
Log.e(TAG,"textvedNote3: Inside "+textvedNote2.length());
SavePreferences("NOTE3", note.getText().toString());
LoadPreferences();
note.setText("");
} else if (textvedNote4.equals("")&& !textvedNote3.equals("")) {
Log.e(TAG,"textvedNote4: Inside "+textvedNote3.length());
SavePreferences("NOTE4", note.getText().toString());
LoadPreferences();
note.setText("");
} else if (textvedNote5.equals("")&& !textvedNote4.equals("")) {
Log.e(TAG,"textvedNote5: Inside "+textvedNote4.length());
SavePreferences("NOTE5", note.getText().toString());
LoadPreferences();
note.setText("");
} else if (textvedNote6.equals("")&& !textvedNote5.equals("")) {
SavePreferences("NOTE6", note.getText().toString());
Log.e(TAG,"textvedNote6: Inside "+textvedNote5.length());
LoadPreferences();
note.setText("");
}
} else if (view == clearText) {
ClearTextViews();
}else if (view == ClearAll){
ClearTextViews();
textSavedNote1.setText("");
textSavedNote2.setText("");
textSavedNote3.setText("");
textSavedNote4.setText("");
textSavedNote5.setText("");
textSavedNote6.setText("");
}
}
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedNote1 = sharedPreferences.getString("NOTE1", "");
String strSavedNote2 = sharedPreferences.getString("NOTE2", "");
String strSavedNote3 = sharedPreferences.getString("NOTE3", "");
String strSavedNote4 = sharedPreferences.getString("NOTE4", "");
String strSavedNote5 = sharedPreferences.getString("NOTE5", "");
String strSavedNote6 = sharedPreferences.getString("NOTE6", "");
if (!strSavedNote1.equals("")) {
Log.e(TAG,"LoadPreferences1: "+strSavedNote1);
textSavedNote1.setText(strSavedNote1);
} else if (!strSavedNote2.equals("")) {
Log.e(TAG,"LoadPreferences2: "+strSavedNote2);
textSavedNote2.setText(strSavedNote2);
} else if (!strSavedNote3.equals("")) {
Log.e(TAG,"LoadPreferences3: "+strSavedNote3);
textSavedNote3.setText(strSavedNote3);
} else if (!strSavedNote4.equals("")) {
textSavedNote4.setText(strSavedNote4);
} else if (!strSavedNote5.equals("")) {
textSavedNote5.setText(strSavedNote5);
} else if (!strSavedNote6.equals("")) {
textSavedNote6.setText(strSavedNote6);
}
}
private void ClearTextViews(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
}
}

Open tutorial on first run doesn't work properly

I have a tutorial in my app showing up when a user runs it for the first time
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
if (firstRun == true) {
Intent tut = new Intent(MainActivity.this, Tutorial.class);
startActivity(tut);
firstRun = false;
}
}
}, 200);
I have delayed it because without a delay i just get a black screen (the interface doesn't have the time to load)
But doing so i get the Tutorial.class opened many times, what am i doing wrong?
EDIT:
Here is some more code, i won't paste all of it since it would be only too long to read and it wouldn't be relevant to the problem
I save my preferences like this
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("Counter1", counter);
editor.putInt("Counter2", counter2);
editor.putBoolean("FirstRun", firstRun);
editor.putString("Label1", label1S);
editor.putString("Label2", label2S);
editor.commit();
}
protected void onPause(){
super.onPause();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("Counter1", counter);
editor.putInt("Counter2", counter2);
editor.commit();
}
Here is how i restore them inside the onCreate();
// Restore previous settings and data
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
int counterRestored = settings.getInt("Counter1", 0);
int counter2Restored = settings.getInt("Counter2", 0);
boolean firstRunRestored = settings.getBoolean("FirstRun", true);
String label1Restored = settings.getString("Label1", "Counter 1");
String label2Restored = settings.getString("Label2", "Counter 2");
counter = counterRestored;
counter2 = counter2Restored;
firstRun = firstRunRestored;
label1S = label1Restored;
label2S = label2Restored;
renameLabel();
calculateTotal();
This is my second activity Tutorial.class
public class Tutorial extends MainActivity{
ImageButton btnSkip, btnSkip2, btnNext, btnNext2;
RelativeLayout tutorial, tutPage1, tutPage2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tutorial);
btnSkip = (ImageButton) findViewById(R.id.btn_skip);
btnNext = (ImageButton) findViewById(R.id.btn_next);
btnSkip2 = (ImageButton) findViewById(R.id.btn_skip2);
btnNext2 = (ImageButton) findViewById(R.id.btn_next2);
tutorial = (RelativeLayout) findViewById(R.id.tutorial);
tutPage1 = (RelativeLayout) findViewById(R.id.page1);
tutPage2 = (RelativeLayout) findViewById(R.id.page2);
btnSkip.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
finish();
}
});
btnSkip2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
finish();
}
});
btnNext.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
tutPage1.setVisibility(View.GONE);
tutPage2.setVisibility(View.VISIBLE);
}
});
btnNext2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
tutPage1.setVisibility(View.VISIBLE);
tutPage2.setVisibility(View.GONE);
tutorial.setVisibility(View.VISIBLE);
finish();
}
});
}
}
why don't you try
if(firstRun){
firstRun = false;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Intent tut = new Intent(MainActivity.this, Tutorial.class);
startActivity(tut);
}
}
}, 200);
}
The value of firstRun will not be stored persistantly over several runs.
You should store this value in SharedPreferences so that it will retain its value even after the app has been closed. You can find a tutorial on how to use SharedPreferences here.

Categories

Resources